Merge branch 'generateFactoryMethods' into generateTransformMethods

This commit is contained in:
Ron Buckton 2015-07-15 12:44:52 -07:00
commit 4eb12adff7
117 changed files with 34049 additions and 22876 deletions

View File

@ -119,7 +119,7 @@ var languageServiceLibrarySources = [
return path.join(serverDirectory, f);
}).concat(servicesSources);
var harnessSources = [
var harnessCoreSources = [
"harness.ts",
"sourceMapRecorder.ts",
"harnessLanguageService.ts",
@ -135,7 +135,9 @@ var harnessSources = [
"runner.ts"
].map(function (f) {
return path.join(harnessDirectory, f);
}).concat([
});
var harnessSources = harnessCoreSources.concat([
"incrementalParser.ts",
"jsDocParsing.ts",
"services/colorization.ts",
@ -622,7 +624,7 @@ task("runtests", ["tests", builtLocalDirectory], function() {
var colors = process.env.colors || process.env.color;
colors = colors ? ' --no-colors ' : ' --colors ';
tests = tests ? ' -g ' + tests : '';
var reporter = process.env.reporter || process.env.r || 'dot';
var reporter = process.env.reporter || process.env.r || 'mocha-fivemat-progress-reporter';
// timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
var cmd = host + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run;
@ -796,12 +798,13 @@ task("update-sublime", ["local", serverFile], function() {
// run this task automatically
desc("Runs tslint on the compiler sources");
task("lint", [], function() {
for(var i in compilerSources) {
var f = compilerSources[i];
function success(f) { return function() { console.log('SUCCESS: No linter errors in ' + f + '\n'); }};
function failure(f) { return function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n') }};
var lintTargets = compilerSources.concat(harnessCoreSources);
for(var i in lintTargets) {
var f = lintTargets[i];
var cmd = 'tslint -f ' + f;
exec(cmd,
function() { console.log('SUCCESS: No linter errors'); },
function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n');
});
exec(cmd, success(f), failure(f));
}
}, { async: true });

View File

@ -1,6 +1,4 @@
[![Build Status](https://travis-ci.org/Microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript)
[![Issue Stats](http://issuestats.com/github/Microsoft/TypeScript/badge/pr)](http://issuestats.com/github/microsoft/typescript)
[![Issue Stats](http://issuestats.com/github/Microsoft/TypeScript/badge/issue)](http://issuestats.com/github/microsoft/typescript)
[![npm version](https://badge.fury.io/js/typescript.svg)](http://badge.fury.io/js/typescript)
[![Downloads](http://img.shields.io/npm/dm/TypeScript.svg)](https://npmjs.org/package/typescript)

13
bin/lib.core.d.ts vendored
View File

@ -1184,3 +1184,16 @@ declare type ClassDecorator = <TFunction extends Function>(target: TFunction) =>
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}

25
bin/lib.core.es6.d.ts vendored
View File

@ -1184,6 +1184,19 @@ declare type ClassDecorator = <TFunction extends Function>(target: TFunction) =>
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
declare type PropertyKey = string | number | symbol;
interface Symbol {
@ -4759,17 +4772,6 @@ declare module Reflect {
function setPrototypeOf(target: any, proto: any): boolean;
}
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
/**
* Represents the completion of an asynchronous operation
*/
@ -4789,6 +4791,7 @@ interface Promise<T> {
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
[Symbol.toStringTag]: string;
}

114
bin/lib.d.ts vendored
View File

@ -1185,6 +1185,19 @@ declare type PropertyDecorator = (target: Object, propertyKey: string | symbol)
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
/////////////////////////////
/// IE10 ECMAScript Extensions
/////////////////////////////
@ -4755,16 +4768,11 @@ interface CanvasRenderingContext2D {
clearRect(x: number, y: number, w: number, h: number): void;
clip(fillRule?: string): void;
closePath(): void;
createImageData(imageDataOrSw: number, sh?: number): ImageData;
createImageData(imageDataOrSw: ImageData, sh?: number): ImageData;
createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createPattern(image: HTMLImageElement, repetition: string): CanvasPattern;
createPattern(image: HTMLCanvasElement, repetition: string): CanvasPattern;
createPattern(image: HTMLVideoElement, repetition: string): CanvasPattern;
createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
drawImage(image: HTMLImageElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLCanvasElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
fill(fillRule?: string): void;
fillRect(x: number, y: number, w: number, h: number): void;
fillText(text: string, x: number, y: number, maxWidth?: number): void;
@ -5922,12 +5930,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
/**
* Gets a collection of objects based on the value of the NAME or ID attribute.
* @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.
*/
getElementsByName(elementName: string): NodeList;
getElementsByName(elementName: string): NodeListOf<Element>;
/**
* Retrieves a collection of objects based on the specified element name.
* @param name Specifies the name of an element.
@ -6105,8 +6113,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
getElementsByTagName(tagname: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(tagname: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(tagname: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(tagname: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(tagname: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
/**
* Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
*/
@ -6379,6 +6387,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
scrollTop: number;
scrollWidth: number;
tagName: string;
id: string;
className: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@ -6558,8 +6568,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(name: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(name: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(name: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string, localName: string): boolean;
msGetRegionContent(): MSRangeCollection;
@ -6740,7 +6750,7 @@ interface FormData {
declare var FormData: {
prototype: FormData;
new(): FormData;
new (form?: HTMLFormElement): FormData;
}
interface GainNode extends AudioNode {
@ -7033,8 +7043,7 @@ interface HTMLAreasCollection extends HTMLCollection {
/**
* Adds an element to the areas, controlRange, or options collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Removes an element from the collection.
*/
@ -7478,14 +7487,12 @@ declare var HTMLDocument: {
interface HTMLElement extends Element {
accessKey: string;
children: HTMLCollection;
className: string;
contentEditable: string;
dataset: DOMStringMap;
dir: string;
draggable: boolean;
hidden: boolean;
hideFocus: boolean;
id: string;
innerHTML: string;
innerText: string;
isContentEditable: boolean;
@ -7572,7 +7579,7 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@ -9782,8 +9789,7 @@ interface HTMLSelectElement extends HTMLElement {
* @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.
* @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Returns whether a form will validate when it is submitted, without having to submit it.
*/
@ -12385,6 +12391,7 @@ declare var SVGDescElement: {
interface SVGElement extends Element {
id: string;
className: any;
onclick: (ev: MouseEvent) => any;
ondblclick: (ev: MouseEvent) => any;
onfocusin: (ev: FocusEvent) => any;
@ -13944,8 +13951,7 @@ interface Screen extends EventTarget {
systemXDPI: number;
systemYDPI: number;
width: number;
msLockOrientation(orientations: string): boolean;
msLockOrientation(orientations: string[]): boolean;
msLockOrientation(orientations: string | string[]): boolean;
msUnlockOrientation(): void;
addEventListener(type: "MSOrientationChange", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -14017,8 +14023,7 @@ interface SourceBuffer extends EventTarget {
updating: boolean;
videoTracks: VideoTrackList;
abort(): void;
appendBuffer(data: ArrayBuffer): void;
appendBuffer(data: ArrayBufferView): void;
appendBuffer(data: ArrayBuffer | ArrayBufferView): void;
appendStream(stream: MSStream, maxSize?: number): void;
remove(start: number, end: number): void;
}
@ -14126,33 +14131,18 @@ declare var StyleSheetPageList: {
}
interface SubtleCrypto {
decrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string, baseKey: CryptoKey, length: number): any;
deriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string, data: ArrayBufferView): any;
digest(algorithm: Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
encrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string | Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
exportKey(format: string, key: CryptoKey): any;
generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): any;
generateKey(algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
sign(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
verify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: Algorithm): any;
generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any;
}
declare var SubtleCrypto: {
@ -14661,11 +14651,8 @@ interface WebGLRenderingContext {
blendEquationSeparate(modeRGB: number, modeAlpha: number): void;
blendFunc(sfactor: number, dfactor: number): void;
blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;
bufferData(target: number, size: number, usage: number): void;
bufferData(target: number, size: ArrayBufferView, usage: number): void;
bufferData(target: number, size: any, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView): void;
bufferSubData(target: number, offset: number, data: any): void;
bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void;
checkFramebufferStatus(target: number): number;
clear(mask: number): void;
clearColor(red: number, green: number, blue: number, alpha: number): void;
@ -15508,8 +15495,7 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string): WebSocket;
new(url: string, protocols?: any): WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
@ -15675,6 +15661,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
toolbar: BarProp;
top: Window;
window: Window;
URL: URL;
alert(message?: any): void;
blur(): void;
cancelAnimationFrame(handle: number): void;
@ -16178,7 +16165,7 @@ interface NavigatorStorageUtils {
interface NodeSelector {
querySelector(selectors: string): Element;
querySelectorAll(selectors: string): NodeList;
querySelectorAll(selectors: string): NodeListOf<Element>;
}
interface RandomSource {
@ -16226,7 +16213,7 @@ interface SVGLocatable {
}
interface SVGStylable {
className: SVGAnimatedString;
className: any;
style: CSSStyleDeclaration;
}
@ -16313,8 +16300,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event, source?: string, fileno?: number, columnNumber?: number): void;
(event: string, source?: string, fileno?: number, columnNumber?: number): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
@ -16490,6 +16476,7 @@ declare var styleMedia: StyleMedia;
declare var toolbar: BarProp;
declare var top: Window;
declare var window: Window;
declare var URL: URL;
declare function alert(message?: any): void;
declare function blur(): void;
declare function cancelAnimationFrame(handle: number): void;
@ -16642,7 +16629,6 @@ declare function addEventListener(type: "volumechange", listener: (ev: Event) =>
declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////

102
bin/lib.dom.d.ts vendored
View File

@ -3585,16 +3585,11 @@ interface CanvasRenderingContext2D {
clearRect(x: number, y: number, w: number, h: number): void;
clip(fillRule?: string): void;
closePath(): void;
createImageData(imageDataOrSw: number, sh?: number): ImageData;
createImageData(imageDataOrSw: ImageData, sh?: number): ImageData;
createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createPattern(image: HTMLImageElement, repetition: string): CanvasPattern;
createPattern(image: HTMLCanvasElement, repetition: string): CanvasPattern;
createPattern(image: HTMLVideoElement, repetition: string): CanvasPattern;
createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
drawImage(image: HTMLImageElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLCanvasElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
fill(fillRule?: string): void;
fillRect(x: number, y: number, w: number, h: number): void;
fillText(text: string, x: number, y: number, maxWidth?: number): void;
@ -4752,12 +4747,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
/**
* Gets a collection of objects based on the value of the NAME or ID attribute.
* @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.
*/
getElementsByName(elementName: string): NodeList;
getElementsByName(elementName: string): NodeListOf<Element>;
/**
* Retrieves a collection of objects based on the specified element name.
* @param name Specifies the name of an element.
@ -4935,8 +4930,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
getElementsByTagName(tagname: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(tagname: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(tagname: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(tagname: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(tagname: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
/**
* Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
*/
@ -5209,6 +5204,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
scrollTop: number;
scrollWidth: number;
tagName: string;
id: string;
className: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@ -5388,8 +5385,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(name: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(name: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(name: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string, localName: string): boolean;
msGetRegionContent(): MSRangeCollection;
@ -5570,7 +5567,7 @@ interface FormData {
declare var FormData: {
prototype: FormData;
new(): FormData;
new (form?: HTMLFormElement): FormData;
}
interface GainNode extends AudioNode {
@ -5863,8 +5860,7 @@ interface HTMLAreasCollection extends HTMLCollection {
/**
* Adds an element to the areas, controlRange, or options collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Removes an element from the collection.
*/
@ -6308,14 +6304,12 @@ declare var HTMLDocument: {
interface HTMLElement extends Element {
accessKey: string;
children: HTMLCollection;
className: string;
contentEditable: string;
dataset: DOMStringMap;
dir: string;
draggable: boolean;
hidden: boolean;
hideFocus: boolean;
id: string;
innerHTML: string;
innerText: string;
isContentEditable: boolean;
@ -6402,7 +6396,7 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@ -8612,8 +8606,7 @@ interface HTMLSelectElement extends HTMLElement {
* @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.
* @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Returns whether a form will validate when it is submitted, without having to submit it.
*/
@ -11215,6 +11208,7 @@ declare var SVGDescElement: {
interface SVGElement extends Element {
id: string;
className: any;
onclick: (ev: MouseEvent) => any;
ondblclick: (ev: MouseEvent) => any;
onfocusin: (ev: FocusEvent) => any;
@ -12774,8 +12768,7 @@ interface Screen extends EventTarget {
systemXDPI: number;
systemYDPI: number;
width: number;
msLockOrientation(orientations: string): boolean;
msLockOrientation(orientations: string[]): boolean;
msLockOrientation(orientations: string | string[]): boolean;
msUnlockOrientation(): void;
addEventListener(type: "MSOrientationChange", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -12847,8 +12840,7 @@ interface SourceBuffer extends EventTarget {
updating: boolean;
videoTracks: VideoTrackList;
abort(): void;
appendBuffer(data: ArrayBuffer): void;
appendBuffer(data: ArrayBufferView): void;
appendBuffer(data: ArrayBuffer | ArrayBufferView): void;
appendStream(stream: MSStream, maxSize?: number): void;
remove(start: number, end: number): void;
}
@ -12956,33 +12948,18 @@ declare var StyleSheetPageList: {
}
interface SubtleCrypto {
decrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string, baseKey: CryptoKey, length: number): any;
deriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string, data: ArrayBufferView): any;
digest(algorithm: Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
encrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string | Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
exportKey(format: string, key: CryptoKey): any;
generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): any;
generateKey(algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
sign(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
verify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: Algorithm): any;
generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any;
}
declare var SubtleCrypto: {
@ -13491,11 +13468,8 @@ interface WebGLRenderingContext {
blendEquationSeparate(modeRGB: number, modeAlpha: number): void;
blendFunc(sfactor: number, dfactor: number): void;
blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;
bufferData(target: number, size: number, usage: number): void;
bufferData(target: number, size: ArrayBufferView, usage: number): void;
bufferData(target: number, size: any, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView): void;
bufferSubData(target: number, offset: number, data: any): void;
bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void;
checkFramebufferStatus(target: number): number;
clear(mask: number): void;
clearColor(red: number, green: number, blue: number, alpha: number): void;
@ -14338,8 +14312,7 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string): WebSocket;
new(url: string, protocols?: any): WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
@ -14505,6 +14478,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
toolbar: BarProp;
top: Window;
window: Window;
URL: URL;
alert(message?: any): void;
blur(): void;
cancelAnimationFrame(handle: number): void;
@ -15008,7 +14982,7 @@ interface NavigatorStorageUtils {
interface NodeSelector {
querySelector(selectors: string): Element;
querySelectorAll(selectors: string): NodeList;
querySelectorAll(selectors: string): NodeListOf<Element>;
}
interface RandomSource {
@ -15056,7 +15030,7 @@ interface SVGLocatable {
}
interface SVGStylable {
className: SVGAnimatedString;
className: any;
style: CSSStyleDeclaration;
}
@ -15143,8 +15117,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event, source?: string, fileno?: number, columnNumber?: number): void;
(event: string, source?: string, fileno?: number, columnNumber?: number): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
@ -15320,6 +15293,7 @@ declare var styleMedia: StyleMedia;
declare var toolbar: BarProp;
declare var top: Window;
declare var window: Window;
declare var URL: URL;
declare function alert(message?: any): void;
declare function blur(): void;
declare function cancelAnimationFrame(handle: number): void;
@ -15471,4 +15445,4 @@ declare function addEventListener(type: "unload", listener: (ev: Event) => any,
declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;

128
bin/lib.es6.d.ts vendored
View File

@ -1184,6 +1184,19 @@ declare type ClassDecorator = <TFunction extends Function>(target: TFunction) =>
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
declare type PropertyKey = string | number | symbol;
interface Symbol {
@ -4759,17 +4772,6 @@ declare module Reflect {
function setPrototypeOf(target: any, proto: any): boolean;
}
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
/**
* Represents the completion of an asynchronous operation
*/
@ -4789,6 +4791,7 @@ interface Promise<T> {
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
[Symbol.toStringTag]: string;
}
@ -6137,16 +6140,11 @@ interface CanvasRenderingContext2D {
clearRect(x: number, y: number, w: number, h: number): void;
clip(fillRule?: string): void;
closePath(): void;
createImageData(imageDataOrSw: number, sh?: number): ImageData;
createImageData(imageDataOrSw: ImageData, sh?: number): ImageData;
createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createPattern(image: HTMLImageElement, repetition: string): CanvasPattern;
createPattern(image: HTMLCanvasElement, repetition: string): CanvasPattern;
createPattern(image: HTMLVideoElement, repetition: string): CanvasPattern;
createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
drawImage(image: HTMLImageElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLCanvasElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
fill(fillRule?: string): void;
fillRect(x: number, y: number, w: number, h: number): void;
fillText(text: string, x: number, y: number, maxWidth?: number): void;
@ -7304,12 +7302,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
/**
* Gets a collection of objects based on the value of the NAME or ID attribute.
* @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.
*/
getElementsByName(elementName: string): NodeList;
getElementsByName(elementName: string): NodeListOf<Element>;
/**
* Retrieves a collection of objects based on the specified element name.
* @param name Specifies the name of an element.
@ -7487,8 +7485,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
getElementsByTagName(tagname: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(tagname: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(tagname: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(tagname: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(tagname: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
/**
* Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
*/
@ -7761,6 +7759,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
scrollTop: number;
scrollWidth: number;
tagName: string;
id: string;
className: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@ -7940,8 +7940,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(name: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(name: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(name: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string, localName: string): boolean;
msGetRegionContent(): MSRangeCollection;
@ -8122,7 +8122,7 @@ interface FormData {
declare var FormData: {
prototype: FormData;
new(): FormData;
new (form?: HTMLFormElement): FormData;
}
interface GainNode extends AudioNode {
@ -8415,8 +8415,7 @@ interface HTMLAreasCollection extends HTMLCollection {
/**
* Adds an element to the areas, controlRange, or options collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Removes an element from the collection.
*/
@ -8860,14 +8859,12 @@ declare var HTMLDocument: {
interface HTMLElement extends Element {
accessKey: string;
children: HTMLCollection;
className: string;
contentEditable: string;
dataset: DOMStringMap;
dir: string;
draggable: boolean;
hidden: boolean;
hideFocus: boolean;
id: string;
innerHTML: string;
innerText: string;
isContentEditable: boolean;
@ -8954,7 +8951,7 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@ -11164,8 +11161,7 @@ interface HTMLSelectElement extends HTMLElement {
* @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.
* @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Returns whether a form will validate when it is submitted, without having to submit it.
*/
@ -13767,6 +13763,7 @@ declare var SVGDescElement: {
interface SVGElement extends Element {
id: string;
className: any;
onclick: (ev: MouseEvent) => any;
ondblclick: (ev: MouseEvent) => any;
onfocusin: (ev: FocusEvent) => any;
@ -15326,8 +15323,7 @@ interface Screen extends EventTarget {
systemXDPI: number;
systemYDPI: number;
width: number;
msLockOrientation(orientations: string): boolean;
msLockOrientation(orientations: string[]): boolean;
msLockOrientation(orientations: string | string[]): boolean;
msUnlockOrientation(): void;
addEventListener(type: "MSOrientationChange", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -15399,8 +15395,7 @@ interface SourceBuffer extends EventTarget {
updating: boolean;
videoTracks: VideoTrackList;
abort(): void;
appendBuffer(data: ArrayBuffer): void;
appendBuffer(data: ArrayBufferView): void;
appendBuffer(data: ArrayBuffer | ArrayBufferView): void;
appendStream(stream: MSStream, maxSize?: number): void;
remove(start: number, end: number): void;
}
@ -15508,33 +15503,18 @@ declare var StyleSheetPageList: {
}
interface SubtleCrypto {
decrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string, baseKey: CryptoKey, length: number): any;
deriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string, data: ArrayBufferView): any;
digest(algorithm: Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
encrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string | Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
exportKey(format: string, key: CryptoKey): any;
generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): any;
generateKey(algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
sign(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
verify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: Algorithm): any;
generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any;
}
declare var SubtleCrypto: {
@ -16043,11 +16023,8 @@ interface WebGLRenderingContext {
blendEquationSeparate(modeRGB: number, modeAlpha: number): void;
blendFunc(sfactor: number, dfactor: number): void;
blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;
bufferData(target: number, size: number, usage: number): void;
bufferData(target: number, size: ArrayBufferView, usage: number): void;
bufferData(target: number, size: any, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView): void;
bufferSubData(target: number, offset: number, data: any): void;
bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void;
checkFramebufferStatus(target: number): number;
clear(mask: number): void;
clearColor(red: number, green: number, blue: number, alpha: number): void;
@ -16890,8 +16867,7 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string): WebSocket;
new(url: string, protocols?: any): WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
@ -17057,6 +17033,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
toolbar: BarProp;
top: Window;
window: Window;
URL: URL;
alert(message?: any): void;
blur(): void;
cancelAnimationFrame(handle: number): void;
@ -17560,7 +17537,7 @@ interface NavigatorStorageUtils {
interface NodeSelector {
querySelector(selectors: string): Element;
querySelectorAll(selectors: string): NodeList;
querySelectorAll(selectors: string): NodeListOf<Element>;
}
interface RandomSource {
@ -17608,7 +17585,7 @@ interface SVGLocatable {
}
interface SVGStylable {
className: SVGAnimatedString;
className: any;
style: CSSStyleDeclaration;
}
@ -17695,8 +17672,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event, source?: string, fileno?: number, columnNumber?: number): void;
(event: string, source?: string, fileno?: number, columnNumber?: number): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
@ -17872,6 +17848,7 @@ declare var styleMedia: StyleMedia;
declare var toolbar: BarProp;
declare var top: Window;
declare var window: Window;
declare var URL: URL;
declare function alert(message?: any): void;
declare function blur(): void;
declare function cancelAnimationFrame(handle: number): void;
@ -18023,8 +18000,7 @@ declare function addEventListener(type: "unload", listener: (ev: Event) => any,
declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
interface DOMTokenList {
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}

View File

@ -3064,8 +3064,7 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string): WebSocket;
new(url: string, protocols?: any): WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
@ -3300,8 +3299,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event, source?: string, fileno?: number, columnNumber?: number): void;
(event: string, source?: string, fileno?: number, columnNumber?: number): void;
(event: Event | string, source?: string, fileno?: number, columnNumber?: number): void;
}
interface PositionCallback {
(position: Position): void;

9631
bin/tsc.js

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

666
bin/typescript.d.ts vendored
View File

@ -54,250 +54,265 @@ declare module "typescript" {
SemicolonToken = 22,
CommaToken = 23,
LessThanToken = 24,
GreaterThanToken = 25,
LessThanEqualsToken = 26,
GreaterThanEqualsToken = 27,
EqualsEqualsToken = 28,
ExclamationEqualsToken = 29,
EqualsEqualsEqualsToken = 30,
ExclamationEqualsEqualsToken = 31,
EqualsGreaterThanToken = 32,
PlusToken = 33,
MinusToken = 34,
AsteriskToken = 35,
SlashToken = 36,
PercentToken = 37,
PlusPlusToken = 38,
MinusMinusToken = 39,
LessThanLessThanToken = 40,
GreaterThanGreaterThanToken = 41,
GreaterThanGreaterThanGreaterThanToken = 42,
AmpersandToken = 43,
BarToken = 44,
CaretToken = 45,
ExclamationToken = 46,
TildeToken = 47,
AmpersandAmpersandToken = 48,
BarBarToken = 49,
QuestionToken = 50,
ColonToken = 51,
AtToken = 52,
EqualsToken = 53,
PlusEqualsToken = 54,
MinusEqualsToken = 55,
AsteriskEqualsToken = 56,
SlashEqualsToken = 57,
PercentEqualsToken = 58,
LessThanLessThanEqualsToken = 59,
GreaterThanGreaterThanEqualsToken = 60,
GreaterThanGreaterThanGreaterThanEqualsToken = 61,
AmpersandEqualsToken = 62,
BarEqualsToken = 63,
CaretEqualsToken = 64,
Identifier = 65,
BreakKeyword = 66,
CaseKeyword = 67,
CatchKeyword = 68,
ClassKeyword = 69,
ConstKeyword = 70,
ContinueKeyword = 71,
DebuggerKeyword = 72,
DefaultKeyword = 73,
DeleteKeyword = 74,
DoKeyword = 75,
ElseKeyword = 76,
EnumKeyword = 77,
ExportKeyword = 78,
ExtendsKeyword = 79,
FalseKeyword = 80,
FinallyKeyword = 81,
ForKeyword = 82,
FunctionKeyword = 83,
IfKeyword = 84,
ImportKeyword = 85,
InKeyword = 86,
InstanceOfKeyword = 87,
NewKeyword = 88,
NullKeyword = 89,
ReturnKeyword = 90,
SuperKeyword = 91,
SwitchKeyword = 92,
ThisKeyword = 93,
ThrowKeyword = 94,
TrueKeyword = 95,
TryKeyword = 96,
TypeOfKeyword = 97,
VarKeyword = 98,
VoidKeyword = 99,
WhileKeyword = 100,
WithKeyword = 101,
ImplementsKeyword = 102,
InterfaceKeyword = 103,
LetKeyword = 104,
PackageKeyword = 105,
PrivateKeyword = 106,
ProtectedKeyword = 107,
PublicKeyword = 108,
StaticKeyword = 109,
YieldKeyword = 110,
AsKeyword = 111,
AnyKeyword = 112,
BooleanKeyword = 113,
ConstructorKeyword = 114,
DeclareKeyword = 115,
GetKeyword = 116,
IsKeyword = 117,
ModuleKeyword = 118,
NamespaceKeyword = 119,
RequireKeyword = 120,
NumberKeyword = 121,
SetKeyword = 122,
StringKeyword = 123,
SymbolKeyword = 124,
TypeKeyword = 125,
FromKeyword = 126,
OfKeyword = 127,
QualifiedName = 128,
ComputedPropertyName = 129,
TypeParameter = 130,
Parameter = 131,
Decorator = 132,
PropertySignature = 133,
PropertyDeclaration = 134,
MethodSignature = 135,
MethodDeclaration = 136,
Constructor = 137,
GetAccessor = 138,
SetAccessor = 139,
CallSignature = 140,
ConstructSignature = 141,
IndexSignature = 142,
TypePredicate = 143,
TypeReference = 144,
FunctionType = 145,
ConstructorType = 146,
TypeQuery = 147,
TypeLiteral = 148,
ArrayType = 149,
TupleType = 150,
UnionType = 151,
ParenthesizedType = 152,
ObjectBindingPattern = 153,
ArrayBindingPattern = 154,
BindingElement = 155,
ArrayLiteralExpression = 156,
ObjectLiteralExpression = 157,
PropertyAccessExpression = 158,
ElementAccessExpression = 159,
CallExpression = 160,
NewExpression = 161,
TaggedTemplateExpression = 162,
TypeAssertionExpression = 163,
ParenthesizedExpression = 164,
FunctionExpression = 165,
ArrowFunction = 166,
DeleteExpression = 167,
TypeOfExpression = 168,
VoidExpression = 169,
PrefixUnaryExpression = 170,
PostfixUnaryExpression = 171,
BinaryExpression = 172,
ConditionalExpression = 173,
TemplateExpression = 174,
YieldExpression = 175,
SpreadElementExpression = 176,
ClassExpression = 177,
OmittedExpression = 178,
ExpressionWithTypeArguments = 179,
TemplateSpan = 180,
SemicolonClassElement = 181,
Block = 182,
VariableStatement = 183,
EmptyStatement = 184,
ExpressionStatement = 185,
IfStatement = 186,
DoStatement = 187,
WhileStatement = 188,
ForStatement = 189,
ForInStatement = 190,
ForOfStatement = 191,
ContinueStatement = 192,
BreakStatement = 193,
ReturnStatement = 194,
WithStatement = 195,
SwitchStatement = 196,
LabeledStatement = 197,
ThrowStatement = 198,
TryStatement = 199,
DebuggerStatement = 200,
VariableDeclaration = 201,
VariableDeclarationList = 202,
FunctionDeclaration = 203,
ClassDeclaration = 204,
InterfaceDeclaration = 205,
TypeAliasDeclaration = 206,
EnumDeclaration = 207,
ModuleDeclaration = 208,
ModuleBlock = 209,
CaseBlock = 210,
ImportEqualsDeclaration = 211,
ImportDeclaration = 212,
ImportClause = 213,
NamespaceImport = 214,
NamedImports = 215,
ImportSpecifier = 216,
ExportAssignment = 217,
ExportDeclaration = 218,
NamedExports = 219,
ExportSpecifier = 220,
MissingDeclaration = 221,
ExternalModuleReference = 222,
CaseClause = 223,
DefaultClause = 224,
HeritageClause = 225,
CatchClause = 226,
PropertyAssignment = 227,
ShorthandPropertyAssignment = 228,
EnumMember = 229,
SourceFile = 230,
JSDocTypeExpression = 231,
JSDocAllType = 232,
JSDocUnknownType = 233,
JSDocArrayType = 234,
JSDocUnionType = 235,
JSDocTupleType = 236,
JSDocNullableType = 237,
JSDocNonNullableType = 238,
JSDocRecordType = 239,
JSDocRecordMember = 240,
JSDocTypeReference = 241,
JSDocOptionalType = 242,
JSDocFunctionType = 243,
JSDocVariadicType = 244,
JSDocConstructorType = 245,
JSDocThisType = 246,
JSDocComment = 247,
JSDocTag = 248,
JSDocParameterTag = 249,
JSDocReturnTag = 250,
JSDocTypeTag = 251,
JSDocTemplateTag = 252,
SyntaxList = 253,
Count = 254,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
LastReservedWord = 101,
FirstKeyword = 66,
LastKeyword = 127,
FirstFutureReservedWord = 102,
LastFutureReservedWord = 110,
FirstTypeNode = 144,
LastTypeNode = 152,
LessThanSlashToken = 25,
GreaterThanToken = 26,
LessThanEqualsToken = 27,
GreaterThanEqualsToken = 28,
EqualsEqualsToken = 29,
ExclamationEqualsToken = 30,
EqualsEqualsEqualsToken = 31,
ExclamationEqualsEqualsToken = 32,
EqualsGreaterThanToken = 33,
PlusToken = 34,
MinusToken = 35,
AsteriskToken = 36,
SlashToken = 37,
PercentToken = 38,
PlusPlusToken = 39,
MinusMinusToken = 40,
LessThanLessThanToken = 41,
GreaterThanGreaterThanToken = 42,
GreaterThanGreaterThanGreaterThanToken = 43,
AmpersandToken = 44,
BarToken = 45,
CaretToken = 46,
ExclamationToken = 47,
TildeToken = 48,
AmpersandAmpersandToken = 49,
BarBarToken = 50,
QuestionToken = 51,
ColonToken = 52,
AtToken = 53,
EqualsToken = 54,
PlusEqualsToken = 55,
MinusEqualsToken = 56,
AsteriskEqualsToken = 57,
SlashEqualsToken = 58,
PercentEqualsToken = 59,
LessThanLessThanEqualsToken = 60,
GreaterThanGreaterThanEqualsToken = 61,
GreaterThanGreaterThanGreaterThanEqualsToken = 62,
AmpersandEqualsToken = 63,
BarEqualsToken = 64,
CaretEqualsToken = 65,
Identifier = 66,
BreakKeyword = 67,
CaseKeyword = 68,
CatchKeyword = 69,
ClassKeyword = 70,
ConstKeyword = 71,
ContinueKeyword = 72,
DebuggerKeyword = 73,
DefaultKeyword = 74,
DeleteKeyword = 75,
DoKeyword = 76,
ElseKeyword = 77,
EnumKeyword = 78,
ExportKeyword = 79,
ExtendsKeyword = 80,
FalseKeyword = 81,
FinallyKeyword = 82,
ForKeyword = 83,
FunctionKeyword = 84,
IfKeyword = 85,
ImportKeyword = 86,
InKeyword = 87,
InstanceOfKeyword = 88,
NewKeyword = 89,
NullKeyword = 90,
ReturnKeyword = 91,
SuperKeyword = 92,
SwitchKeyword = 93,
ThisKeyword = 94,
ThrowKeyword = 95,
TrueKeyword = 96,
TryKeyword = 97,
TypeOfKeyword = 98,
VarKeyword = 99,
VoidKeyword = 100,
WhileKeyword = 101,
WithKeyword = 102,
ImplementsKeyword = 103,
InterfaceKeyword = 104,
LetKeyword = 105,
PackageKeyword = 106,
PrivateKeyword = 107,
ProtectedKeyword = 108,
PublicKeyword = 109,
StaticKeyword = 110,
YieldKeyword = 111,
AbstractKeyword = 112,
AsKeyword = 113,
AnyKeyword = 114,
AsyncKeyword = 115,
AwaitKeyword = 116,
BooleanKeyword = 117,
ConstructorKeyword = 118,
DeclareKeyword = 119,
GetKeyword = 120,
IsKeyword = 121,
ModuleKeyword = 122,
NamespaceKeyword = 123,
RequireKeyword = 124,
NumberKeyword = 125,
SetKeyword = 126,
StringKeyword = 127,
SymbolKeyword = 128,
TypeKeyword = 129,
FromKeyword = 130,
OfKeyword = 131,
QualifiedName = 132,
ComputedPropertyName = 133,
TypeParameter = 134,
Parameter = 135,
Decorator = 136,
PropertySignature = 137,
PropertyDeclaration = 138,
MethodSignature = 139,
MethodDeclaration = 140,
Constructor = 141,
GetAccessor = 142,
SetAccessor = 143,
CallSignature = 144,
ConstructSignature = 145,
IndexSignature = 146,
TypePredicate = 147,
TypeReference = 148,
FunctionType = 149,
ConstructorType = 150,
TypeQuery = 151,
TypeLiteral = 152,
ArrayType = 153,
TupleType = 154,
UnionType = 155,
IntersectionType = 156,
ParenthesizedType = 157,
ObjectBindingPattern = 158,
ArrayBindingPattern = 159,
BindingElement = 160,
ArrayLiteralExpression = 161,
ObjectLiteralExpression = 162,
PropertyAccessExpression = 163,
ElementAccessExpression = 164,
CallExpression = 165,
NewExpression = 166,
TaggedTemplateExpression = 167,
TypeAssertionExpression = 168,
ParenthesizedExpression = 169,
FunctionExpression = 170,
ArrowFunction = 171,
DeleteExpression = 172,
TypeOfExpression = 173,
VoidExpression = 174,
AwaitExpression = 175,
PrefixUnaryExpression = 176,
PostfixUnaryExpression = 177,
BinaryExpression = 178,
ConditionalExpression = 179,
TemplateExpression = 180,
YieldExpression = 181,
SpreadElementExpression = 182,
ClassExpression = 183,
OmittedExpression = 184,
ExpressionWithTypeArguments = 185,
AsExpression = 186,
TemplateSpan = 187,
SemicolonClassElement = 188,
Block = 189,
VariableStatement = 190,
EmptyStatement = 191,
ExpressionStatement = 192,
IfStatement = 193,
DoStatement = 194,
WhileStatement = 195,
ForStatement = 196,
ForInStatement = 197,
ForOfStatement = 198,
ContinueStatement = 199,
BreakStatement = 200,
ReturnStatement = 201,
WithStatement = 202,
SwitchStatement = 203,
LabeledStatement = 204,
ThrowStatement = 205,
TryStatement = 206,
DebuggerStatement = 207,
VariableDeclaration = 208,
VariableDeclarationList = 209,
FunctionDeclaration = 210,
ClassDeclaration = 211,
InterfaceDeclaration = 212,
TypeAliasDeclaration = 213,
EnumDeclaration = 214,
ModuleDeclaration = 215,
ModuleBlock = 216,
CaseBlock = 217,
ImportEqualsDeclaration = 218,
ImportDeclaration = 219,
ImportClause = 220,
NamespaceImport = 221,
NamedImports = 222,
ImportSpecifier = 223,
ExportAssignment = 224,
ExportDeclaration = 225,
NamedExports = 226,
ExportSpecifier = 227,
MissingDeclaration = 228,
ExternalModuleReference = 229,
JsxElement = 230,
JsxSelfClosingElement = 231,
JsxOpeningElement = 232,
JsxText = 233,
JsxClosingElement = 234,
JsxAttribute = 235,
JsxSpreadAttribute = 236,
JsxExpression = 237,
CaseClause = 238,
DefaultClause = 239,
HeritageClause = 240,
CatchClause = 241,
PropertyAssignment = 242,
ShorthandPropertyAssignment = 243,
EnumMember = 244,
SourceFile = 245,
JSDocTypeExpression = 246,
JSDocAllType = 247,
JSDocUnknownType = 248,
JSDocArrayType = 249,
JSDocUnionType = 250,
JSDocTupleType = 251,
JSDocNullableType = 252,
JSDocNonNullableType = 253,
JSDocRecordType = 254,
JSDocRecordMember = 255,
JSDocTypeReference = 256,
JSDocOptionalType = 257,
JSDocFunctionType = 258,
JSDocVariadicType = 259,
JSDocConstructorType = 260,
JSDocThisType = 261,
JSDocComment = 262,
JSDocTag = 263,
JSDocParameterTag = 264,
JSDocReturnTag = 265,
JSDocTypeTag = 266,
JSDocTemplateTag = 267,
SyntaxList = 268,
Count = 269,
FirstAssignment = 54,
LastAssignment = 65,
FirstReservedWord = 67,
LastReservedWord = 102,
FirstKeyword = 67,
LastKeyword = 131,
FirstFutureReservedWord = 103,
LastFutureReservedWord = 111,
FirstTypeNode = 148,
LastTypeNode = 157,
FirstPunctuation = 14,
LastPunctuation = 64,
LastPunctuation = 65,
FirstToken = 0,
LastToken = 127,
LastToken = 131,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
@ -305,8 +320,8 @@ declare module "typescript" {
FirstTemplateToken = 10,
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 64,
FirstNode = 128,
LastBinaryOperator = 65,
FirstNode = 132,
}
const enum NodeFlags {
Export = 1,
@ -315,18 +330,28 @@ declare module "typescript" {
Private = 32,
Protected = 64,
Static = 128,
Default = 256,
MultiLine = 512,
Synthetic = 1024,
DeclarationFile = 2048,
Let = 4096,
Const = 8192,
OctalLiteral = 16384,
Namespace = 32768,
ExportContext = 65536,
Modifier = 499,
Abstract = 256,
Async = 512,
Default = 1024,
MultiLine = 2048,
Synthetic = 4096,
DeclarationFile = 8192,
Let = 16384,
Const = 32768,
OctalLiteral = 65536,
Namespace = 131072,
ExportContext = 262144,
Modifier = 2035,
AccessibilityModifier = 112,
BlockScoped = 12288,
BlockScoped = 49152,
}
const enum JsxFlags {
None = 0,
IntrinsicNamedElement = 1,
IntrinsicIndexedElement = 2,
ClassElement = 4,
UnknownElement = 8,
IntrinsicElement = 3,
}
interface Node extends TextRange {
kind: SyntaxKind;
@ -483,9 +508,13 @@ declare module "typescript" {
interface TupleTypeNode extends TypeNode {
elementTypes: NodeArray<TypeNode>;
}
interface UnionTypeNode extends TypeNode {
interface UnionOrIntersectionTypeNode extends TypeNode {
types: NodeArray<TypeNode>;
}
interface UnionTypeNode extends UnionOrIntersectionTypeNode {
}
interface IntersectionTypeNode extends UnionOrIntersectionTypeNode {
}
interface ParenthesizedTypeNode extends TypeNode {
type: TypeNode;
}
@ -528,6 +557,9 @@ declare module "typescript" {
interface VoidExpression extends UnaryExpression {
expression: UnaryExpression;
}
interface AwaitExpression extends UnaryExpression {
expression: UnaryExpression;
}
interface YieldExpression extends Expression {
asteriskToken?: Node;
expression?: Expression;
@ -601,10 +633,46 @@ declare module "typescript" {
template: LiteralExpression | TemplateExpression;
}
type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
interface AsExpression extends Expression {
expression: Expression;
type: TypeNode;
}
interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
closingElement: JsxClosingElement;
}
interface JsxOpeningElement extends Expression {
_openingElementBrand?: any;
tagName: EntityName;
attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>;
}
interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement {
_selfClosingElementBrand?: any;
}
type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
interface JsxAttribute extends Node {
name: Identifier;
initializer?: Expression;
}
interface JsxSpreadAttribute extends Node {
expression: Expression;
}
interface JsxClosingElement extends Node {
tagName: EntityName;
}
interface JsxExpression extends Expression {
expression?: Expression;
}
interface JsxText extends Node {
_jsxTextExpressionBrand: any;
}
type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement;
interface Statement extends Node {
_statementBrand: any;
}
@ -859,6 +927,7 @@ declare module "typescript" {
}[];
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
/**
* lib.d.ts should have a reference comment like
*
@ -881,6 +950,13 @@ declare module "typescript" {
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
class OperationCanceledException {
}
interface CancellationToken {
isCancellationRequested(): boolean;
/** @throws OperationCanceledException if isCancellationRequested is true */
throwIfCancellationRequested(): void;
}
interface Program extends ScriptReferenceHost {
/**
* Get a list of files in the program
@ -896,12 +972,12 @@ declare module "typescript" {
* used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
* will be invoked when writing the JavaScript and declaration files.
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
getOptionsDiagnostics(): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
@ -976,6 +1052,8 @@ declare module "typescript" {
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@ -1053,7 +1131,7 @@ declare module "typescript" {
Merged = 33554432,
Transient = 67108864,
Prototype = 134217728,
UnionProperty = 268435456,
SyntheticProperty = 268435456,
Optional = 536870912,
ExportStar = 1073741824,
Enum = 384,
@ -1069,8 +1147,8 @@ declare module "typescript" {
PropertyExcludes = 107455,
EnumMemberExcludes = 107455,
FunctionExcludes = 106927,
ClassExcludes = 899583,
InterfaceExcludes = 792992,
ClassExcludes = 899519,
InterfaceExcludes = 792960,
RegularEnumExcludes = 899327,
ConstEnumExcludes = 899967,
ValueModuleExcludes = 106639,
@ -1116,13 +1194,16 @@ declare module "typescript" {
Reference = 4096,
Tuple = 8192,
Union = 16384,
Anonymous = 32768,
Instantiated = 65536,
ObjectLiteral = 262144,
ESSymbol = 2097152,
Intersection = 32768,
Anonymous = 65536,
Instantiated = 131072,
ObjectLiteral = 524288,
ESSymbol = 4194304,
StringLike = 258,
NumberLike = 132,
ObjectType = 48128,
ObjectType = 80896,
UnionOrIntersection = 49152,
StructuredType = 130048,
}
interface Type {
flags: TypeFlags;
@ -1157,9 +1238,13 @@ declare module "typescript" {
elementTypes: Type[];
baseArrayType: TypeReference;
}
interface UnionType extends Type {
interface UnionOrIntersectionType extends Type {
types: Type[];
}
interface UnionType extends UnionOrIntersectionType {
}
interface IntersectionType extends UnionOrIntersectionType {
}
interface TypeParameter extends Type {
constraint: Type;
}
@ -1216,6 +1301,7 @@ declare module "typescript" {
help?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
listFiles?: boolean;
locale?: string;
mapRoot?: string;
@ -1242,6 +1328,7 @@ declare module "typescript" {
watch?: boolean;
isolatedModules?: boolean;
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
[option: string]: string | number | boolean;
}
@ -1252,6 +1339,11 @@ declare module "typescript" {
UMD = 3,
System = 4,
}
const enum JsxEmit {
None = 0,
Preserve = 1,
React = 2,
}
const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
@ -1266,18 +1358,18 @@ declare module "typescript" {
ES6 = 2,
Latest = 2,
}
const enum LanguageVariant {
Standard = 0,
JSX = 1,
}
interface ParsedCommandLine {
options: CompilerOptions;
fileNames: string[];
errors: Diagnostic[];
}
interface CancellationToken {
isCancellationRequested(): boolean;
}
interface CompilerHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getDefaultLibFileName(options: CompilerOptions): string;
getCancellationToken?(): CancellationToken;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
@ -1336,10 +1428,14 @@ declare module "typescript" {
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scan(): SyntaxKind;
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
setScriptTarget(scriptTarget: ScriptTarget): void;
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
lookAhead<T>(callback: () => T): T;
tryScan<T>(callback: () => T): T;
@ -1397,7 +1493,7 @@ declare module "typescript" {
const version: string;
function findConfigFile(searchPath: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[];
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
@ -1504,6 +1600,9 @@ declare module "typescript" {
importedFiles: FileReference[];
isLibFile: boolean;
}
interface HostCancellationToken {
isCancellationRequested(): boolean;
}
interface LanguageServiceHost {
getCompilationSettings(): CompilerOptions;
getNewLine?(): string;
@ -1512,7 +1611,7 @@ declare module "typescript" {
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): CancellationToken;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
getDefaultLibFileName(options: CompilerOptions): string;
log?(s: string): void;
@ -1892,6 +1991,7 @@ declare module "typescript" {
const scriptElement: string;
const moduleElement: string;
const classElement: string;
const localClassElement: string;
const interfaceElement: string;
const typeElement: string;
const enumElement: string;
@ -1923,6 +2023,7 @@ declare module "typescript" {
const exportedModifier: string;
const ambientModifier: string;
const staticModifier: string;
const abstractModifier: string;
}
class ClassificationTypeNames {
static comment: string;
@ -1968,15 +2069,6 @@ declare module "typescript" {
}
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
class OperationCanceledException {
}
class CancellationTokenObject {
private cancellationToken;
static None: CancellationTokenObject;
constructor(cancellationToken: CancellationToken);
isCancellationRequested(): boolean;
throwIfCancellationRequested(): void;
}
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
@ -1986,7 +2078,7 @@ declare module "typescript" {
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
function createClassifier(): Classifier;
/**
* Get the path of the default library file (lib.d.ts) as distributed with the typescript
* Get the path of the default library files (lib.d.ts) as distributed with the typescript
* node package.
* The functionality is not supported if the ts module is consumed outside of a node module.
*/

File diff suppressed because it is too large Load Diff

View File

@ -54,250 +54,265 @@ declare namespace ts {
SemicolonToken = 22,
CommaToken = 23,
LessThanToken = 24,
GreaterThanToken = 25,
LessThanEqualsToken = 26,
GreaterThanEqualsToken = 27,
EqualsEqualsToken = 28,
ExclamationEqualsToken = 29,
EqualsEqualsEqualsToken = 30,
ExclamationEqualsEqualsToken = 31,
EqualsGreaterThanToken = 32,
PlusToken = 33,
MinusToken = 34,
AsteriskToken = 35,
SlashToken = 36,
PercentToken = 37,
PlusPlusToken = 38,
MinusMinusToken = 39,
LessThanLessThanToken = 40,
GreaterThanGreaterThanToken = 41,
GreaterThanGreaterThanGreaterThanToken = 42,
AmpersandToken = 43,
BarToken = 44,
CaretToken = 45,
ExclamationToken = 46,
TildeToken = 47,
AmpersandAmpersandToken = 48,
BarBarToken = 49,
QuestionToken = 50,
ColonToken = 51,
AtToken = 52,
EqualsToken = 53,
PlusEqualsToken = 54,
MinusEqualsToken = 55,
AsteriskEqualsToken = 56,
SlashEqualsToken = 57,
PercentEqualsToken = 58,
LessThanLessThanEqualsToken = 59,
GreaterThanGreaterThanEqualsToken = 60,
GreaterThanGreaterThanGreaterThanEqualsToken = 61,
AmpersandEqualsToken = 62,
BarEqualsToken = 63,
CaretEqualsToken = 64,
Identifier = 65,
BreakKeyword = 66,
CaseKeyword = 67,
CatchKeyword = 68,
ClassKeyword = 69,
ConstKeyword = 70,
ContinueKeyword = 71,
DebuggerKeyword = 72,
DefaultKeyword = 73,
DeleteKeyword = 74,
DoKeyword = 75,
ElseKeyword = 76,
EnumKeyword = 77,
ExportKeyword = 78,
ExtendsKeyword = 79,
FalseKeyword = 80,
FinallyKeyword = 81,
ForKeyword = 82,
FunctionKeyword = 83,
IfKeyword = 84,
ImportKeyword = 85,
InKeyword = 86,
InstanceOfKeyword = 87,
NewKeyword = 88,
NullKeyword = 89,
ReturnKeyword = 90,
SuperKeyword = 91,
SwitchKeyword = 92,
ThisKeyword = 93,
ThrowKeyword = 94,
TrueKeyword = 95,
TryKeyword = 96,
TypeOfKeyword = 97,
VarKeyword = 98,
VoidKeyword = 99,
WhileKeyword = 100,
WithKeyword = 101,
ImplementsKeyword = 102,
InterfaceKeyword = 103,
LetKeyword = 104,
PackageKeyword = 105,
PrivateKeyword = 106,
ProtectedKeyword = 107,
PublicKeyword = 108,
StaticKeyword = 109,
YieldKeyword = 110,
AsKeyword = 111,
AnyKeyword = 112,
BooleanKeyword = 113,
ConstructorKeyword = 114,
DeclareKeyword = 115,
GetKeyword = 116,
IsKeyword = 117,
ModuleKeyword = 118,
NamespaceKeyword = 119,
RequireKeyword = 120,
NumberKeyword = 121,
SetKeyword = 122,
StringKeyword = 123,
SymbolKeyword = 124,
TypeKeyword = 125,
FromKeyword = 126,
OfKeyword = 127,
QualifiedName = 128,
ComputedPropertyName = 129,
TypeParameter = 130,
Parameter = 131,
Decorator = 132,
PropertySignature = 133,
PropertyDeclaration = 134,
MethodSignature = 135,
MethodDeclaration = 136,
Constructor = 137,
GetAccessor = 138,
SetAccessor = 139,
CallSignature = 140,
ConstructSignature = 141,
IndexSignature = 142,
TypePredicate = 143,
TypeReference = 144,
FunctionType = 145,
ConstructorType = 146,
TypeQuery = 147,
TypeLiteral = 148,
ArrayType = 149,
TupleType = 150,
UnionType = 151,
ParenthesizedType = 152,
ObjectBindingPattern = 153,
ArrayBindingPattern = 154,
BindingElement = 155,
ArrayLiteralExpression = 156,
ObjectLiteralExpression = 157,
PropertyAccessExpression = 158,
ElementAccessExpression = 159,
CallExpression = 160,
NewExpression = 161,
TaggedTemplateExpression = 162,
TypeAssertionExpression = 163,
ParenthesizedExpression = 164,
FunctionExpression = 165,
ArrowFunction = 166,
DeleteExpression = 167,
TypeOfExpression = 168,
VoidExpression = 169,
PrefixUnaryExpression = 170,
PostfixUnaryExpression = 171,
BinaryExpression = 172,
ConditionalExpression = 173,
TemplateExpression = 174,
YieldExpression = 175,
SpreadElementExpression = 176,
ClassExpression = 177,
OmittedExpression = 178,
ExpressionWithTypeArguments = 179,
TemplateSpan = 180,
SemicolonClassElement = 181,
Block = 182,
VariableStatement = 183,
EmptyStatement = 184,
ExpressionStatement = 185,
IfStatement = 186,
DoStatement = 187,
WhileStatement = 188,
ForStatement = 189,
ForInStatement = 190,
ForOfStatement = 191,
ContinueStatement = 192,
BreakStatement = 193,
ReturnStatement = 194,
WithStatement = 195,
SwitchStatement = 196,
LabeledStatement = 197,
ThrowStatement = 198,
TryStatement = 199,
DebuggerStatement = 200,
VariableDeclaration = 201,
VariableDeclarationList = 202,
FunctionDeclaration = 203,
ClassDeclaration = 204,
InterfaceDeclaration = 205,
TypeAliasDeclaration = 206,
EnumDeclaration = 207,
ModuleDeclaration = 208,
ModuleBlock = 209,
CaseBlock = 210,
ImportEqualsDeclaration = 211,
ImportDeclaration = 212,
ImportClause = 213,
NamespaceImport = 214,
NamedImports = 215,
ImportSpecifier = 216,
ExportAssignment = 217,
ExportDeclaration = 218,
NamedExports = 219,
ExportSpecifier = 220,
MissingDeclaration = 221,
ExternalModuleReference = 222,
CaseClause = 223,
DefaultClause = 224,
HeritageClause = 225,
CatchClause = 226,
PropertyAssignment = 227,
ShorthandPropertyAssignment = 228,
EnumMember = 229,
SourceFile = 230,
JSDocTypeExpression = 231,
JSDocAllType = 232,
JSDocUnknownType = 233,
JSDocArrayType = 234,
JSDocUnionType = 235,
JSDocTupleType = 236,
JSDocNullableType = 237,
JSDocNonNullableType = 238,
JSDocRecordType = 239,
JSDocRecordMember = 240,
JSDocTypeReference = 241,
JSDocOptionalType = 242,
JSDocFunctionType = 243,
JSDocVariadicType = 244,
JSDocConstructorType = 245,
JSDocThisType = 246,
JSDocComment = 247,
JSDocTag = 248,
JSDocParameterTag = 249,
JSDocReturnTag = 250,
JSDocTypeTag = 251,
JSDocTemplateTag = 252,
SyntaxList = 253,
Count = 254,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
LastReservedWord = 101,
FirstKeyword = 66,
LastKeyword = 127,
FirstFutureReservedWord = 102,
LastFutureReservedWord = 110,
FirstTypeNode = 144,
LastTypeNode = 152,
LessThanSlashToken = 25,
GreaterThanToken = 26,
LessThanEqualsToken = 27,
GreaterThanEqualsToken = 28,
EqualsEqualsToken = 29,
ExclamationEqualsToken = 30,
EqualsEqualsEqualsToken = 31,
ExclamationEqualsEqualsToken = 32,
EqualsGreaterThanToken = 33,
PlusToken = 34,
MinusToken = 35,
AsteriskToken = 36,
SlashToken = 37,
PercentToken = 38,
PlusPlusToken = 39,
MinusMinusToken = 40,
LessThanLessThanToken = 41,
GreaterThanGreaterThanToken = 42,
GreaterThanGreaterThanGreaterThanToken = 43,
AmpersandToken = 44,
BarToken = 45,
CaretToken = 46,
ExclamationToken = 47,
TildeToken = 48,
AmpersandAmpersandToken = 49,
BarBarToken = 50,
QuestionToken = 51,
ColonToken = 52,
AtToken = 53,
EqualsToken = 54,
PlusEqualsToken = 55,
MinusEqualsToken = 56,
AsteriskEqualsToken = 57,
SlashEqualsToken = 58,
PercentEqualsToken = 59,
LessThanLessThanEqualsToken = 60,
GreaterThanGreaterThanEqualsToken = 61,
GreaterThanGreaterThanGreaterThanEqualsToken = 62,
AmpersandEqualsToken = 63,
BarEqualsToken = 64,
CaretEqualsToken = 65,
Identifier = 66,
BreakKeyword = 67,
CaseKeyword = 68,
CatchKeyword = 69,
ClassKeyword = 70,
ConstKeyword = 71,
ContinueKeyword = 72,
DebuggerKeyword = 73,
DefaultKeyword = 74,
DeleteKeyword = 75,
DoKeyword = 76,
ElseKeyword = 77,
EnumKeyword = 78,
ExportKeyword = 79,
ExtendsKeyword = 80,
FalseKeyword = 81,
FinallyKeyword = 82,
ForKeyword = 83,
FunctionKeyword = 84,
IfKeyword = 85,
ImportKeyword = 86,
InKeyword = 87,
InstanceOfKeyword = 88,
NewKeyword = 89,
NullKeyword = 90,
ReturnKeyword = 91,
SuperKeyword = 92,
SwitchKeyword = 93,
ThisKeyword = 94,
ThrowKeyword = 95,
TrueKeyword = 96,
TryKeyword = 97,
TypeOfKeyword = 98,
VarKeyword = 99,
VoidKeyword = 100,
WhileKeyword = 101,
WithKeyword = 102,
ImplementsKeyword = 103,
InterfaceKeyword = 104,
LetKeyword = 105,
PackageKeyword = 106,
PrivateKeyword = 107,
ProtectedKeyword = 108,
PublicKeyword = 109,
StaticKeyword = 110,
YieldKeyword = 111,
AbstractKeyword = 112,
AsKeyword = 113,
AnyKeyword = 114,
AsyncKeyword = 115,
AwaitKeyword = 116,
BooleanKeyword = 117,
ConstructorKeyword = 118,
DeclareKeyword = 119,
GetKeyword = 120,
IsKeyword = 121,
ModuleKeyword = 122,
NamespaceKeyword = 123,
RequireKeyword = 124,
NumberKeyword = 125,
SetKeyword = 126,
StringKeyword = 127,
SymbolKeyword = 128,
TypeKeyword = 129,
FromKeyword = 130,
OfKeyword = 131,
QualifiedName = 132,
ComputedPropertyName = 133,
TypeParameter = 134,
Parameter = 135,
Decorator = 136,
PropertySignature = 137,
PropertyDeclaration = 138,
MethodSignature = 139,
MethodDeclaration = 140,
Constructor = 141,
GetAccessor = 142,
SetAccessor = 143,
CallSignature = 144,
ConstructSignature = 145,
IndexSignature = 146,
TypePredicate = 147,
TypeReference = 148,
FunctionType = 149,
ConstructorType = 150,
TypeQuery = 151,
TypeLiteral = 152,
ArrayType = 153,
TupleType = 154,
UnionType = 155,
IntersectionType = 156,
ParenthesizedType = 157,
ObjectBindingPattern = 158,
ArrayBindingPattern = 159,
BindingElement = 160,
ArrayLiteralExpression = 161,
ObjectLiteralExpression = 162,
PropertyAccessExpression = 163,
ElementAccessExpression = 164,
CallExpression = 165,
NewExpression = 166,
TaggedTemplateExpression = 167,
TypeAssertionExpression = 168,
ParenthesizedExpression = 169,
FunctionExpression = 170,
ArrowFunction = 171,
DeleteExpression = 172,
TypeOfExpression = 173,
VoidExpression = 174,
AwaitExpression = 175,
PrefixUnaryExpression = 176,
PostfixUnaryExpression = 177,
BinaryExpression = 178,
ConditionalExpression = 179,
TemplateExpression = 180,
YieldExpression = 181,
SpreadElementExpression = 182,
ClassExpression = 183,
OmittedExpression = 184,
ExpressionWithTypeArguments = 185,
AsExpression = 186,
TemplateSpan = 187,
SemicolonClassElement = 188,
Block = 189,
VariableStatement = 190,
EmptyStatement = 191,
ExpressionStatement = 192,
IfStatement = 193,
DoStatement = 194,
WhileStatement = 195,
ForStatement = 196,
ForInStatement = 197,
ForOfStatement = 198,
ContinueStatement = 199,
BreakStatement = 200,
ReturnStatement = 201,
WithStatement = 202,
SwitchStatement = 203,
LabeledStatement = 204,
ThrowStatement = 205,
TryStatement = 206,
DebuggerStatement = 207,
VariableDeclaration = 208,
VariableDeclarationList = 209,
FunctionDeclaration = 210,
ClassDeclaration = 211,
InterfaceDeclaration = 212,
TypeAliasDeclaration = 213,
EnumDeclaration = 214,
ModuleDeclaration = 215,
ModuleBlock = 216,
CaseBlock = 217,
ImportEqualsDeclaration = 218,
ImportDeclaration = 219,
ImportClause = 220,
NamespaceImport = 221,
NamedImports = 222,
ImportSpecifier = 223,
ExportAssignment = 224,
ExportDeclaration = 225,
NamedExports = 226,
ExportSpecifier = 227,
MissingDeclaration = 228,
ExternalModuleReference = 229,
JsxElement = 230,
JsxSelfClosingElement = 231,
JsxOpeningElement = 232,
JsxText = 233,
JsxClosingElement = 234,
JsxAttribute = 235,
JsxSpreadAttribute = 236,
JsxExpression = 237,
CaseClause = 238,
DefaultClause = 239,
HeritageClause = 240,
CatchClause = 241,
PropertyAssignment = 242,
ShorthandPropertyAssignment = 243,
EnumMember = 244,
SourceFile = 245,
JSDocTypeExpression = 246,
JSDocAllType = 247,
JSDocUnknownType = 248,
JSDocArrayType = 249,
JSDocUnionType = 250,
JSDocTupleType = 251,
JSDocNullableType = 252,
JSDocNonNullableType = 253,
JSDocRecordType = 254,
JSDocRecordMember = 255,
JSDocTypeReference = 256,
JSDocOptionalType = 257,
JSDocFunctionType = 258,
JSDocVariadicType = 259,
JSDocConstructorType = 260,
JSDocThisType = 261,
JSDocComment = 262,
JSDocTag = 263,
JSDocParameterTag = 264,
JSDocReturnTag = 265,
JSDocTypeTag = 266,
JSDocTemplateTag = 267,
SyntaxList = 268,
Count = 269,
FirstAssignment = 54,
LastAssignment = 65,
FirstReservedWord = 67,
LastReservedWord = 102,
FirstKeyword = 67,
LastKeyword = 131,
FirstFutureReservedWord = 103,
LastFutureReservedWord = 111,
FirstTypeNode = 148,
LastTypeNode = 157,
FirstPunctuation = 14,
LastPunctuation = 64,
LastPunctuation = 65,
FirstToken = 0,
LastToken = 127,
LastToken = 131,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
@ -305,8 +320,8 @@ declare namespace ts {
FirstTemplateToken = 10,
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 64,
FirstNode = 128,
LastBinaryOperator = 65,
FirstNode = 132,
}
const enum NodeFlags {
Export = 1,
@ -315,18 +330,28 @@ declare namespace ts {
Private = 32,
Protected = 64,
Static = 128,
Default = 256,
MultiLine = 512,
Synthetic = 1024,
DeclarationFile = 2048,
Let = 4096,
Const = 8192,
OctalLiteral = 16384,
Namespace = 32768,
ExportContext = 65536,
Modifier = 499,
Abstract = 256,
Async = 512,
Default = 1024,
MultiLine = 2048,
Synthetic = 4096,
DeclarationFile = 8192,
Let = 16384,
Const = 32768,
OctalLiteral = 65536,
Namespace = 131072,
ExportContext = 262144,
Modifier = 2035,
AccessibilityModifier = 112,
BlockScoped = 12288,
BlockScoped = 49152,
}
const enum JsxFlags {
None = 0,
IntrinsicNamedElement = 1,
IntrinsicIndexedElement = 2,
ClassElement = 4,
UnknownElement = 8,
IntrinsicElement = 3,
}
interface Node extends TextRange {
kind: SyntaxKind;
@ -483,9 +508,13 @@ declare namespace ts {
interface TupleTypeNode extends TypeNode {
elementTypes: NodeArray<TypeNode>;
}
interface UnionTypeNode extends TypeNode {
interface UnionOrIntersectionTypeNode extends TypeNode {
types: NodeArray<TypeNode>;
}
interface UnionTypeNode extends UnionOrIntersectionTypeNode {
}
interface IntersectionTypeNode extends UnionOrIntersectionTypeNode {
}
interface ParenthesizedTypeNode extends TypeNode {
type: TypeNode;
}
@ -528,6 +557,9 @@ declare namespace ts {
interface VoidExpression extends UnaryExpression {
expression: UnaryExpression;
}
interface AwaitExpression extends UnaryExpression {
expression: UnaryExpression;
}
interface YieldExpression extends Expression {
asteriskToken?: Node;
expression?: Expression;
@ -601,10 +633,46 @@ declare namespace ts {
template: LiteralExpression | TemplateExpression;
}
type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
interface AsExpression extends Expression {
expression: Expression;
type: TypeNode;
}
interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
closingElement: JsxClosingElement;
}
interface JsxOpeningElement extends Expression {
_openingElementBrand?: any;
tagName: EntityName;
attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>;
}
interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement {
_selfClosingElementBrand?: any;
}
type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
interface JsxAttribute extends Node {
name: Identifier;
initializer?: Expression;
}
interface JsxSpreadAttribute extends Node {
expression: Expression;
}
interface JsxClosingElement extends Node {
tagName: EntityName;
}
interface JsxExpression extends Expression {
expression?: Expression;
}
interface JsxText extends Node {
_jsxTextExpressionBrand: any;
}
type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement;
interface Statement extends Node {
_statementBrand: any;
}
@ -859,6 +927,7 @@ declare namespace ts {
}[];
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
/**
* lib.d.ts should have a reference comment like
*
@ -881,6 +950,13 @@ declare namespace ts {
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
class OperationCanceledException {
}
interface CancellationToken {
isCancellationRequested(): boolean;
/** @throws OperationCanceledException if isCancellationRequested is true */
throwIfCancellationRequested(): void;
}
interface Program extends ScriptReferenceHost {
/**
* Get a list of files in the program
@ -896,12 +972,12 @@ declare namespace ts {
* used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
* will be invoked when writing the JavaScript and declaration files.
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
getOptionsDiagnostics(): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
@ -976,6 +1052,8 @@ declare namespace ts {
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@ -1053,7 +1131,7 @@ declare namespace ts {
Merged = 33554432,
Transient = 67108864,
Prototype = 134217728,
UnionProperty = 268435456,
SyntheticProperty = 268435456,
Optional = 536870912,
ExportStar = 1073741824,
Enum = 384,
@ -1069,8 +1147,8 @@ declare namespace ts {
PropertyExcludes = 107455,
EnumMemberExcludes = 107455,
FunctionExcludes = 106927,
ClassExcludes = 899583,
InterfaceExcludes = 792992,
ClassExcludes = 899519,
InterfaceExcludes = 792960,
RegularEnumExcludes = 899327,
ConstEnumExcludes = 899967,
ValueModuleExcludes = 106639,
@ -1116,13 +1194,16 @@ declare namespace ts {
Reference = 4096,
Tuple = 8192,
Union = 16384,
Anonymous = 32768,
Instantiated = 65536,
ObjectLiteral = 262144,
ESSymbol = 2097152,
Intersection = 32768,
Anonymous = 65536,
Instantiated = 131072,
ObjectLiteral = 524288,
ESSymbol = 4194304,
StringLike = 258,
NumberLike = 132,
ObjectType = 48128,
ObjectType = 80896,
UnionOrIntersection = 49152,
StructuredType = 130048,
}
interface Type {
flags: TypeFlags;
@ -1157,9 +1238,13 @@ declare namespace ts {
elementTypes: Type[];
baseArrayType: TypeReference;
}
interface UnionType extends Type {
interface UnionOrIntersectionType extends Type {
types: Type[];
}
interface UnionType extends UnionOrIntersectionType {
}
interface IntersectionType extends UnionOrIntersectionType {
}
interface TypeParameter extends Type {
constraint: Type;
}
@ -1216,6 +1301,7 @@ declare namespace ts {
help?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
listFiles?: boolean;
locale?: string;
mapRoot?: string;
@ -1242,6 +1328,7 @@ declare namespace ts {
watch?: boolean;
isolatedModules?: boolean;
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
[option: string]: string | number | boolean;
}
@ -1252,6 +1339,11 @@ declare namespace ts {
UMD = 3,
System = 4,
}
const enum JsxEmit {
None = 0,
Preserve = 1,
React = 2,
}
const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
@ -1266,18 +1358,18 @@ declare namespace ts {
ES6 = 2,
Latest = 2,
}
const enum LanguageVariant {
Standard = 0,
JSX = 1,
}
interface ParsedCommandLine {
options: CompilerOptions;
fileNames: string[];
errors: Diagnostic[];
}
interface CancellationToken {
isCancellationRequested(): boolean;
}
interface CompilerHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getDefaultLibFileName(options: CompilerOptions): string;
getCancellationToken?(): CancellationToken;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
@ -1336,10 +1428,14 @@ declare namespace ts {
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scan(): SyntaxKind;
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
setScriptTarget(scriptTarget: ScriptTarget): void;
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
lookAhead<T>(callback: () => T): T;
tryScan<T>(callback: () => T): T;
@ -1397,7 +1493,7 @@ declare namespace ts {
const version: string;
function findConfigFile(searchPath: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[];
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
@ -1504,6 +1600,9 @@ declare namespace ts {
importedFiles: FileReference[];
isLibFile: boolean;
}
interface HostCancellationToken {
isCancellationRequested(): boolean;
}
interface LanguageServiceHost {
getCompilationSettings(): CompilerOptions;
getNewLine?(): string;
@ -1512,7 +1611,7 @@ declare namespace ts {
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): CancellationToken;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
getDefaultLibFileName(options: CompilerOptions): string;
log?(s: string): void;
@ -1892,6 +1991,7 @@ declare namespace ts {
const scriptElement: string;
const moduleElement: string;
const classElement: string;
const localClassElement: string;
const interfaceElement: string;
const typeElement: string;
const enumElement: string;
@ -1923,6 +2023,7 @@ declare namespace ts {
const exportedModifier: string;
const ambientModifier: string;
const staticModifier: string;
const abstractModifier: string;
}
class ClassificationTypeNames {
static comment: string;
@ -1968,15 +2069,6 @@ declare namespace ts {
}
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
class OperationCanceledException {
}
class CancellationTokenObject {
private cancellationToken;
static None: CancellationTokenObject;
constructor(cancellationToken: CancellationToken);
isCancellationRequested(): boolean;
throwIfCancellationRequested(): void;
}
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
@ -1986,7 +2078,7 @@ declare namespace ts {
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
function createClassifier(): Classifier;
/**
* Get the path of the default library file (lib.d.ts) as distributed with the typescript
* Get the path of the default library files (lib.d.ts) as distributed with the typescript
* node package.
* The functionality is not supported if the ts module is consumed outside of a node module.
*/

File diff suppressed because it is too large Load Diff

View File

@ -34,6 +34,7 @@
"chai": "latest",
"browserify": "latest",
"istanbul": "latest",
"mocha-fivemat-progress-reporter": "latest",
"tslint": "latest"
},
"scripts": {

View File

@ -876,7 +876,7 @@ namespace ts {
}
// Resolves a qualified name and any involved aliases
function resolveEntityName(name: EntityName | Expression, meaning: SymbolFlags): Symbol {
function resolveEntityName(name: EntityName | Expression, meaning: SymbolFlags, ignoreErrors?: boolean): Symbol {
if (nodeIsMissing(name)) {
return undefined;
}
@ -885,7 +885,7 @@ namespace ts {
if (name.kind === SyntaxKind.Identifier) {
let message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0;
symbol = resolveName(name, (<Identifier>name).text, meaning, message, <Identifier>name);
symbol = resolveName(name, (<Identifier>name).text, meaning, ignoreErrors ? undefined : message, <Identifier>name);
if (!symbol) {
return undefined;
}
@ -894,13 +894,15 @@ namespace ts {
let left = name.kind === SyntaxKind.QualifiedName ? (<QualifiedName>name).left : (<PropertyAccessExpression>name).expression;
let right = name.kind === SyntaxKind.QualifiedName ? (<QualifiedName>name).right : (<PropertyAccessExpression>name).name;
let namespace = resolveEntityName(left, SymbolFlags.Namespace);
let namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors);
if (!namespace || namespace === unknownSymbol || nodeIsMissing(right)) {
return undefined;
}
symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning);
if (!symbol) {
error(right, Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), declarationNameToString(right));
if (!ignoreErrors) {
error(right, Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), declarationNameToString(right));
}
return undefined;
}
}
@ -2486,10 +2488,6 @@ namespace ts {
return links.type;
}
function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode {
return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type;
}
function getAnnotatedAccessorType(accessor: AccessorDeclaration): Type {
if (accessor) {
if (accessor.kind === SyntaxKind.GetAccessor) {
@ -3381,6 +3379,15 @@ namespace ts {
return getSignaturesOfStructuredType(getApparentType(type), kind);
}
function typeHasConstructSignatures(type: Type): boolean {
let apparentType = getApparentType(type);
if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Union)) {
let resolved = resolveStructuredTypeMembers(<ObjectType>type);
return resolved.constructSignatures.length > 0;
}
return false;
}
function typeHasCallOrConstructSignatures(type: Type): boolean {
let apparentType = getApparentType(type);
if (apparentType.flags & TypeFlags.StructuredType) {
@ -3936,7 +3943,7 @@ namespace ts {
let id = getTypeListId(elementTypes);
let type = tupleTypes[id];
if (!type) {
type = tupleTypes[id] = <TupleType>createObjectType(TypeFlags.Tuple);
type = tupleTypes[id] = <TupleType>createObjectType(TypeFlags.Tuple | getWideningFlagsOfTypes(elementTypes));
type.elementTypes = elementTypes;
}
return type;
@ -4896,9 +4903,38 @@ namespace ts {
let targetSignatures = getSignaturesOfType(target, kind);
let result = Ternary.True;
let saveErrorInfo = errorInfo;
// Because the "abstractness" of a class is the same across all construct signatures
// (internally we are checking the corresponding declaration), it is enough to perform
// the check and report an error once over all pairs of source and target construct signatures.
let sourceSig = sourceSignatures[0];
// Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds.
let targetSig = targetSignatures[0];
if (sourceSig && targetSig) {
let sourceErasedSignature = getErasedSignature(sourceSig);
let targetErasedSignature = getErasedSignature(targetSig);
let sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature);
let targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature);
let sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getDeclarationOfKind(sourceReturnType.symbol, SyntaxKind.ClassDeclaration);
let targetReturnDecl = targetReturnType && targetReturnType.symbol && getDeclarationOfKind(targetReturnType.symbol, SyntaxKind.ClassDeclaration);
let sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract;
let targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract;
if (sourceIsAbstract && !targetIsAbstract) {
if (reportErrors) {
reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
}
return Ternary.False;
}
}
outer: for (let t of targetSignatures) {
if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) {
let localErrors = reportErrors;
let checkedAbstractAssignability = false;
for (let s of sourceSignatures) {
if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) {
let related = signatureRelatedTo(s, t, localErrors);
@ -5005,10 +5041,11 @@ namespace ts {
return Ternary.False;
}
let t = getReturnTypeOfSignature(target);
if (t === voidType) return result;
let s = getReturnTypeOfSignature(source);
return result & isRelatedTo(s, t, reportErrors);
let targetReturnType = getReturnTypeOfSignature(target);
if (targetReturnType === voidType) return result;
let sourceReturnType = getReturnTypeOfSignature(source);
return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors);
}
function signaturesIdenticalTo(source: Type, target: Type, kind: SignatureKind): Ternary {
@ -5262,8 +5299,8 @@ namespace ts {
* Check if a Type was written as a tuple type literal.
* Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
*/
function isTupleType(type: Type): boolean {
return (type.flags & TypeFlags.Tuple) && !!(<TupleType>type).elementTypes;
function isTupleType(type: Type): type is TupleType {
return !!(type.flags & TypeFlags.Tuple);
}
function getWidenedTypeOfObjectLiteral(type: Type): Type {
@ -5304,26 +5341,45 @@ namespace ts {
if (isArrayType(type)) {
return createArrayType(getWidenedType((<TypeReference>type).typeArguments[0]));
}
if (isTupleType(type)) {
return createTupleType(map(type.elementTypes, getWidenedType));
}
}
return type;
}
/**
* Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
* to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
* getWidenedType. But in some cases getWidenedType is called without reporting errors
* (type argument inference is an example).
*
* The return value indicates whether an error was in fact reported. The particular circumstances
* are on a best effort basis. Currently, if the null or undefined that causes widening is inside
* an object literal property (arbitrarily deeply), this function reports an error. If no error is
* reported, reportImplicitAnyError is a suitable fallback to report a general error.
*/
function reportWideningErrorsInType(type: Type): boolean {
let errorReported = false;
if (type.flags & TypeFlags.Union) {
let errorReported = false;
forEach((<UnionType>type).types, t => {
for (let t of (<UnionType>type).types) {
if (reportWideningErrorsInType(t)) {
errorReported = true;
}
});
return errorReported;
}
}
if (isArrayType(type)) {
return reportWideningErrorsInType((<TypeReference>type).typeArguments[0]);
}
if (isTupleType(type)) {
for (let t of type.elementTypes) {
if (reportWideningErrorsInType(t)) {
errorReported = true;
}
}
}
if (type.flags & TypeFlags.ObjectLiteral) {
let errorReported = false;
forEach(getPropertiesOfObjectType(type), p => {
for (let p of getPropertiesOfObjectType(type)) {
let t = getTypeOfSymbol(p);
if (t.flags & TypeFlags.ContainsUndefinedOrNull) {
if (!reportWideningErrorsInType(t)) {
@ -5331,10 +5387,9 @@ namespace ts {
}
errorReported = true;
}
});
return errorReported;
}
}
return false;
return errorReported;
}
function reportImplicitAnyError(declaration: Declaration, type: Type) {
@ -5501,30 +5556,33 @@ namespace ts {
inferFromTypes(sourceType, target);
}
}
else if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) ||
(target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) {
// If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members
if (isInProcess(source, target)) {
return;
}
if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) {
return;
}
else {
source = getApparentType(source);
if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) ||
(target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) {
// If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members
if (isInProcess(source, target)) {
return;
}
if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) {
return;
}
if (depth === 0) {
sourceStack = [];
targetStack = [];
if (depth === 0) {
sourceStack = [];
targetStack = [];
}
sourceStack[depth] = source;
targetStack[depth] = target;
depth++;
inferFromProperties(source, target);
inferFromSignatures(source, target, SignatureKind.Call);
inferFromSignatures(source, target, SignatureKind.Construct);
inferFromIndexTypes(source, target, IndexKind.String, IndexKind.String);
inferFromIndexTypes(source, target, IndexKind.Number, IndexKind.Number);
inferFromIndexTypes(source, target, IndexKind.String, IndexKind.Number);
depth--;
}
sourceStack[depth] = source;
targetStack[depth] = target;
depth++;
inferFromProperties(source, target);
inferFromSignatures(source, target, SignatureKind.Call);
inferFromSignatures(source, target, SignatureKind.Construct);
inferFromIndexTypes(source, target, IndexKind.String, IndexKind.String);
inferFromIndexTypes(source, target, IndexKind.Number, IndexKind.Number);
inferFromIndexTypes(source, target, IndexKind.String, IndexKind.Number);
depth--;
}
}
@ -6765,7 +6823,7 @@ namespace ts {
let restArrayType = checkExpression((<SpreadElementExpression>e).expression, contextualMapper);
let restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) ||
(languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined);
if (restElementType) {
if (restElementType) {
elementTypes.push(restElementType);
}
}
@ -6924,7 +6982,6 @@ namespace ts {
}
}
function checkJsxSelfClosingElement(node: JsxSelfClosingElement) {
checkJsxOpeningLikeElement(node);
return jsxElementType || anyType;
@ -8012,8 +8069,8 @@ namespace ts {
return args;
}
/**
/**
* Returns the effective argument count for a node that works like a function invocation.
* If 'node' is a Decorator, the number of arguments is derived from the decoration
* target and the signature:
@ -8090,11 +8147,11 @@ namespace ts {
let classSymbol = getSymbolOfNode(node);
return getTypeOfSymbol(classSymbol);
}
// fall-through
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
// For a property or method decorator, the `target` is the
@ -8137,14 +8194,14 @@ namespace ts {
// For a constructor parameter decorator, the `propertyKey` will be `undefined`.
return anyType;
}
// For a non-constructor parameter decorator, the `propertyKey` will be either
// a string or a symbol, based on the name of the parameter's containing method.
// fall-through
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
// The `propertyKey` for a property or method decorator will be a
@ -8172,8 +8229,8 @@ namespace ts {
return unknownType;
}
default:
default:
Debug.fail("Unsupported decorator target.");
return unknownType;
}
@ -10981,13 +11038,10 @@ namespace ts {
// as if it were an expression so that we can emit the type in a value position when we
// serialize the type metadata.
if (node && node.kind === SyntaxKind.TypeReference) {
let type = getTypeFromTypeNode(node);
let shouldCheckIfUnknownType = type === unknownType && compilerOptions.isolatedModules;
if (!type || (!shouldCheckIfUnknownType && type.flags & (TypeFlags.Intrinsic | TypeFlags.NumberLike | TypeFlags.StringLike))) {
return;
}
if (shouldCheckIfUnknownType || type.symbol.valueDeclaration) {
checkExpression((<TypeReferenceNode>node).typeName);
let root = getFirstIdentifier((<TypeReferenceNode>node).typeName);
let rootSymbol = resolveName(root, root.text, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined);
if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) {
markAliasSymbolAsReferenced(rootSymbol);
}
}
}
@ -11459,19 +11513,19 @@ namespace ts {
forEach(node.declarationList.declarations, checkSourceElement);
}
function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node: Node) {
function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node: Node) {
// We only disallow modifier on a method declaration if it is a property of object-literal-expression
if (node.modifiers && node.parent.kind === SyntaxKind.ObjectLiteralExpression){
if (isAsyncFunctionLike(node)) {
if (node.modifiers.length > 1) {
return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here);
return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here);
}
}
else {
return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here);
}
}
}
}
function checkExpressionStatement(node: ExpressionStatement) {
// Grammar checking
@ -12812,7 +12866,7 @@ namespace ts {
Debug.assert(node.kind === SyntaxKind.Identifier);
return <Identifier>node;
}
function checkExternalImportOrExportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean {
let moduleName = getExternalModuleName(node);
if (!nodeIsMissing(moduleName) && moduleName.kind !== SyntaxKind.StringLiteral) {
@ -13958,205 +14012,54 @@ namespace ts {
return undefined;
}
/** Serializes an EntityName (with substitutions) to an appropriate JS constructor value. Used by the __metadata decorator. */
function serializeEntityName(node: EntityName, fallbackPath?: string[]): string {
if (node.kind === SyntaxKind.Identifier) {
// TODO(ron.buckton): The getExpressionNameSubstitution function has been removed, but calling it
// here has no effect anyway as an identifier in a type name is not an expression.
// var substitution = getExpressionNameSubstitution(<Identifier>node, getGeneratedNameForNode);
// var text = substitution || (<Identifier>node).text;
let text = (<Identifier>node).text;
if (fallbackPath) {
fallbackPath.push(text);
}
else {
return text;
}
function isFunctionType(type: Type): boolean {
return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Call).length > 0;
}
function getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind {
// Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
let symbol = resolveEntityName(node.typeName, SymbolFlags.Value, /*ignoreErrors*/ true);
let constructorType = symbol ? getTypeOfSymbol(symbol) : undefined;
if (constructorType && isConstructorType(constructorType)) {
return TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
}
let type = getTypeFromTypeNode(node);
if (type === unknownType) {
return TypeReferenceSerializationKind.Unknown;
}
else if (type.flags & TypeFlags.Any) {
return TypeReferenceSerializationKind.ObjectType;
}
else if (allConstituentTypesHaveKind(type, TypeFlags.Void)) {
return TypeReferenceSerializationKind.VoidType;
}
else if (allConstituentTypesHaveKind(type, TypeFlags.Boolean)) {
return TypeReferenceSerializationKind.BooleanType;
}
else if (allConstituentTypesHaveKind(type, TypeFlags.NumberLike)) {
return TypeReferenceSerializationKind.NumberLikeType;
}
else if (allConstituentTypesHaveKind(type, TypeFlags.StringLike)) {
return TypeReferenceSerializationKind.StringLikeType;
}
else if (allConstituentTypesHaveKind(type, TypeFlags.Tuple)) {
return TypeReferenceSerializationKind.ArrayLikeType;
}
else if (allConstituentTypesHaveKind(type, TypeFlags.ESSymbol)) {
return TypeReferenceSerializationKind.ESSymbolType;
}
else if (isFunctionType(type)) {
return TypeReferenceSerializationKind.TypeWithCallSignature;
}
else if (isArrayType(type)) {
return TypeReferenceSerializationKind.ArrayLikeType;
}
else {
let left = serializeEntityName((<QualifiedName>node).left, fallbackPath);
let right = serializeEntityName((<QualifiedName>node).right, fallbackPath);
if (!fallbackPath) {
return left + "." + right;
}
return TypeReferenceSerializationKind.ObjectType;
}
}
/** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */
function serializeTypeReferenceNode(node: TypeReferenceNode): string | string[] {
// serialization of a TypeReferenceNode uses the following rules:
//
// * The serialized type of a TypeReference that is `void` is "void 0".
// * The serialized type of a TypeReference that is a `boolean` is "Boolean".
// * The serialized type of a TypeReference that is an enum or `number` is "Number".
// * The serialized type of a TypeReference that is a string literal or `string` is "String".
// * The serialized type of a TypeReference that is a tuple is "Array".
// * The serialized type of a TypeReference that is a `symbol` is "Symbol".
// * The serialized type of a TypeReference with a value declaration is its entity name.
// * The serialized type of a TypeReference with a call or construct signature is "Function".
// * The serialized type of any other type is "Object".
let type = getTypeFromTypeNode(node);
if (type.flags & TypeFlags.Void) {
return "void 0";
}
else if (type.flags & TypeFlags.Boolean) {
return "Boolean";
}
else if (type.flags & TypeFlags.NumberLike) {
return "Number";
}
else if (type.flags & TypeFlags.StringLike) {
return "String";
}
else if (type.flags & TypeFlags.Tuple) {
return "Array";
}
else if (type.flags & TypeFlags.ESSymbol) {
return "Symbol";
}
else if (type === unknownType) {
let fallbackPath: string[] = [];
serializeEntityName(node.typeName, fallbackPath);
return fallbackPath;
}
else if (type.symbol && type.symbol.valueDeclaration) {
return serializeEntityName(node.typeName);
}
else if (typeHasCallOrConstructSignatures(type)) {
return "Function";
}
return "Object";
}
/** Serializes a TypeNode to an appropriate JS constructor value. Used by the __metadata decorator. */
function serializeTypeNode(node: TypeNode | LiteralExpression): string | string[] {
// serialization of a TypeNode uses the following rules:
//
// * The serialized type of `void` is "void 0" (undefined).
// * The serialized type of a parenthesized type is the serialized type of its nested type.
// * The serialized type of a Function or Constructor type is "Function".
// * The serialized type of an Array or Tuple type is "Array".
// * The serialized type of `boolean` is "Boolean".
// * The serialized type of `string` or a string-literal type is "String".
// * The serialized type of a type reference is handled by `serializeTypeReferenceNode`.
// * The serialized type of any other type node is "Object".
if (node) {
switch (node.kind) {
case SyntaxKind.VoidKeyword:
return "void 0";
case SyntaxKind.ParenthesizedType:
return serializeTypeNode((<ParenthesizedTypeNode>node).type);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return "Function";
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
return "Array";
case SyntaxKind.BooleanKeyword:
return "Boolean";
case SyntaxKind.StringKeyword:
case SyntaxKind.StringLiteral:
return "String";
case SyntaxKind.NumberKeyword:
return "Number";
case SyntaxKind.TypeReference:
return serializeTypeReferenceNode(<TypeReferenceNode>node);
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeLiteral:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.AnyKeyword:
break;
default:
Debug.fail("Cannot serialize unexpected type node.");
break;
}
}
return "Object";
}
/** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */
function serializeTypeOfNode(node: Node): string | string[] {
// serialization of the type of a declaration uses the following rules:
//
// * The serialized type of a ClassDeclaration is "Function"
// * The serialized type of a ParameterDeclaration is the serialized type of its type annotation.
// * The serialized type of a PropertyDeclaration is the serialized type of its type annotation.
// * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter.
// * The serialized type of any other FunctionLikeDeclaration is "Function".
// * The serialized type of any other node is "void 0".
//
// For rules on serializing type annotations, see `serializeTypeNode`.
switch (node.kind) {
case SyntaxKind.ClassDeclaration: return "Function";
case SyntaxKind.PropertyDeclaration: return serializeTypeNode((<PropertyDeclaration>node).type);
case SyntaxKind.Parameter: return serializeTypeNode((<ParameterDeclaration>node).type);
case SyntaxKind.GetAccessor: return serializeTypeNode((<AccessorDeclaration>node).type);
case SyntaxKind.SetAccessor: return serializeTypeNode(getSetAccessorTypeAnnotationNode(<AccessorDeclaration>node));
}
if (isFunctionLike(node)) {
return "Function";
}
return "void 0";
}
/** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */
function serializeParameterTypesOfNode(node: Node): (string | string[])[] {
// serialization of parameter types uses the following rules:
//
// * If the declaration is a class, the parameters of the first constructor with a body are used.
// * If the declaration is function-like and has a body, the parameters of the function are used.
//
// For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.
if (node) {
let valueDeclaration: FunctionLikeDeclaration;
if (node.kind === SyntaxKind.ClassDeclaration) {
valueDeclaration = getFirstConstructorWithBody(<ClassDeclaration>node);
}
else if (isFunctionLike(node) && nodeIsPresent((<FunctionLikeDeclaration>node).body)) {
valueDeclaration = <FunctionLikeDeclaration>node;
}
if (valueDeclaration) {
let result: (string | string[])[];
let parameters = valueDeclaration.parameters;
let parameterCount = parameters.length;
if (parameterCount > 0) {
result = new Array<string>(parameterCount);
for (let i = 0; i < parameterCount; i++) {
if (parameters[i].dotDotDotToken) {
let parameterType = parameters[i].type;
if (parameterType.kind === SyntaxKind.ArrayType) {
parameterType = (<ArrayTypeNode>parameterType).elementType;
}
else if (parameterType.kind === SyntaxKind.TypeReference && (<TypeReferenceNode>parameterType).typeArguments && (<TypeReferenceNode>parameterType).typeArguments.length === 1) {
parameterType = (<TypeReferenceNode>parameterType).typeArguments[0];
}
else {
parameterType = undefined;
}
result[i] = serializeTypeNode(parameterType);
}
else {
result[i] = serializeTypeOfNode(parameters[i]);
}
}
return result;
}
}
}
return emptyArray;
}
/** Serializes the return type of function. Used by the __metadata decorator for a method. */
function serializeReturnTypeOfNode(node: Node): string | string[] {
if (node && isFunctionLike(node)) {
return serializeTypeNode((<FunctionLikeDeclaration>node).type);
}
return "void 0";
}
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) {
// Get type of the symbol if this is the valid symbol otherwise get type at location
let symbol = getSymbolOfNode(declaration);
@ -14254,9 +14157,7 @@ namespace ts {
collectLinkedAliases,
getBlockScopedVariableId,
getReferencedValueDeclaration,
serializeTypeOfNode,
serializeParameterTypesOfNode,
serializeReturnTypeOfNode,
getTypeReferenceSerializationKind,
};
}
@ -14516,7 +14417,7 @@ namespace ts {
}
flags |= NodeFlags.Ambient;
lastDeclare = modifier;
break;
break;
case SyntaxKind.AbstractKeyword:
if (flags & NodeFlags.Abstract) {
@ -14552,7 +14453,7 @@ namespace ts {
}
flags |= NodeFlags.Async;
lastAsync = modifier;
break;
break;
}
}

View File

@ -407,7 +407,7 @@ namespace ts {
Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." },
Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." },
All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." },
Constructor_objects_of_abstract_type_cannot_be_assigned_to_constructor_objects_of_non_abstract_type: { code: 2517, category: DiagnosticCategory.Error, key: "Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type" },
Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." },
Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." },
Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." },
Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." },

View File

@ -1617,7 +1617,7 @@
"category": "Error",
"code": 2516
},
"Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type": {
"Cannot assign an abstract constructor type to a non-abstract constructor type.": {
"category": "Error",
"code":2517
},

View File

@ -2015,13 +2015,52 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.name);
decreaseIndentIf(indentedBeforeDot, indentedAfterDot);
}
function emitQualifiedName(node: QualifiedName) {
emit(node.left);
write(".");
emit(node.right);
}
function emitQualifiedNameAsExpression(node: QualifiedName, useFallback: boolean) {
if (node.left.kind === SyntaxKind.Identifier) {
emitEntityNameAsExpression(node.left, useFallback);
}
else if (useFallback) {
let temp = createAndRecordTempVariable(TempFlags.Auto);
write("(");
emitNodeWithoutSourceMap(temp);
write(" = ");
emitEntityNameAsExpression(node.left, /*useFallback*/ true);
write(") && ");
emitNodeWithoutSourceMap(temp);
}
else {
emitEntityNameAsExpression(node.left, /*useFallback*/ false);
}
write(".");
emitNodeWithoutSourceMap(node.right);
}
function emitEntityNameAsExpression(node: EntityName, useFallback: boolean) {
switch (node.kind) {
case SyntaxKind.Identifier:
if (useFallback) {
write("typeof ");
emitExpressionIdentifier(<Identifier>node);
write(" !== 'undefined' && ");
}
emitExpressionIdentifier(<Identifier>node);
break;
case SyntaxKind.QualifiedName:
emitQualifiedNameAsExpression(<QualifiedName>node, useFallback);
break;
}
}
function emitIndexedAccess(node: ElementAccessExpression) {
if (tryEmitConstantValue(node)) {
return;
@ -4640,83 +4679,267 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
return false;
}
/** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */
function emitSerializedTypeOfNode(node: Node) {
// serialization of the type of a declaration uses the following rules:
//
// * The serialized type of a ClassDeclaration is "Function"
// * The serialized type of a ParameterDeclaration is the serialized type of its type annotation.
// * The serialized type of a PropertyDeclaration is the serialized type of its type annotation.
// * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter.
// * The serialized type of any other FunctionLikeDeclaration is "Function".
// * The serialized type of any other node is "void 0".
//
// For rules on serializing type annotations, see `serializeTypeNode`.
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
write("Function");
return;
case SyntaxKind.PropertyDeclaration:
emitSerializedTypeNode((<PropertyDeclaration>node).type);
return;
case SyntaxKind.Parameter:
emitSerializedTypeNode((<ParameterDeclaration>node).type);
return;
case SyntaxKind.GetAccessor:
emitSerializedTypeNode((<AccessorDeclaration>node).type);
return;
case SyntaxKind.SetAccessor:
emitSerializedTypeNode(getSetAccessorTypeAnnotationNode(<AccessorDeclaration>node));
return;
}
if (isFunctionLike(node)) {
write("Function");
return;
}
write("void 0");
}
function emitSerializedTypeNode(node: TypeNode) {
switch (node.kind) {
case SyntaxKind.VoidKeyword:
write("void 0");
return;
case SyntaxKind.ParenthesizedType:
emitSerializedTypeNode((<ParenthesizedTypeNode>node).type);
return;
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
write("Function");
return;
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
write("Array");
return;
case SyntaxKind.TypePredicate:
case SyntaxKind.BooleanKeyword:
write("Boolean");
return;
case SyntaxKind.StringKeyword:
case SyntaxKind.StringLiteral:
write("String");
return;
case SyntaxKind.NumberKeyword:
write("Number");
return;
case SyntaxKind.SymbolKeyword:
write("Symbol");
return;
case SyntaxKind.TypeReference:
emitSerializedTypeReferenceNode(<TypeReferenceNode>node);
return;
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeLiteral:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.AnyKeyword:
break;
default:
Debug.fail("Cannot serialize unexpected type node.");
break;
}
write("Object");
}
/** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */
function emitSerializedTypeReferenceNode(node: TypeReferenceNode) {
let typeName = node.typeName;
let result = resolver.getTypeReferenceSerializationKind(node);
switch (result) {
case TypeReferenceSerializationKind.Unknown:
let temp = createAndRecordTempVariable(TempFlags.Auto);
write("(typeof (");
emitNodeWithoutSourceMap(temp);
write(" = ")
emitEntityNameAsExpression(typeName, /*useFallback*/ true);
write(") === 'function' && ");
emitNodeWithoutSourceMap(temp);
write(") || Object");
break;
case TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
emitEntityNameAsExpression(typeName, /*useFallback*/ false);
break;
case TypeReferenceSerializationKind.VoidType:
write("void 0");
break;
case TypeReferenceSerializationKind.BooleanType:
write("Boolean");
break;
case TypeReferenceSerializationKind.NumberLikeType:
write("Number");
break;
case TypeReferenceSerializationKind.StringLikeType:
write("String");
break;
case TypeReferenceSerializationKind.ArrayLikeType:
write("Array");
break;
case TypeReferenceSerializationKind.ESSymbolType:
if (languageVersion < ScriptTarget.ES6) {
write("typeof Symbol === 'function' ? Symbol : Object");
}
else {
write("Symbol");
}
break;
case TypeReferenceSerializationKind.TypeWithCallSignature:
write("Function");
break;
case TypeReferenceSerializationKind.ObjectType:
write("Object");
break;
}
}
/** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */
function emitSerializedParameterTypesOfNode(node: Node) {
// serialization of parameter types uses the following rules:
//
// * If the declaration is a class, the parameters of the first constructor with a body are used.
// * If the declaration is function-like and has a body, the parameters of the function are used.
//
// For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.
if (node) {
var valueDeclaration: FunctionLikeDeclaration;
if (node.kind === SyntaxKind.ClassDeclaration) {
valueDeclaration = getFirstConstructorWithBody(<ClassDeclaration>node);
}
else if (isFunctionLike(node) && nodeIsPresent((<FunctionLikeDeclaration>node).body)) {
valueDeclaration = <FunctionLikeDeclaration>node;
}
if (valueDeclaration) {
var parameters = valueDeclaration.parameters;
var parameterCount = parameters.length;
if (parameterCount > 0) {
for (var i = 0; i < parameterCount; i++) {
if (i > 0) {
write(", ");
}
if (parameters[i].dotDotDotToken) {
var parameterType = parameters[i].type;
if (parameterType.kind === SyntaxKind.ArrayType) {
parameterType = (<ArrayTypeNode>parameterType).elementType;
}
else if (parameterType.kind === SyntaxKind.TypeReference && (<TypeReferenceNode>parameterType).typeArguments && (<TypeReferenceNode>parameterType).typeArguments.length === 1) {
parameterType = (<TypeReferenceNode>parameterType).typeArguments[0];
}
else {
parameterType = undefined;
}
emitSerializedTypeNode(parameterType);
}
else {
emitSerializedTypeOfNode(parameters[i]);
}
}
}
}
}
}
/** Serializes the return type of function. Used by the __metadata decorator for a method. */
function emitSerializedReturnTypeOfNode(node: Node): string | string[] {
if (node && isFunctionLike(node)) {
emitSerializedTypeNode((<FunctionLikeDeclaration>node).type);
return;
}
write("void 0");
}
function emitSerializedTypeMetadata(node: Declaration, writeComma: boolean): number {
// This method emits the serialized type metadata for a decorator target.
// The caller should have already tested whether the node has decorators.
let argumentsWritten = 0;
if (compilerOptions.emitDecoratorMetadata) {
if (shouldEmitTypeMetadata(node)) {
let serializedType = resolver.serializeTypeOfNode(node);
if (serializedType) {
if (writeComma) {
write(", ");
}
writeLine();
write("__metadata('design:type', ");
emitSerializedType(node, serializedType);
write(")");
argumentsWritten++;
if (writeComma) {
write(", ");
}
writeLine();
write("__metadata('design:type', ");
emitSerializedTypeOfNode(node);
write(")");
argumentsWritten++;
}
if (shouldEmitParamTypesMetadata(node)) {
let serializedTypes = resolver.serializeParameterTypesOfNode(node);
if (serializedTypes) {
if (writeComma || argumentsWritten) {
write(", ");
}
writeLine();
write("__metadata('design:paramtypes', [");
for (var i = 0; i < serializedTypes.length; ++i) {
if (i > 0) {
write(", ");
}
emitSerializedType(node, serializedTypes[i]);
}
write("])");
argumentsWritten++;
if (writeComma || argumentsWritten) {
write(", ");
}
writeLine();
write("__metadata('design:paramtypes', [");
emitSerializedParameterTypesOfNode(node);
write("])");
argumentsWritten++;
}
if (shouldEmitReturnTypeMetadata(node)) {
let serializedType = resolver.serializeReturnTypeOfNode(node);
if (serializedType) {
if (writeComma || argumentsWritten) {
write(", ");
}
writeLine();
write("__metadata('design:returntype', ");
emitSerializedType(node, serializedType);
write(")");
argumentsWritten++;
if (writeComma || argumentsWritten) {
write(", ");
}
writeLine();
write("__metadata('design:returntype', ");
emitSerializedReturnTypeOfNode(node);
write(")");
argumentsWritten++;
}
}
return argumentsWritten;
}
function serializeTypeNameSegment(location: Node, path: string[], index: number): string {
switch (index) {
case 0:
return `typeof ${path[index]} !== 'undefined' && ${path[index]}`;
case 1:
return `${serializeTypeNameSegment(location, path, index - 1) }.${path[index]}`;
default:
let temp = createAndRecordTempVariable(TempFlags.Auto).text;
return `(${temp} = ${serializeTypeNameSegment(location, path, index - 1) }) && ${temp}.${path[index]}`;
}
}
function emitSerializedType(location: Node, name: string | string[]): void {
if (typeof name === "string") {
write(name);
return;
}
else {
Debug.assert(name.length > 0, "Invalid serialized type name");
write(`(${serializeTypeNameSegment(location, name, name.length - 1) }) || Object`);
}
}
function emitInterfaceDeclaration(node: InterfaceDeclaration) {
emitOnlyPinnedOrTripleSlashComments(node);
}
@ -5823,6 +6046,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
Debug.assert(!exportFunctionForFile);
// make sure that name of 'exports' function does not conflict with existing identifiers
exportFunctionForFile = makeUniqueName("exports");
writeLine();
write("System.register(");
if (node.moduleName) {
write(`"${node.moduleName}", `);

View File

@ -29,6 +29,9 @@ namespace ts {
declare var process: any;
declare var global: any;
declare var __filename: string;
declare var Buffer: {
new (str: string, encoding ?: string): any;
}
declare class Enumerator {
public atEnd(): boolean;
@ -267,10 +270,17 @@ namespace ts {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
write(s: string): void {
write(s: string): void {
var buffer = new Buffer(s, 'utf8');
var offset: number = 0;
var toWrite: number = buffer.length;
var written = 0;
// 1 is a standard descriptor for stdout
_fs.writeSync(1, s);
},
while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) {
offset += written;
toWrite -= written;
}
},
readFile,
writeFile,
watchFile: (fileName, callback) => {

View File

@ -1846,6 +1846,27 @@ namespace ts {
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator
* metadata */
/* @internal */
export enum TypeReferenceSerializationKind {
Unknown, // The TypeReferenceNode could not be resolved. The type name
// should be emitted using a safe fallback.
TypeWithConstructSignatureAndValue, // The TypeReferenceNode resolves to a type with a constructor
// function that can be reached at runtime (e.g. a `class`
// declaration or a `var` declaration for the static side
// of a type, such as the global `Promise` type in lib.d.ts).
VoidType, // The TypeReferenceNode resolves to a Void-like type.
NumberLikeType, // The TypeReferenceNode resolves to a Number-like type.
StringLikeType, // The TypeReferenceNode resolves to a String-like type.
BooleanType, // The TypeReferenceNode resolves to a Boolean-like type.
ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type.
ESSymbolType, // The TypeReferenceNode resolves to the ESSymbol type.
TypeWithCallSignature, // The TypeReferenceNode resolves to a Function type or a type
// with call signatures.
ObjectType, // The TypeReferenceNode resolves to any other type.
}
/* @internal */
export interface EmitResolver {
@ -1870,9 +1891,7 @@ namespace ts {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getBlockScopedVariableId(node: Identifier): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
serializeTypeOfNode(node: Node): string | string[];
serializeParameterTypesOfNode(node: Node): (string | string[])[];
serializeReturnTypeOfNode(node: Node): string | string[];
getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind;
}
export const enum SymbolFlags {

View File

@ -1687,6 +1687,10 @@ namespace ts {
});
}
export function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode {
return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type;
}
export function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
if (!isDeclarationFile(sourceFile)) {
if ((isExternalModule(sourceFile) || !compilerOptions.out)) {

View File

@ -10,6 +10,7 @@ const enum CompilerTestType {
class CompilerBaselineRunner extends RunnerBase {
private basePath = 'tests/cases';
private testSuiteName: string;
private errors: boolean;
private emit: boolean;
private decl: boolean;
@ -24,43 +25,43 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = true;
this.output = true;
if (testType === CompilerTestType.Conformance) {
this.basePath += '/conformance';
this.testSuiteName = 'conformance';
}
else if (testType === CompilerTestType.Regressions) {
this.basePath += '/compiler';
this.testSuiteName = 'compiler';
}
else if (testType === CompilerTestType.Test262) {
this.basePath += '/test262';
this.testSuiteName = 'test262';
} else {
this.basePath += '/compiler'; // default to this for historical reasons
this.testSuiteName = 'compiler'; // default to this for historical reasons
}
this.basePath += '/' + this.testSuiteName;
}
public checkTestCodeOutput(fileName: string) {
describe('compiler tests for ' + fileName, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
var justName: string;
var content: string;
var testCaseContent: { settings: Harness.TestCaseParser.CompilerSetting[]; testUnitData: Harness.TestCaseParser.TestUnitData[]; }
let justName: string;
let content: string;
let testCaseContent: { settings: Harness.TestCaseParser.CompilerSetting[]; testUnitData: Harness.TestCaseParser.TestUnitData[]; };
var units: Harness.TestCaseParser.TestUnitData[];
var tcSettings: Harness.TestCaseParser.CompilerSetting[];
var createNewInstance: boolean;
let units: Harness.TestCaseParser.TestUnitData[];
let tcSettings: Harness.TestCaseParser.CompilerSetting[];
var lastUnit: Harness.TestCaseParser.TestUnitData;
var rootDir: string;
let lastUnit: Harness.TestCaseParser.TestUnitData;
let rootDir: string;
var result: Harness.Compiler.CompilerResult;
var program: ts.Program;
var options: ts.CompilerOptions;
let result: Harness.Compiler.CompilerResult;
let program: ts.Program;
let options: ts.CompilerOptions;
// equivalent to the files that will be passed on the command line
var toBeCompiled: { unitName: string; content: string }[];
let toBeCompiled: { unitName: string; content: string }[];
// equivalent to other files on the file system not directly passed to the compiler (ie things that are referenced by other files)
var otherFiles: { unitName: string; content: string }[];
var harnessCompiler: Harness.Compiler.HarnessCompiler;
let otherFiles: { unitName: string; content: string }[];
let harnessCompiler: Harness.Compiler.HarnessCompiler;
var createNewInstance = false;
let createNewInstance = false;
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ''); // strips the fileName from the path.
@ -100,10 +101,10 @@ class CompilerBaselineRunner extends RunnerBase {
});
beforeEach(() => {
/* The compiler doesn't handle certain flags flipping during a single compilation setting. Tests on these flags will need
/* The compiler doesn't handle certain flags flipping during a single compilation setting. Tests on these flags will need
a fresh compiler instance for themselves and then create a fresh one for the next test. Would be nice to get dev fixes
eventually to remove this limitation. */
for (var i = 0; i < tcSettings.length; ++i) {
for (let i = 0; i < tcSettings.length; ++i) {
// noImplicitAny is passed to getCompiler, but target is just passed in the settings blob to setCompilerSettings
if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === 'target')) {
harnessCompiler = Harness.Compiler.getCompiler();
@ -160,7 +161,7 @@ class CompilerBaselineRunner extends RunnerBase {
it('Correct sourcemap content for ' + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => {
var record = result.getSourceMapRecord();
let record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
return null;
@ -178,18 +179,18 @@ class CompilerBaselineRunner extends RunnerBase {
// check js output
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => {
var tsCode = '';
var tsSources = otherFiles.concat(toBeCompiled);
let tsCode = '';
let tsSources = otherFiles.concat(toBeCompiled);
if (tsSources.length > 1) {
tsCode += '//// [' + fileName + '] ////\r\n\r\n';
}
for (var i = 0; i < tsSources.length; i++) {
for (let i = 0; i < tsSources.length; i++) {
tsCode += '//// [' + Harness.Path.getFileName(tsSources[i].unitName) + ']\r\n';
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? '\r\n' : '');
}
var jsCode = '';
for (var i = 0; i < result.files.length; i++) {
let jsCode = '';
for (let i = 0; i < result.files.length; i++) {
jsCode += '//// [' + Harness.Path.getFileName(result.files[i].fileName) + ']\r\n';
jsCode += getByteOrderMarkText(result.files[i]);
jsCode += result.files[i].code;
@ -197,14 +198,14 @@ class CompilerBaselineRunner extends RunnerBase {
if (result.declFilesCode.length > 0) {
jsCode += '\r\n\r\n';
for (var i = 0; i < result.declFilesCode.length; i++) {
for (let i = 0; i < result.declFilesCode.length; i++) {
jsCode += '//// [' + Harness.Path.getFileName(result.declFilesCode[i].fileName) + ']\r\n';
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
jsCode += result.declFilesCode[i].code;
}
}
var declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
let declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
}, options);
@ -242,8 +243,8 @@ class CompilerBaselineRunner extends RunnerBase {
return null;
}
var sourceMapCode = '';
for (var i = 0; i < result.sourceMaps.length; i++) {
let sourceMapCode = '';
for (let i = 0; i < result.sourceMaps.length; i++) {
sourceMapCode += '//// [' + Harness.Path.getFileName(result.sourceMaps[i].fileName) + ']\r\n';
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
sourceMapCode += result.sourceMaps[i].code;
@ -261,19 +262,19 @@ class CompilerBaselineRunner extends RunnerBase {
// NEWTODO: Type baselines
if (result.errors.length === 0) {
// The full walker simulates the types that you would get from doing a full
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type outputed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
let allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
@ -291,7 +292,7 @@ class CompilerBaselineRunner extends RunnerBase {
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
var e1: Error, e2: Error;
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine:*/ false);
}
@ -333,20 +334,20 @@ class CompilerBaselineRunner extends RunnerBase {
let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
var codeLines = file.content.split('\n');
let codeLines = file.content.split('\n');
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
var typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
var formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
let typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
let formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
var typeInfo = [formattedLine];
var existingTypeInfo = typeMap[file.unitName][result.line];
let typeInfo = [formattedLine];
let existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
@ -354,11 +355,11 @@ class CompilerBaselineRunner extends RunnerBase {
});
typeLines.push('=== ' + file.unitName + ' ===\r\n');
for (var i = 0; i < codeLines.length; i++) {
var currentCodeLine = codeLines[i];
for (let i = 0; i < codeLines.length; i++) {
let currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + '\r\n');
if (typeMap[file.unitName]) {
var typeInfo = typeMap[file.unitName][i];
let typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push('>' + ty + '\r\n');
@ -384,25 +385,27 @@ class CompilerBaselineRunner extends RunnerBase {
}
public initializeTests() {
describe("Setup compiler for compiler baselines", () => {
var harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
});
// this will set up a series of describe/it blocks to run between the setup and cleanup phases
if (this.tests.length === 0) {
var testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true });
testFiles.forEach(fn => {
fn = fn.replace(/\\/g, "/");
this.checkTestCodeOutput(fn);
describe(this.testSuiteName + ' tests', () => {
describe("Setup compiler for compiler baselines", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
});
}
else {
this.tests.forEach(test => this.checkTestCodeOutput(test));
}
describe("Cleanup after compiler baselines", () => {
var harnessCompiler = Harness.Compiler.getCompiler();
// this will set up a series of describe/it blocks to run between the setup and cleanup phases
if (this.tests.length === 0) {
let testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true });
testFiles.forEach(fn => {
fn = fn.replace(/\\/g, "/");
this.checkTestCodeOutput(fn);
});
}
else {
this.tests.forEach(test => this.checkTestCodeOutput(test));
}
describe("Cleanup after compiler baselines", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
});
});
}
@ -413,8 +416,8 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = false;
this.output = false;
var opts = this.options.split(',');
for (var i = 0; i < opts.length; i++) {
let opts = this.options.split(',');
for (let i = 0; i < opts.length; i++) {
switch (opts[i]) {
case 'error':
this.errors = true;
@ -434,4 +437,4 @@ class CompilerBaselineRunner extends RunnerBase {
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
///<reference path='harness.ts'/>
///<reference path='runnerbase.ts' />
const enum FourSlashTestType {
const enum FourSlashTestType {
Native,
Shims,
Server
@ -35,70 +35,72 @@ class FourSlashRunner extends RunnerBase {
this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false });
}
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
var justName = fn.replace(/^.*[\\\/]/, '');
describe(this.testSuiteName + ' tests', () => {
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
let justName = fn.replace(/^.*[\\\/]/, '');
// Convert to relative path
var testIndex = fn.indexOf('tests/');
if (testIndex >= 0) fn = fn.substr(testIndex);
// Convert to relative path
let testIndex = fn.indexOf('tests/');
if (testIndex >= 0) fn = fn.substr(testIndex);
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}
});
});
});
describe('Generate Tao XML', () => {
var invalidReasons: any = {};
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1;
describe('Generate Tao XML', () => {
let invalidReasons: any = {};
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1;
}
});
let invalidReport: { reason: string; count: number }[] = [];
for (let reason in invalidReasons) {
if (invalidReasons.hasOwnProperty(reason)) {
invalidReport.push({ reason: reason, count: invalidReasons[reason] });
}
}
});
var invalidReport: { reason: string; count: number }[] = [];
for (var reason in invalidReasons) {
if (invalidReasons.hasOwnProperty(reason)) {
invalidReport.push({ reason: reason, count: invalidReasons[reason] });
}
}
invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
var lines: string[] = [];
lines.push('<!-- Blocked Test Report');
invalidReport.forEach((reasonAndCount) => {
lines.push(reasonAndCount.count + ' tests blocked by ' + reasonAndCount.reason);
let lines: string[] = [];
lines.push('<!-- Blocked Test Report');
invalidReport.forEach((reasonAndCount) => {
lines.push(reasonAndCount.count + ' tests blocked by ' + reasonAndCount.reason);
});
lines.push('-->');
lines.push('<TaoTest xmlns="http://microsoft.com/schemas/VSLanguages/TAO">');
lines.push(' <InitTest>');
lines.push(' <StartTarget />');
lines.push(' </InitTest>');
lines.push(' <ScenarioList>');
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
lines.push('<!-- Skipped ' + xml.originalName + ', reason: ' + xml.invalidReason + ' -->');
} else {
lines.push(' <Scenario Name="' + xml.originalName + '">');
xml.actions.forEach(action => {
lines.push(' ' + action);
});
lines.push(' </Scenario>');
}
});
lines.push(' </ScenarioList>');
lines.push(' <CleanupScenario>');
lines.push(' <CloseAllDocuments />');
lines.push(' <CleanupCreatedFiles />');
lines.push(' </CleanupScenario>');
lines.push(' <CleanupTest>');
lines.push(' <CloseTarget />');
lines.push(' </CleanupTest>');
lines.push('</TaoTest>');
Harness.IO.writeFile('built/local/fourslash.xml', lines.join('\r\n'));
});
lines.push('-->');
lines.push('<TaoTest xmlns="http://microsoft.com/schemas/VSLanguages/TAO">');
lines.push(' <InitTest>');
lines.push(' <StartTarget />');
lines.push(' </InitTest>');
lines.push(' <ScenarioList>');
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
lines.push('<!-- Skipped ' + xml.originalName + ', reason: ' + xml.invalidReason + ' -->');
} else {
lines.push(' <Scenario Name="' + xml.originalName + '">');
xml.actions.forEach(action => {
lines.push(' ' + action);
});
lines.push(' </Scenario>');
}
});
lines.push(' </ScenarioList>');
lines.push(' <CleanupScenario>');
lines.push(' <CloseAllDocuments />');
lines.push(' <CleanupCreatedFiles />');
lines.push(' </CleanupScenario>');
lines.push(' <CleanupTest>');
lines.push(' <CloseTarget />');
lines.push(' </CleanupTest>');
lines.push('</TaoTest>');
Harness.IO.writeFile('built/local/fourslash.xml', lines.join('\r\n'));
});
}
}
@ -108,4 +110,4 @@ class GeneratedFourslashRunner extends FourSlashRunner {
super(testType);
this.basePath += '/generated/';
}
}
}

View File

@ -33,8 +33,6 @@ declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(null);
module Utils {
var global = <any>Function("return this").call(null);
// Setup some globals based on the current environment
export const enum ExecutionEnvironment {
Node,
@ -54,17 +52,17 @@ module Utils {
}
}
export var currentExecutionEnvironment = getExecutionEnvironment();
export let currentExecutionEnvironment = getExecutionEnvironment();
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
var environment = getExecutionEnvironment();
let environment = getExecutionEnvironment();
switch (environment) {
case ExecutionEnvironment.CScript:
case ExecutionEnvironment.Browser:
eval(fileContents);
break;
case ExecutionEnvironment.Node:
var vm = require('vm');
let vm = require('vm');
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
} else {
@ -81,7 +79,7 @@ module Utils {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to use string-based splitting instead and try to figure out the delimiting chars
var lines = content.split('\r\n');
let lines = content.split('\r\n');
if (lines.length === 1) {
lines = content.split('\n');
@ -98,8 +96,9 @@ module Utils {
path = "tests/" + path;
}
let content: string = undefined;
try {
var content = ts.sys.readFile(Harness.userSpecifiedRoot + path);
content = ts.sys.readFile(Harness.userSpecifiedRoot + path);
}
catch (err) {
return undefined;
@ -109,11 +108,11 @@ module Utils {
}
export function memoize<T extends Function>(f: T): T {
var cache: { [idx: string]: any } = {};
let cache: { [idx: string]: any } = {};
return <any>(function () {
var key = Array.prototype.join.call(arguments);
var cachedResult = cache[key];
let key = Array.prototype.join.call(arguments);
let cachedResult = cache[key];
if (cachedResult) {
return cachedResult;
} else {
@ -140,7 +139,7 @@ module Utils {
});
// Make sure each of the children is in order.
var currentPos = 0;
let currentPos = 0;
ts.forEachChild(node,
child => {
assert.isFalse(child.pos < currentPos, "child.pos < currentPos");
@ -151,22 +150,22 @@ module Utils {
assert.isFalse(array.end > node.end, "array.end > node.end");
assert.isFalse(array.pos < currentPos, "array.pos < currentPos");
for (var i = 0, n = array.length; i < n; i++) {
for (let i = 0, n = array.length; i < n; i++) {
assert.isFalse(array[i].pos < currentPos, "array[i].pos < currentPos");
currentPos = array[i].end
currentPos = array[i].end;
}
currentPos = array.end;
});
var childNodesAndArrays: any[] = [];
ts.forEachChild(node, child => { childNodesAndArrays.push(child) }, array => { childNodesAndArrays.push(array) });
let childNodesAndArrays: any[] = [];
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
for (var childName in node) {
for (let childName in node) {
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator") {
continue;
}
var child = (<any>node)[childName];
let child = (<any>node)[childName];
if (isNodeOrArray(child)) {
assert.isFalse(childNodesAndArrays.indexOf(child) < 0,
"Missing child when forEach'ing over node: " + (<any>ts).SyntaxKind[node.kind] + "-" + childName);
@ -194,7 +193,7 @@ module Utils {
}
export function sourceFileToJSON(file: ts.Node): string {
return JSON.stringify(file,(k, v) => {
return JSON.stringify(file, (k, v) => {
return isNodeOrArray(v) ? serializeNode(v) : v;
}, " ");
@ -203,7 +202,7 @@ module Utils {
return k;
}
return (<any>ts).SyntaxKind[k]
return (<any>ts).SyntaxKind[k];
}
function getFlagName(flags: any, f: number): any {
@ -211,7 +210,7 @@ module Utils {
return 0;
}
var result = "";
let result = "";
ts.forEach(Object.getOwnPropertyNames(flags), (v: any) => {
if (isFinite(v)) {
v = +v;
@ -234,7 +233,7 @@ module Utils {
function getParserContextFlagName(f: number) { return getFlagName((<any>ts).ParserContextFlags, f); }
function serializeNode(n: ts.Node): any {
var o: any = { kind: getKindName(n.kind) };
let o: any = { kind: getKindName(n.kind) };
if (ts.containsParseError(n)) {
o.containsParseError = true;
}
@ -268,7 +267,7 @@ module Utils {
// Clear the flag that are produced by aggregating child values.. That is ephemeral
// data we don't care about in the dump. We only care what the parser set directly
// on the ast.
var value = n.parserContextFlags & ts.ParserContextFlags.ParserGeneratedFlags;
let value = n.parserContextFlags & ts.ParserContextFlags.ParserGeneratedFlags;
if (value) {
o[propertyName] = getParserContextFlagName(value);
}
@ -313,9 +312,9 @@ module Utils {
assert.equal(array1.length, array2.length, "array1.length !== array2.length");
for (var i = 0, n = array1.length; i < n; i++) {
var d1 = array1[i];
var d2 = array2[i];
for (let i = 0, n = array1.length; i < n; i++) {
let d1 = array1[i];
let d2 = array2[i];
assert.equal(d1.start, d2.start, "d1.start !== d2.start");
assert.equal(d1.length, d2.length, "d1.length !== d2.length");
@ -346,14 +345,14 @@ module Utils {
ts.forEachChild(node1,
child1 => {
var childName = findChildName(node1, child1);
var child2: ts.Node = (<any>node2)[childName];
let childName = findChildName(node1, child1);
let child2: ts.Node = (<any>node2)[childName];
assertStructuralEquals(child1, child2);
},
(array1: ts.NodeArray<ts.Node>) => {
var childName = findChildName(node1, array1);
var array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];
let childName = findChildName(node1, array1);
let array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];
assertArrayStructuralEquals(array1, array2);
});
@ -370,13 +369,13 @@ module Utils {
assert.equal(array1.end, array2.end, "array1.end !== array2.end");
assert.equal(array1.length, array2.length, "array1.length !== array2.length");
for (var i = 0, n = array1.length; i < n; i++) {
for (let i = 0, n = array1.length; i < n; i++) {
assertStructuralEquals(array1[i], array2[i]);
}
}
function findChildName(parent: any, child: any) {
for (var name in parent) {
for (let name in parent) {
if (parent.hasOwnProperty(name) && parent[name] === child) {
return name;
}
@ -393,8 +392,8 @@ module Harness.Path {
export function filePath(fullPath: string) {
fullPath = ts.normalizeSlashes(fullPath);
var components = fullPath.split("/");
var path: string[] = components.slice(0, components.length - 1);
let components = fullPath.split("/");
let path: string[] = components.slice(0, components.length - 1);
return path.join("/") + "/";
}
}
@ -422,19 +421,19 @@ module Harness {
}
export module CScript {
var fso: any;
let fso: any;
if (global.ActiveXObject) {
fso = new global.ActiveXObject("Scripting.FileSystemObject");
} else {
fso = {};
}
export var readFile: typeof IO.readFile = ts.sys.readFile;
export var writeFile: typeof IO.writeFile = ts.sys.writeFile;
export var directoryName: typeof IO.directoryName = fso.GetParentFolderName;
export var directoryExists: typeof IO.directoryExists = fso.FolderExists;
export var fileExists: typeof IO.fileExists = fso.FileExists;
export var log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export let readFile: typeof IO.readFile = ts.sys.readFile;
export let writeFile: typeof IO.writeFile = ts.sys.writeFile;
export let directoryName: typeof IO.directoryName = fso.GetParentFolderName;
export let directoryExists: typeof IO.directoryExists = fso.FolderExists;
export let fileExists: typeof IO.fileExists = fso.FileExists;
export let log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export function createDirectory(path: string) {
if (directoryExists(path)) {
@ -448,11 +447,11 @@ module Harness {
}
}
export var listFiles: typeof IO.listFiles = (path, spec?, options?) => {
export let listFiles: typeof IO.listFiles = (path, spec?, options?) => {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: any, root: string): string[] {
var paths: string[] = [];
var fc: any;
let paths: string[] = [];
let fc: any;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
@ -473,17 +472,16 @@ module Harness {
return paths;
}
var folder: any = fso.GetFolder(path);
var paths: string[] = [];
let folder: any = fso.GetFolder(path);
let paths: string[] = [];
return filesInFolder(folder, path);
}
};
}
export module Node {
declare var require: any;
var fs: any, pathModule: any;
declare let require: any;
let fs: any, pathModule: any;
if (require) {
fs = require('fs');
pathModule = require('path');
@ -491,10 +489,10 @@ module Harness {
fs = pathModule = {};
}
export var readFile: typeof IO.readFile = ts.sys.readFile;
export var writeFile: typeof IO.writeFile = ts.sys.writeFile;
export var fileExists: typeof IO.fileExists = fs.existsSync;
export var log: typeof IO.log = console.log;
export let readFile: typeof IO.readFile = ts.sys.readFile;
export let writeFile: typeof IO.writeFile = ts.sys.writeFile;
export let fileExists: typeof IO.fileExists = fs.existsSync;
export let log: typeof IO.log = console.log;
export function createDirectory(path: string) {
if (!directoryExists(path)) {
@ -514,7 +512,7 @@ module Harness {
}
export function directoryName(path: string) {
var dirPath = pathModule.dirname(path);
let dirPath = pathModule.dirname(path);
// Node will just continue to repeat the root path, rather than return null
if (dirPath === path) {
@ -524,16 +522,16 @@ module Harness {
}
}
export var listFiles: typeof IO.listFiles = (path, spec?, options?) => {
export let listFiles: typeof IO.listFiles = (path, spec?, options?) => {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: string): string[] {
var paths: string[] = [];
let paths: string[] = [];
var files = fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
var pathToFile = pathModule.join(folder, files[i]);
var stat = fs.statSync(pathToFile);
let files = fs.readdirSync(folder);
for (let i = 0; i < files.length; i++) {
let pathToFile = pathModule.join(folder, files[i]);
let stat = fs.statSync(pathToFile);
if (options.recursive && stat.isDirectory()) {
paths = paths.concat(filesInFolder(pathToFile));
}
@ -546,23 +544,23 @@ module Harness {
}
return filesInFolder(path);
}
};
export var getMemoryUsage: typeof IO.getMemoryUsage = () => {
export let getMemoryUsage: typeof IO.getMemoryUsage = () => {
if (global.gc) {
global.gc();
}
return process.memoryUsage().heapUsed;
}
};
}
export module Network {
var serverRoot = "http://localhost:8888/";
let serverRoot = "http://localhost:8888/";
// Unused?
var newLine = '\r\n';
var currentDirectory = () => '';
var supportsCodePage = () => false;
let newLine = '\r\n';
let currentDirectory = () => '';
let supportsCodePage = () => false;
module Http {
function waitForXHR(xhr: XMLHttpRequest) {
@ -572,7 +570,7 @@ module Harness {
/// Ask the server to use node's path.resolve to resolve the given path
function getResolvedPathFromServer(path: string) {
var xhr = new XMLHttpRequest();
let xhr = new XMLHttpRequest();
try {
xhr.open("GET", path + "?resolve", false);
xhr.send();
@ -591,7 +589,7 @@ module Harness {
/// Ask the server for the contents of the file at the given URL via a simple GET request
export function getFileFromServerSync(url: string): XHRResponse {
var xhr = new XMLHttpRequest();
let xhr = new XMLHttpRequest();
try {
xhr.open("GET", url, false);
xhr.send();
@ -605,10 +603,10 @@ module Harness {
/// Submit a POST request to the server to do the given action (ex WRITE, DELETE) on the provided URL
export function writeToServerSync(url: string, action: string, contents?: string): XHRResponse {
var xhr = new XMLHttpRequest();
let xhr = new XMLHttpRequest();
try {
var action = '?action=' + action;
xhr.open('POST', url + action, false);
let actionMsg = '?action=' + action;
xhr.open('POST', url + actionMsg, false);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send(contents);
}
@ -633,7 +631,7 @@ module Harness {
}
function directoryNameImpl(path: string) {
var dirPath = path;
let dirPath = path;
// root of the server
if (dirPath.match(/localhost:\d+$/) || dirPath.match(/localhost:\d+\/$/)) {
dirPath = null;
@ -646,22 +644,22 @@ module Harness {
if (dirPath.match(/.*\/$/)) {
dirPath = dirPath.substring(0, dirPath.length - 2);
}
var dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
}
return dirPath;
}
export var directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export let directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export function fileExists(path: string): boolean {
var response = Http.getFileFromServerSync(serverRoot + path);
let response = Http.getFileFromServerSync(serverRoot + path);
return response.status === 200;
}
export function _listFilesImpl(path: string, spec?: RegExp, options?: any) {
var response = Http.getFileFromServerSync(serverRoot + path);
let response = Http.getFileFromServerSync(serverRoot + path);
if (response.status === 200) {
var results = response.responseText.split(',');
let results = response.responseText.split(',');
if (spec) {
return results.filter(file => spec.test(file));
} else {
@ -672,12 +670,12 @@ module Harness {
return [''];
}
};
export var listFiles = Utils.memoize(_listFilesImpl);
export let listFiles = Utils.memoize(_listFilesImpl);
export var log = console.log;
export let log = console.log;
export function readFile(file: string) {
var response = Http.getFileFromServerSync(serverRoot + file);
let response = Http.getFileFromServerSync(serverRoot + file);
if (response.status === 200) {
return response.responseText;
} else {
@ -706,9 +704,9 @@ module Harness {
}
module Harness {
var tcServicesFileName = "typescriptServices.js";
let tcServicesFileName = "typescriptServices.js";
export var libFolder: string;
export let libFolder: string;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
libFolder = "built/local/";
@ -725,7 +723,7 @@ module Harness {
default:
throw new Error('Unknown context');
}
export var tcServicesFile = IO.readFile(tcServicesFileName);
export let tcServicesFile = IO.readFile(tcServicesFileName);
export interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
@ -777,7 +775,7 @@ module Harness {
/** create file gets the whole path to create, so this works as expected with the --out parameter */
public writeFile(s: string, contents: string, writeByteOrderMark: boolean): void {
var writer: ITextWriter;
let writer: ITextWriter;
if (this.fileCollection[s]) {
writer = <ITextWriter>this.fileCollection[s];
}
@ -795,10 +793,10 @@ module Harness {
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[] {
var result: { fileName: string; file: WriterAggregator; }[] = [];
for (var p in this.fileCollection) {
let result: { fileName: string; file: WriterAggregator; }[] = [];
for (let p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
var current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
let current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
if (current.lines.length > 0) {
if (p.indexOf('.d.ts') !== -1) { current.lines.unshift(['////[', Path.getFileName(p), ']'].join('')); }
result.push({ fileName: p, file: this.fileCollection[p] });
@ -813,11 +811,11 @@ module Harness {
fileName: string,
sourceText: string,
languageVersion: ts.ScriptTarget) {
// We'll only assert invariants outside of light mode.
// We'll only assert inletiants outside of light mode.
const shouldAssertInvariants = !Harness.lightMode;
// Only set the parent nodes if we're asserting invariants. We don't need them otherwise.
var result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
// Only set the parent nodes if we're asserting inletiants. We don't need them otherwise.
let result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
if (shouldAssertInvariants) {
Utils.assertInvariants(result, /*parent:*/ undefined);
@ -829,13 +827,13 @@ module Harness {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export var defaultLibFileName = 'lib.d.ts';
export var defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export var defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultLibFileName = 'lib.d.ts';
export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
// Cache these between executions so we don't have to re-parse them for every test
export var fourslashFileName = 'fourslash.ts';
export var fourslashSourceFile: ts.SourceFile;
export let fourslashFileName = 'fourslash.ts';
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
@ -855,13 +853,13 @@ module Harness {
return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
var filemap: { [fileName: string]: ts.SourceFile; } = {};
var getCurrentDirectory = currentDirectory === undefined ? ts.sys.getCurrentDirectory : () => currentDirectory;
let filemap: { [fileName: string]: ts.SourceFile; } = {};
let getCurrentDirectory = currentDirectory === undefined ? ts.sys.getCurrentDirectory : () => currentDirectory;
// Register input files
function register(file: { unitName: string; content: string; }) {
if (file.content !== undefined) {
var fileName = ts.normalizePath(file.unitName);
let fileName = ts.normalizePath(file.unitName);
filemap[getCanonicalFileName(fileName)] = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget);
}
};
@ -880,11 +878,11 @@ module Harness {
return filemap[getCanonicalFileName(fn)];
}
else if (currentDirectory) {
var canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
let canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
}
else if (fn === fourslashFileName) {
var tsFn = 'tests/cases/fourslash/' + fourslashFileName;
let tsFn = 'tests/cases/fourslash/' + fourslashFileName;
fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
return fourslashSourceFile;
}
@ -980,27 +978,27 @@ module Harness {
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
// Treat them as library files, so include them in build, but not in baselines.
var includeBuiltFiles: { unitName: string; content: string }[] = [];
let includeBuiltFiles: { unitName: string; content: string }[] = [];
var useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
let useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
this.settings.forEach(setCompilerOptionForSetting);
var fileOutputs: GeneratedFile[] = [];
let fileOutputs: GeneratedFile[] = [];
var programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
let programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
var compilerHost = createCompilerHost(
let compilerHost = createCompilerHost(
inputFiles.concat(includeBuiltFiles).concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine);
var program = ts.createProgram(programFiles, options, compilerHost);
let program = ts.createProgram(programFiles, options, compilerHost);
var emitResult = program.emit();
let emitResult = program.emit();
var errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
let errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
this.lastErrors = errors;
var result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult.sourceMaps);
let result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult.sourceMaps);
onComplete(result, program);
// reset what newline means in case the last test changed it
@ -1193,12 +1191,12 @@ module Harness {
throw new Error('There were no errors and declFiles generated did not match number of js files generated');
}
let declInputFiles: { unitName: string; content: string }[] = [];
let declOtherFiles: { unitName: string; content: string }[] = [];
let declResult: Harness.Compiler.CompilerResult;
// if the .d.ts is non-empty, confirm it compiles correctly as well
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
var declInputFiles: { unitName: string; content: string }[] = [];
var declOtherFiles: { unitName: string; content: string }[] = [];
var declResult: Harness.Compiler.CompilerResult;
ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
this.compileFiles(declInputFiles, declOtherFiles, function (compileResult) { declResult = compileResult; },
@ -1212,20 +1210,20 @@ module Harness {
dtsFiles.push(file);
}
else if (isTS(file.unitName)) {
var declFile = findResultCodeFile(file.unitName);
let declFile = findResultCodeFile(file.unitName);
if (!findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
}
}
function findResultCodeFile(fileName: string) {
var sourceFile = result.program.getSourceFile(fileName);
let sourceFile = result.program.getSourceFile(fileName);
assert(sourceFile, "Program has no source file with name '" + fileName + "'");
// Is this file going to be emitted separately
var sourceFileName: string;
let sourceFileName: string;
if (ts.isExternalModule(sourceFile) || !options.out) {
if (options.outDir) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
@ -1238,7 +1236,7 @@ module Harness {
sourceFileName = options.out;
}
var dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
let dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
@ -1251,7 +1249,7 @@ module Harness {
}
function normalizeLineEndings(text: string, lineEnding: string): string {
var normalized = text.replace(/\r\n?/g, '\n');
let normalized = text.replace(/\r\n?/g, '\n');
if (lineEnding !== '\n') {
normalized = normalized.replace(/\n/g, lineEnding);
}
@ -1260,10 +1258,10 @@ module Harness {
export function minimalDiagnosticsToString(diagnostics: ts.Diagnostic[]) {
// This is basically copied from tsc.ts's reportError to replicate what tsc does
var errorOutput = "";
let errorOutput = "";
ts.forEach(diagnostics, diagnostic => {
if (diagnostic.file) {
var lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
let lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
errorOutput += diagnostic.file.fileName + "(" + (lineAndCharacter.line + 1) + "," + (lineAndCharacter.character + 1) + "): ";
}
@ -1275,14 +1273,14 @@ module Harness {
export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: ts.Diagnostic[]) {
diagnostics.sort(ts.compareDiagnostics);
var outputLines: string[] = [];
let outputLines: string[] = [];
// Count up all the errors we find so we don't miss any
var totalErrorsReported = 0;
let totalErrorsReported = 0;
function outputErrorText(error: ts.Diagnostic) {
var message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine);
let message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine);
var errLines = RunnerBase.removeFullPaths(message)
let errLines = RunnerBase.removeFullPaths(message)
.split('\n')
.map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s)
.filter(s => s.length > 0)
@ -1293,14 +1291,14 @@ module Harness {
}
// Report global errors
var globalErrors = diagnostics.filter(err => !err.file);
let globalErrors = diagnostics.filter(err => !err.file);
globalErrors.forEach(outputErrorText);
// 'merge' the lines of each input file with any errors associated with it
inputFiles.filter(f => f.content !== undefined).forEach(inputFile => {
// Filter down to the errors in the file
var fileErrors = diagnostics.filter(e => {
var errFn = e.file;
let fileErrors = diagnostics.filter(e => {
let errFn = e.file;
return errFn && errFn.fileName === inputFile.unitName;
});
@ -1309,13 +1307,13 @@ module Harness {
outputLines.push('==== ' + inputFile.unitName + ' (' + fileErrors.length + ' errors) ====');
// Make sure we emit something for every error
var markedErrorCount = 0;
let markedErrorCount = 0;
// For each line, emit the line followed by any error squiggles matching this line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to string-based splitting instead and try to figure out the delimiting chars
var lineStarts = ts.computeLineStarts(inputFile.content);
var lines = inputFile.content.split('\n');
let lineStarts = ts.computeLineStarts(inputFile.content);
let lines = inputFile.content.split('\n');
if (lines.length === 1) {
lines = lines[0].split("\r");
}
@ -1325,8 +1323,8 @@ module Harness {
line = line.substr(0, line.length - 1);
}
var thisLineStart = lineStarts[lineIndex];
var nextLineStart: number;
let thisLineStart = lineStarts[lineIndex];
let nextLineStart: number;
// On the last line of the file, fake the next line start number so that we handle errors on the last character of the file correctly
if (lineIndex === lines.length - 1) {
nextLineStart = inputFile.content.length;
@ -1340,11 +1338,11 @@ module Harness {
let end = ts.textSpanEnd(err);
if ((end >= thisLineStart) && ((err.start < nextLineStart) || (lineIndex === lines.length - 1))) {
// How many characters from the start of this line the error starts at (could be positive or negative)
var relativeOffset = err.start - thisLineStart;
let relativeOffset = err.start - thisLineStart;
// How many characters of the error are on this line (might be longer than this line in reality)
var length = (end - err.start) - Math.max(0, thisLineStart - err.start);
let length = (end - err.start) - Math.max(0, thisLineStart - err.start);
// Calculate the start of the squiggle
var squiggleStart = Math.max(0, relativeOffset);
let squiggleStart = Math.max(0, relativeOffset);
// TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another
outputLines.push(' ' + line.substr(0, squiggleStart).replace(/[^\s]/g, ' ') + new Array(Math.min(length, line.length - squiggleStart) + 1).join('~'));
@ -1364,11 +1362,11 @@ module Harness {
assert.equal(markedErrorCount, fileErrors.length, 'count of errors in ' + inputFile.unitName);
});
var numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
let numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
return diagnostic.file && (isLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
});
var numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
let numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
// Count an error generated from tests262-harness folder.This should only apply for test262
return diagnostic.file && diagnostic.file.fileName.indexOf("test262-harness") >= 0;
});
@ -1385,7 +1383,7 @@ module Harness {
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
// Emit them
var result = '';
let result = '';
for (let outputFile of outputFiles) {
// Some extra spacing if this isn't the first file
if (result.length) {
@ -1401,13 +1399,13 @@ module Harness {
return result;
function cleanName(fn: string) {
var lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/');
let lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/');
return fn.substr(lastSlash + 1).toLowerCase();
}
}
/** The harness' compiler instance used when tests are actually run. Reseting or changing settings of this compiler instance must be done within a test case (i.e., describe/it) */
var harnessCompiler: HarnessCompiler;
let harnessCompiler: HarnessCompiler;
/** Returns the singleton harness compiler instance for generating and running tests.
If required a fresh compiler instance will be created, otherwise the existing singleton will be re-used.
@ -1420,8 +1418,6 @@ module Harness {
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
throw new Error('compileString NYI');
//var harnessCompiler = Harness.Compiler.getCompiler(Harness.Compiler.CompilerInstance.RunTime);
//harnessCompiler.compileString(code, unitName, callback);
}
export interface GeneratedFile {
@ -1513,10 +1509,10 @@ module Harness {
}
// Regex for parsing options in the format "@Alpha: Value of any sort"
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
let optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module",
let fileMetadataNames = ["filename", "comments", "declaration", "module",
"nolib", "sourcemap", "target", "out", "outdir", "noemithelpers", "noemitonerror",
"noimplicitany", "noresolve", "newline", "normalizenewline", "emitbom",
"errortruncation", "usecasesensitivefilenames", "preserveconstenums",
@ -1527,9 +1523,9 @@ module Harness {
function extractCompilerSettings(content: string): CompilerSetting[] {
var opts: CompilerSetting[] = [];
let opts: CompilerSetting[] = [];
var match: RegExpExecArray;
let match: RegExpExecArray;
while ((match = optionRegex.exec(content)) != null) {
opts.push({ flag: match[1], value: match[2] });
}
@ -1539,26 +1535,26 @@ module Harness {
/** Given a test file containing // @FileName directives, return an array of named units of code to be added to an existing compiler instance */
export function makeUnitsFromTest(code: string, fileName: string): { settings: CompilerSetting[]; testUnitData: TestUnitData[]; } {
var settings = extractCompilerSettings(code);
let settings = extractCompilerSettings(code);
// List of all the subfiles we've parsed out
var testUnitData: TestUnitData[] = [];
let testUnitData: TestUnitData[] = [];
var lines = Utils.splitContentByNewlines(code);
let lines = Utils.splitContentByNewlines(code);
// Stuff related to the subfile we're parsing
var currentFileContent: string = null;
var currentFileOptions: any = {};
var currentFileName: any = null;
var refs: string[] = [];
let currentFileContent: string = null;
let currentFileOptions: any = {};
let currentFileName: any = null;
let refs: string[] = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var testMetaData = optionRegex.exec(line);
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
let testMetaData = optionRegex.exec(line);
if (testMetaData) {
// Comment line, check for global/file @options and record them
optionRegex.lastIndex = 0;
var metaDataName = testMetaData[1].toLowerCase();
let metaDataName = testMetaData[1].toLowerCase();
if (metaDataName === "filename") {
currentFileOptions[testMetaData[1]] = testMetaData[2];
} else {
@ -1568,8 +1564,7 @@ module Harness {
// New metadata statement after having collected some code to go with the previous metadata
if (currentFileName) {
// Store result file
var newTestFile =
{
let newTestFile = {
content: currentFileContent,
name: currentFileName,
fileOptions: currentFileOptions,
@ -1604,7 +1599,7 @@ module Harness {
currentFileName = testUnitData.length > 0 ? currentFileName : Path.getFileName(fileName);
// EOF, push whatever remains
var newTestFile2 = {
let newTestFile2 = {
content: currentFileContent || '',
name: currentFileName,
fileOptions: currentFileOptions,
@ -1651,7 +1646,7 @@ module Harness {
}
}
var fileCache: { [idx: string]: boolean } = {};
let fileCache: { [idx: string]: boolean } = {};
function generateActual(actualFileName: string, generateContent: () => string): string {
// For now this is written using TypeScript, because sys is not available when running old test cases.
// But we need to move to sys once we have
@ -1662,7 +1657,7 @@ module Harness {
return;
}
var parentDirectory = IO.directoryName(dirName);
let parentDirectory = IO.directoryName(dirName);
if (parentDirectory != "") {
createDirectoryStructure(parentDirectory);
}
@ -1678,7 +1673,7 @@ module Harness {
IO.deleteFile(actualFileName);
}
var actual = generateContent();
let actual = generateContent();
if (actual === undefined) {
throw new Error('The generated content was "undefined". Return "null" if no baselining is required."');
@ -1701,13 +1696,13 @@ module Harness {
return;
}
var refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
let refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
if (actual === null) {
actual = '<no content>';
}
var expected = '<no content>';
let expected = '<no content>';
if (IO.fileExists(refFileName)) {
expected = IO.readFile(refFileName);
}
@ -1716,10 +1711,10 @@ module Harness {
}
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
var encoded_actual = (new Buffer(actual)).toString('utf8')
let encoded_actual = (new Buffer(actual)).toString('utf8');
if (expected != encoded_actual) {
// Overwrite & issue error
var errMsg = 'The baseline file ' + relativeFileName + ' has changed';
let errMsg = 'The baseline file ' + relativeFileName + ' has changed';
throw new Error(errMsg);
}
}
@ -1731,17 +1726,17 @@ module Harness {
runImmediately = false,
opts?: BaselineOptions): void {
var actual = <string>undefined;
var actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
let actual = <string>undefined;
let actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
if (runImmediately) {
actual = generateActual(actualFileName, generateContent);
var comparison = compareToBaseline(actual, relativeFileName, opts);
let comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
} else {
actual = generateActual(actualFileName, generateContent);
var comparison = compareToBaseline(actual, relativeFileName, opts);
let comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
}
}
@ -1756,11 +1751,11 @@ module Harness {
}
export function getDefaultLibraryFile(): { unitName: string, content: string } {
var libFile = Harness.userSpecifiedRoot + Harness.libFolder + "/" + "lib.d.ts";
let libFile = Harness.userSpecifiedRoot + Harness.libFolder + "/" + "lib.d.ts";
return {
unitName: libFile,
content: IO.readFile(libFile)
}
};
}
if (Error) (<any>Error).stackTraceLimit = 1;

View File

@ -26,9 +26,9 @@ module Harness.LanguageService {
public editContent(start: number, end: number, newText: string): void {
// Apply edits
var prefix = this.content.substring(0, start);
var middle = newText;
var suffix = this.content.substring(end);
let prefix = this.content.substring(0, start);
let middle = newText;
let suffix = this.content.substring(end);
this.setContent(prefix + middle + suffix);
// Store edit range + new length of script
@ -48,10 +48,10 @@ module Harness.LanguageService {
return ts.unchangedTextChangeRange;
}
var initialEditRangeIndex = this.editRanges.length - (this.version - startVersion);
var lastEditRangeIndex = this.editRanges.length - (this.version - endVersion);
let initialEditRangeIndex = this.editRanges.length - (this.version - startVersion);
let lastEditRangeIndex = this.editRanges.length - (this.version - endVersion);
var entries = this.editRanges.slice(initialEditRangeIndex, lastEditRangeIndex);
let entries = this.editRanges.slice(initialEditRangeIndex, lastEditRangeIndex);
return ts.collapseTextChangeRangesAcrossMultipleVersions(entries.map(e => e.textChangeRange));
}
}
@ -74,7 +74,7 @@ module Harness.LanguageService {
}
public getChangeRange(oldScript: ts.IScriptSnapshot): ts.TextChangeRange {
var oldShim = <ScriptSnapshot>oldScript;
let oldShim = <ScriptSnapshot>oldScript;
return this.scriptInfo.getTextChangeRangeBetweenVersions(oldShim.version, this.version);
}
}
@ -92,9 +92,9 @@ module Harness.LanguageService {
}
public getChangeRange(oldScript: ts.ScriptSnapshotShim): string {
var oldShim = <ScriptSnapshotProxy>oldScript;
let oldShim = <ScriptSnapshotProxy>oldScript;
var range = this.scriptSnapshot.getChangeRange(oldShim.scriptSnapshot);
let range = this.scriptSnapshot.getChangeRange(oldShim.scriptSnapshot);
if (range === null) {
return null;
}
@ -130,8 +130,8 @@ module Harness.LanguageService {
}
public getFilenames(): string[] {
var fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript,(fileName) => { fileNames.push(fileName); });
let fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript, (fileName) => { fileNames.push(fileName); });
return fileNames;
}
@ -144,7 +144,7 @@ module Harness.LanguageService {
}
public editScript(fileName: string, start: number, end: number, newText: string) {
var script = this.getScriptInfo(fileName);
let script = this.getScriptInfo(fileName);
if (script !== null) {
script.editContent(start, end, newText);
return;
@ -161,7 +161,7 @@ module Harness.LanguageService {
* @param col 0 based index
*/
public positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter {
var script: ScriptInfo = this.fileNameToScript[fileName];
let script: ScriptInfo = this.fileNameToScript[fileName];
assert.isNotNull(script);
return ts.computeLineAndCharacterOfPosition(script.lineMap, position);
@ -176,11 +176,11 @@ module Harness.LanguageService {
getDefaultLibFileName(): string { return ""; }
getScriptFileNames(): string[] { return this.getFilenames(); }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
var script = this.getScriptInfo(fileName);
let script = this.getScriptInfo(fileName);
return script ? new ScriptSnapshot(script) : undefined;
}
getScriptVersion(fileName: string): string {
var script = this.getScriptInfo(fileName);
let script = this.getScriptInfo(fileName);
return script ? script.version.toString() : undefined;
}
@ -220,7 +220,7 @@ module Harness.LanguageService {
getDefaultLibFileName(): string { return this.nativeHost.getDefaultLibFileName(); }
getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); }
getScriptSnapshot(fileName: string): ts.ScriptSnapshotShim {
var nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
let nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
}
getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); }
@ -242,13 +242,13 @@ module Harness.LanguageService {
throw new Error("NYI");
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
var result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
var entries: ts.ClassificationInfo[] = [];
var i = 0;
var position = 0;
let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
let entries: ts.ClassificationInfo[] = [];
let i = 0;
let position = 0;
for (; i < result.length - 1; i += 2) {
var t = entries[i / 2] = {
let t = entries[i / 2] = {
length: parseInt(result[i]),
classification: parseInt(result[i + 1])
};
@ -256,7 +256,7 @@ module Harness.LanguageService {
assert.isTrue(t.length > 0, "Result length should be greater than 0, got :" + t.length);
position += t.length;
}
var finalLexState = parseInt(result[result.length - 1]);
let finalLexState = parseInt(result[result.length - 1]);
assert.equal(position, text.length, "Expected cumulative length of all entries to match the length of the source. expected: " + text.length + ", but got: " + position);
@ -268,7 +268,7 @@ module Harness.LanguageService {
}
function unwrapJSONCallResult(result: string): any {
var parsedResult = JSON.parse(result);
let parsedResult = JSON.parse(result);
if (parsedResult.error) {
throw new Error("Language Service Shim Error: " + JSON.stringify(parsedResult.error));
}
@ -282,7 +282,7 @@ module Harness.LanguageService {
constructor(private shim: ts.LanguageServiceShim) {
}
private unwrappJSONCallResult(result: string): any {
var parsedResult = JSON.parse(result);
let parsedResult = JSON.parse(result);
if (parsedResult.error) {
throw new Error("Language Service Shim Error: " + JSON.stringify(parsedResult.error));
}
@ -404,16 +404,16 @@ module Harness.LanguageService {
getLanguageService(): ts.LanguageService { return new LanguageServiceShimProxy(this.factory.createLanguageServiceShim(this.host)); }
getClassifier(): ts.Classifier { return new ClassifierShimProxy(this.factory.createClassifierShim(this.host)); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo {
var shimResult: {
let shimResult: {
referencedFiles: ts.IFileReference[];
importedFiles: ts.IFileReference[];
isLibFile: boolean;
};
var coreServicesShim = this.factory.createCoreServicesShim(this.host);
let coreServicesShim = this.factory.createCoreServicesShim(this.host);
shimResult = unwrapJSONCallResult(coreServicesShim.getPreProcessedFileInfo(fileName, ts.ScriptSnapshot.fromString(fileContents)));
var convertResult: ts.PreProcessedFileInfo = {
let convertResult: ts.PreProcessedFileInfo = {
referencedFiles: [],
importedFiles: [],
isLibFile: shimResult.isLibFile
@ -496,7 +496,7 @@ module Harness.LanguageService {
fileName = Harness.Compiler.defaultLibFileName;
}
var snapshot = this.host.getScriptSnapshot(fileName);
let snapshot = this.host.getScriptSnapshot(fileName);
return snapshot && snapshot.getText(0, snapshot.getLength());
}
@ -574,13 +574,13 @@ module Harness.LanguageService {
private client: ts.server.SessionClient;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
// This is the main host that tests use to direct tests
var clientHost = new SessionClientHost(cancellationToken, options);
var client = new ts.server.SessionClient(clientHost);
let clientHost = new SessionClientHost(cancellationToken, options);
let client = new ts.server.SessionClient(clientHost);
// This host is just a proxy for the clientHost, it uses the client
// host to answer server queries about files on disk
var serverHost = new SessionServerHost(clientHost);
var server = new ts.server.Session(serverHost, Buffer.byteLength, process.hrtime, serverHost);
let serverHost = new SessionServerHost(clientHost);
let server = new ts.server.Session(serverHost, Buffer.byteLength, process.hrtime, serverHost);
// Fake the connection between the client and the server
serverHost.writeMessage = client.onMessage.bind(client);

View File

@ -70,9 +70,9 @@ interface PlaybackControl {
}
module Playback {
var recordLog: IOLog = undefined;
var replayLog: IOLog = undefined;
var recordLogFileNameBase = '';
let recordLog: IOLog = undefined;
let replayLog: IOLog = undefined;
let recordLogFileNameBase = '';
interface Memoized<T> {
(s: string): T;
@ -80,8 +80,8 @@ module Playback {
}
function memoize<T>(func: (s: string) => T): Memoized<T> {
var lookup: { [s: string]: T } = {};
var run: Memoized<T> = <Memoized<T>>((s: string) => {
let lookup: { [s: string]: T } = {};
let run: Memoized<T> = <Memoized<T>>((s: string) => {
if (lookup.hasOwnProperty(s)) return lookup[s];
return lookup[s] = func(s);
});
@ -161,10 +161,10 @@ module Playback {
}
function findResultByFields<T>(logArray: { result?: T }[], expectedFields: {}, defaultValue?: T): T {
var predicate = (entry: { result?: T }) => {
let predicate = (entry: { result?: T }) => {
return Object.getOwnPropertyNames(expectedFields).every((name) => (<any>entry)[name] === (<any>expectedFields)[name]);
};
var results = logArray.filter(entry => predicate(entry));
let results = logArray.filter(entry => predicate(entry));
if (results.length === 0) {
if (defaultValue !== undefined) {
return defaultValue;
@ -176,17 +176,17 @@ module Playback {
}
function findResultByPath<T>(wrapper: { resolvePath(s: string): string }, logArray: { path: string; result?: T }[], expectedPath: string, defaultValue?: T): T {
var normalizedName = ts.normalizeSlashes(expectedPath).toLowerCase();
let normalizedName = ts.normalizeSlashes(expectedPath).toLowerCase();
// Try to find the result through normal fileName
for (var i = 0; i < logArray.length; i++) {
for (let i = 0; i < logArray.length; i++) {
if (ts.normalizeSlashes(logArray[i].path).toLowerCase() === normalizedName) {
return logArray[i].result;
}
}
// Fallback, try to resolve the target paths as well
if (replayLog.pathsResolved.length > 0) {
var normalizedResolvedName = wrapper.resolvePath(expectedPath).toLowerCase();
for (var i = 0; i < logArray.length; i++) {
let normalizedResolvedName = wrapper.resolvePath(expectedPath).toLowerCase();
for (let i = 0; i < logArray.length; i++) {
if (wrapper.resolvePath(logArray[i].path).toLowerCase() === normalizedResolvedName) {
return logArray[i].result;
}
@ -200,9 +200,9 @@ module Playback {
}
}
var pathEquivCache: any = {};
let pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
var key = left + '-~~-' + right;
let key = left + '-~~-' + right;
function areSame(a: string, b: string) {
return ts.normalizeSlashes(a).toLowerCase() === ts.normalizeSlashes(b).toLowerCase();
}
@ -219,11 +219,11 @@ module Playback {
}
function noOpReplay(name: string) {
//console.log("Swallowed write operation during replay: " + name);
// console.log("Swallowed write operation during replay: " + name);
}
export function wrapSystem(underlying: ts.System): PlaybackSystem {
var wrapper: PlaybackSystem = <any>{};
let wrapper: PlaybackSystem = <any>{};
initWrapper(wrapper, underlying);
wrapper.startReplayFromFile = logFn => {
@ -231,8 +231,8 @@ module Playback {
};
wrapper.endRecord = () => {
if (recordLog !== undefined) {
var i = 0;
var fn = () => recordLogFileNameBase + i + '.json';
let i = 0;
let fn = () => recordLogFileNameBase + i + '.json';
while (underlying.fileExists(fn())) i++;
underlying.writeFile(fn(), JSON.stringify(recordLog));
recordLog = undefined;
@ -289,8 +289,8 @@ module Playback {
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
(path) => {
var result = underlying.readFile(path);
var logEntry = { path: path, codepage: 0, result: { contents: result, codepage: 0 } };
let result = underlying.readFile(path);
let logEntry = { path: path, codepage: 0, result: { contents: result, codepage: 0 } };
recordLog.filesRead.push(logEntry);
return result;
},

View File

@ -46,7 +46,7 @@ interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult {
class ProjectRunner extends RunnerBase {
public initializeTests() {
if (this.tests.length === 0) {
var testFiles = this.enumerateFiles("tests/cases/project", /\.json$/, { recursive: true });
let testFiles = this.enumerateFiles("tests/cases/project", /\.json$/, { recursive: true });
testFiles.forEach(fn => {
fn = fn.replace(/\\/g, "/");
this.runProjectTestCase(fn);
@ -58,10 +58,11 @@ class ProjectRunner extends RunnerBase {
}
private runProjectTestCase(testCaseFileName: string) {
var testCase: ProjectRunnerTestCase;
let testCase: ProjectRunnerTestCase;
let testFileText: string = null;
try {
var testFileText = ts.sys.readFile(testCaseFileName);
testFileText = ts.sys.readFile(testCaseFileName);
}
catch (e) {
assert(false, "Unable to open testcase file: " + testCaseFileName + ": " + e.message);
@ -73,7 +74,7 @@ class ProjectRunner extends RunnerBase {
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
}
var testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
function moduleNameToString(moduleKind: ts.ModuleKind) {
return moduleKind === ts.ModuleKind.AMD
@ -89,7 +90,7 @@ class ProjectRunner extends RunnerBase {
}
// When test case output goes to tests/baselines/local/projectOutput/testCaseName/moduleKind/
// We have these two separate locations because when comparing baselines the baseline verifier will delete the existing file
// We have these two separate locations because when comparing baselines the baseline verifier will delete the existing file
// so even if it was created by compiler in that location, the file will be deleted by verified before we can read it
// so lets keep these two locations separate
function getProjectOutputFolder(fileName: string, moduleKind: ts.ModuleKind) {
@ -97,9 +98,9 @@ class ProjectRunner extends RunnerBase {
}
function cleanProjectUrl(url: string) {
var diskProjectPath = ts.normalizeSlashes(ts.sys.resolvePath(testCase.projectRoot));
var projectRootUrl = "file:///" + diskProjectPath;
var normalizedProjectRoot = ts.normalizeSlashes(testCase.projectRoot);
let diskProjectPath = ts.normalizeSlashes(ts.sys.resolvePath(testCase.projectRoot));
let projectRootUrl = "file:///" + diskProjectPath;
let normalizedProjectRoot = ts.normalizeSlashes(testCase.projectRoot);
diskProjectPath = diskProjectPath.substr(0, diskProjectPath.lastIndexOf(normalizedProjectRoot));
projectRootUrl = projectRootUrl.substr(0, projectRootUrl.lastIndexOf(normalizedProjectRoot));
if (url && url.length) {
@ -124,21 +125,21 @@ class ProjectRunner extends RunnerBase {
return ts.sys.resolvePath(testCase.projectRoot);
}
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: ()=> string[],
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: () => string[],
getSourceFileText: (fileName: string) => string,
writeFile: (fileName: string, data: string, writeByteOrderMark: boolean) => void): CompileProjectFilesResult {
var program = ts.createProgram(getInputFiles(), createCompilerOptions(), createCompilerHost());
var errors = ts.getPreEmitDiagnostics(program);
let program = ts.createProgram(getInputFiles(), createCompilerOptions(), createCompilerHost());
let errors = ts.getPreEmitDiagnostics(program);
var emitResult = program.emit();
let emitResult = program.emit();
errors = ts.concatenate(errors, emitResult.diagnostics);
var sourceMapData = emitResult.sourceMaps;
let sourceMapData = emitResult.sourceMaps;
// Clean up source map data that will be used in baselining
if (sourceMapData) {
for (var i = 0; i < sourceMapData.length; i++) {
for (var j = 0; j < sourceMapData[i].sourceMapSources.length; j++) {
for (let i = 0; i < sourceMapData.length; i++) {
for (let j = 0; j < sourceMapData[i].sourceMapSources.length; j++) {
sourceMapData[i].sourceMapSources[j] = cleanProjectUrl(sourceMapData[i].sourceMapSources[j]);
}
sourceMapData[i].jsSourceMappingURL = cleanProjectUrl(sourceMapData[i].jsSourceMappingURL);
@ -168,12 +169,12 @@ class ProjectRunner extends RunnerBase {
}
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile {
var sourceFile: ts.SourceFile = undefined;
let sourceFile: ts.SourceFile = undefined;
if (fileName === Harness.Compiler.defaultLibFileName) {
sourceFile = languageVersion === ts.ScriptTarget.ES6 ? Harness.Compiler.defaultES6LibSourceFile : Harness.Compiler.defaultLibSourceFile;
}
else {
var text = getSourceFileText(fileName);
let text = getSourceFileText(fileName);
if (text !== undefined) {
sourceFile = Harness.Compiler.createSourceFileAndAssertInvariants(fileName, text, languageVersion);
}
@ -194,13 +195,13 @@ class ProjectRunner extends RunnerBase {
};
}
}
function batchCompilerProjectTestCase(moduleKind: ts.ModuleKind): BatchCompileProjectTestCaseResult{
var nonSubfolderDiskFiles = 0;
let nonSubfolderDiskFiles = 0;
var outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
let outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
var projectCompilerResult = compileProjectFiles(moduleKind, () => testCase.inputFiles, getSourceFileText, writeFile);
let projectCompilerResult = compileProjectFiles(moduleKind, () => testCase.inputFiles, getSourceFileText, writeFile);
return {
moduleKind,
program: projectCompilerResult.program,
@ -211,8 +212,9 @@ class ProjectRunner extends RunnerBase {
};
function getSourceFileText(fileName: string): string {
let text: string = undefined;
try {
var text = ts.sys.readFile(ts.isRootedDiskPath(fileName)
text = ts.sys.readFile(ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName));
}
@ -223,14 +225,14 @@ class ProjectRunner extends RunnerBase {
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean) {
var diskFileName = ts.isRootedDiskPath(fileName)
let diskFileName = ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName);
var diskRelativeName = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, diskFileName,
let diskRelativeName = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, diskFileName,
getCurrentDirectory(), Harness.Compiler.getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
if (ts.isRootedDiskPath(diskRelativeName) || diskRelativeName.substr(0, 3) === "../") {
// If the generated output file resides in the parent folder or is rooted path,
// If the generated output file resides in the parent folder or is rooted path,
// we need to instead create files that can live in the project reference folder
// but make sure extension of these files matches with the fileName the compiler asked to write
diskRelativeName = "diskFile" + nonSubfolderDiskFiles++ +
@ -240,22 +242,22 @@ class ProjectRunner extends RunnerBase {
if (Harness.Compiler.isJS(fileName)) {
// Make sure if there is URl we have it cleaned up
var indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
let indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
if (indexOfSourceMapUrl !== -1) {
data = data.substring(0, indexOfSourceMapUrl + 21) + cleanProjectUrl(data.substring(indexOfSourceMapUrl + 21));
}
}
else if (Harness.Compiler.isJSMap(fileName)) {
// Make sure sources list is cleaned
var sourceMapData = JSON.parse(data);
for (var i = 0; i < sourceMapData.sources.length; i++) {
let sourceMapData = JSON.parse(data);
for (let i = 0; i < sourceMapData.sources.length; i++) {
sourceMapData.sources[i] = cleanProjectUrl(sourceMapData.sources[i]);
}
sourceMapData.sourceRoot = cleanProjectUrl(sourceMapData.sourceRoot);
data = JSON.stringify(sourceMapData);
}
var outputFilePath = getProjectOutputFolder(diskRelativeName, moduleKind);
let outputFilePath = getProjectOutputFolder(diskRelativeName, moduleKind);
// Actual writing of file as in tc.ts
function ensureDirectoryStructure(directoryname: string) {
if (directoryname) {
@ -273,36 +275,37 @@ class ProjectRunner extends RunnerBase {
}
function compileCompileDTsFiles(compilerResult: BatchCompileProjectTestCaseResult) {
var allInputFiles: { emittedFileName: string; code: string; }[] = [];
var compilerOptions = compilerResult.program.getCompilerOptions();
let allInputFiles: { emittedFileName: string; code: string; }[] = [];
let compilerOptions = compilerResult.program.getCompilerOptions();
ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => {
if (Harness.Compiler.isDTS(sourceFile.fileName)) {
allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text });
}
else if (ts.shouldEmitToOwnFile(sourceFile, compilerResult.program.getCompilerOptions())) {
let emitOutputFilePathWithoutExtension: string = undefined;
if (compilerOptions.outDir) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, compilerResult.program.getCurrentDirectory());
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, compilerResult.program.getCurrentDirectory());
sourceFilePath = sourceFilePath.replace(compilerResult.program.getCommonSourceDirectory(), "");
var emitOutputFilePathWithoutExtension = ts.removeFileExtension(ts.combinePaths(compilerOptions.outDir, sourceFilePath));
emitOutputFilePathWithoutExtension = ts.removeFileExtension(ts.combinePaths(compilerOptions.outDir, sourceFilePath));
}
else {
var emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName);
emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName);
}
var outputDtsFileName = emitOutputFilePathWithoutExtension + ".d.ts";
let outputDtsFileName = emitOutputFilePathWithoutExtension + ".d.ts";
allInputFiles.unshift(findOutpuDtsFile(outputDtsFileName));
}
else {
var outputDtsFileName = ts.removeFileExtension(compilerOptions.out) + ".d.ts";
var outputDtsFile = findOutpuDtsFile(outputDtsFileName);
let outputDtsFileName = ts.removeFileExtension(compilerOptions.out) + ".d.ts";
let outputDtsFile = findOutpuDtsFile(outputDtsFileName);
if (!ts.contains(allInputFiles, outputDtsFile)) {
allInputFiles.unshift(outputDtsFile);
}
}
});
return compileProjectFiles(compilerResult.moduleKind,getInputFiles, getSourceFileText, writeFile);
return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile);
function findOutpuDtsFile(fileName: string) {
return ts.forEach(compilerResult.outputFiles, outputFile => outputFile.emittedFileName === fileName ? outputFile : undefined);
@ -319,7 +322,7 @@ class ProjectRunner extends RunnerBase {
}
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
var inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
let inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => {
return { unitName: sourceFile.fileName, content: sourceFile.text };
@ -328,110 +331,112 @@ class ProjectRunner extends RunnerBase {
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
var name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
let name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
describe(name, () => {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
function getCompilerResolutionInfo() {
var resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
scenario: testCase.scenario,
projectRoot: testCase.projectRoot,
inputFiles: testCase.inputFiles,
out: testCase.out,
outDir: testCase.outDir,
sourceMap: testCase.sourceMap,
mapRoot: testCase.mapRoot,
resolveMapRoot: testCase.resolveMapRoot,
sourceRoot: testCase.sourceRoot,
resolveSourceRoot: testCase.resolveSourceRoot,
declaration: testCase.declaration,
baselineCheck: testCase.baselineCheck,
runTest: testCase.runTest,
bug: testCase.bug,
rootDir: testCase.rootDir,
resolvedInputFiles: ts.map(compilerResult.program.getSourceFiles(), inputFile => inputFile.fileName),
emittedFiles: ts.map(compilerResult.outputFiles, outputFile => outputFile.emittedFileName)
};
describe('Projects tests', () => {
describe(name, () => {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
let compilerResult: BatchCompileProjectTestCaseResult;
return resolutionInfo;
}
function getCompilerResolutionInfo() {
let resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
scenario: testCase.scenario,
projectRoot: testCase.projectRoot,
inputFiles: testCase.inputFiles,
out: testCase.out,
outDir: testCase.outDir,
sourceMap: testCase.sourceMap,
mapRoot: testCase.mapRoot,
resolveMapRoot: testCase.resolveMapRoot,
sourceRoot: testCase.sourceRoot,
resolveSourceRoot: testCase.resolveSourceRoot,
declaration: testCase.declaration,
baselineCheck: testCase.baselineCheck,
runTest: testCase.runTest,
bug: testCase.bug,
rootDir: testCase.rootDir,
resolvedInputFiles: ts.map(compilerResult.program.getSourceFiles(), inputFile => inputFile.fileName),
emittedFiles: ts.map(compilerResult.outputFiles, outputFile => outputFile.emittedFileName)
};
var compilerResult: BatchCompileProjectTestCaseResult;
return resolutionInfo;
}
it(name + ": " + moduleNameToString(moduleKind) , () => {
// Compile using node
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
it('Resolution information of (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.json', () => {
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
it(name + ": " + moduleNameToString(moduleKind) , () => {
// Compile using node
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
});
it('Errors for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (compilerResult.errors.length) {
Harness.Baseline.runBaseline('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.errors.txt', () => {
return getErrorsBaseline(compilerResult);
it('Resolution information of (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.json', () => {
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
});
}
});
});
it('Baseline of emitted result (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
Harness.Baseline.runBaseline('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return ts.sys.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
}
});
});
}
});
it('SourceMapRecord for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
}
});
// Verify that all the generated .d.ts files compile
it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
var dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
return getErrorsBaseline(dTsCompileResult);
it('Errors for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (compilerResult.errors.length) {
Harness.Baseline.runBaseline('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.errors.txt', () => {
return getErrorsBaseline(compilerResult);
});
}
}
});
});
it('Baseline of emitted result (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
Harness.Baseline.runBaseline('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return ts.sys.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
}
});
});
}
});
it('SourceMapRecord for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
}
});
// Verify that all the generated .d.ts files compile
it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
let dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
return getErrorsBaseline(dTsCompileResult);
});
}
}
});
after(() => {
compilerResult = undefined;
});
}
verifyCompilerResults(ts.ModuleKind.CommonJS);
verifyCompilerResults(ts.ModuleKind.AMD);
after(() => {
compilerResult = undefined;
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
testCase = undefined;
testFileText = undefined;
testCaseJustName = undefined;
});
}
verifyCompilerResults(ts.ModuleKind.CommonJS);
verifyCompilerResults(ts.ModuleKind.AMD);
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
testCase = undefined;
testFileText = undefined;
testCaseJustName = undefined;
});
});
}
}
}

View File

@ -1,6 +1,6 @@
//
// 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
@ -20,26 +20,26 @@
/// <reference path='rwcRunner.ts' />
/// <reference path='harness.ts' />
let runners: RunnerBase[] = [];
let iterations: number = 1;
function runTests(runners: RunnerBase[]) {
for (var i = iterations; i > 0; i--) {
for (var j = 0; j < runners.length; j++) {
for (let i = iterations; i > 0; i--) {
for (let j = 0; j < runners.length; j++) {
runners[j].initializeTests();
}
}
}
var runners: RunnerBase[] = [];
var iterations: number = 1;
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
var mytestconfig = 'mytest.config';
var testconfig = 'test.config';
var testConfigFile =
let mytestconfig = 'mytest.config';
let testconfig = 'test.config';
let testConfigFile =
Harness.IO.fileExists(mytestconfig) ? Harness.IO.readFile(mytestconfig) :
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : '');
if (testConfigFile !== '') {
var testConfig = JSON.parse(testConfigFile);
let testConfig = JSON.parse(testConfigFile);
if (testConfig.light) {
Harness.lightMode = true;
}
@ -99,7 +99,7 @@ if (runners.length === 0) {
runners.push(new FourSlashRunner(FourSlashTestType.Native));
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
runners.push(new FourSlashRunner(FourSlashTestType.Server));
//runners.push(new GeneratedFourslashRunner());
// runners.push(new GeneratedFourslashRunner());
}
ts.sys.newLine = '\r\n';

View File

@ -24,17 +24,17 @@ class RunnerBase {
/** Replaces instances of full paths with fileNames only */
static removeFullPaths(path: string) {
var fixedPath = path;
let fixedPath = path;
// full paths either start with a drive letter or / for *nix, shouldn't have \ in the path at this point
var fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
var fullPathList = fixedPath.match(fullPath);
let fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
let fullPathList = fixedPath.match(fullPath);
if (fullPathList) {
fullPathList.forEach((match: string) => fixedPath = fixedPath.replace(match, Harness.Path.getFileName(match)));
}
// when running in the browser the 'full path' is the host name, shows up in error baselines
var localHost = /http:\/localhost:\d+/g;
let localHost = /http:\/localhost:\d+/g;
fixedPath = fixedPath.replace(localHost, '');
return fixedPath;
}

View File

@ -5,9 +5,9 @@
module RWC {
function runWithIOLog(ioLog: IOLog, fn: () => void) {
var oldSys = ts.sys;
let oldSys = ts.sys;
var wrappedSys = Playback.wrapSystem(ts.sys);
let wrappedSys = Playback.wrapSystem(ts.sys);
wrappedSys.startReplayFromData(ioLog);
ts.sys = wrappedSys;
@ -21,17 +21,17 @@ module RWC {
export function runRWCTest(jsonPath: string) {
describe("Testing a RWC project: " + jsonPath, () => {
var inputFiles: { unitName: string; content: string; }[] = [];
var otherFiles: { unitName: string; content: string; }[] = [];
var compilerResult: Harness.Compiler.CompilerResult;
var compilerOptions: ts.CompilerOptions;
var baselineOpts: Harness.Baseline.BaselineOptions = {
let inputFiles: { unitName: string; content: string; }[] = [];
let otherFiles: { unitName: string; content: string; }[] = [];
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: 'rwc',
Baselinefolder: 'internal/baselines'
};
var baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
var currentDirectory: string;
var useCustomLibraryFile: boolean;
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
let useCustomLibraryFile: boolean;
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
@ -50,10 +50,10 @@ module RWC {
});
it('can compile', () => {
var harnessCompiler = Harness.Compiler.getCompiler();
var opts: ts.ParsedCommandLine;
let harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
var ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
let ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
currentDirectory = ioLog.currentDirectory;
useCustomLibraryFile = ioLog.useCustomLibraryFile;
runWithIOLog(ioLog, () => {
@ -77,7 +77,7 @@ module RWC {
for (let fileRead of ioLog.filesRead) {
// Check if the file is already added into the set of input files.
var resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
var inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
let inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
if (!Harness.isLibraryFile(fileRead.path)) {
if (inInputList) {
@ -117,9 +117,10 @@ module RWC {
});
function getHarnessCompilerInputUnit(fileName: string) {
var unitName = ts.normalizeSlashes(ts.sys.resolvePath(fileName));
let unitName = ts.normalizeSlashes(ts.sys.resolvePath(fileName));
let content: string = null;
try {
var content = ts.sys.readFile(unitName);
content = ts.sys.readFile(unitName);
}
catch (e) {
// Leave content undefined.
@ -155,13 +156,13 @@ module RWC {
}, false, baselineOpts);
});
//it('has correct source map record', () => {
// if (compilerOptions.sourceMap) {
// Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
// return compilerResult.getSourceMapRecord();
// }, false, baselineOpts);
// }
//});
/*it('has correct source map record', () => {
if (compilerOptions.sourceMap) {
Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
return compilerResult.getSourceMapRecord();
}, false, baselineOpts);
}
});*/
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
@ -178,7 +179,7 @@ module RWC {
it('has the expected errors in generated declaration files', () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => {
var declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
let declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
/*settingscallback*/ undefined, compilerOptions, currentDirectory);
if (declFileCompilationResult.declResult.errors.length === 0) {
return null;
@ -204,8 +205,8 @@ class RWCRunner extends RunnerBase {
*/
public initializeTests(): void {
// Read in and evaluate the test list
var testList = Harness.IO.listFiles(RWCRunner.sourcePath, /.+\.json$/);
for (var i = 0; i < testList.length; i++) {
let testList = Harness.IO.listFiles(RWCRunner.sourcePath, /.+\.json$/);
for (let i = 0; i < testList.length; i++) {
this.runTest(testList[i]);
}
}

View File

@ -1,6 +1,6 @@
//
// 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
@ -23,12 +23,12 @@ module Harness.SourceMapRecoder {
}
module SourceMapDecoder {
var sourceMapMappings: string;
var sourceMapNames: string[];
var decodingIndex: number;
var prevNameIndex: number;
var decodeOfEncodedMapping: ts.SourceMapSpan;
var errorDecodeOfEncodedMapping: string;
let sourceMapMappings: string;
let sourceMapNames: string[];
let decodingIndex: number;
let prevNameIndex: number;
let decodeOfEncodedMapping: ts.SourceMapSpan;
let errorDecodeOfEncodedMapping: string;
export function initializeSourceMapDecoding(sourceMapData: ts.SourceMapData) {
sourceMapMappings = sourceMapData.sourceMapMappings;
@ -82,9 +82,9 @@ module Harness.SourceMapRecoder {
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(sourceMapMappings.charAt(decodingIndex));
}
var moreDigits = true;
var shiftCount = 0;
var value = 0;
let moreDigits = true;
let shiftCount = 0;
let value = 0;
for (; moreDigits; decodingIndex++) {
if (createErrorIfCondition(decodingIndex >= sourceMapMappings.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) {
@ -92,7 +92,7 @@ module Harness.SourceMapRecoder {
}
// 6 digit number
var currentByte = base64FormatDecode();
let currentByte = base64FormatDecode();
// If msb is set, we still have more bits to continue
moreDigits = (currentByte & 32) !== 0;
@ -143,7 +143,7 @@ module Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 2. Relative sourceIndex
// 2. Relative sourceIndex
decodeOfEncodedMapping.sourceIndex += base64VLQFormatDecode();
// Incorrect sourceIndex dont support this map
if (createErrorIfCondition(decodeOfEncodedMapping.sourceIndex < 0, "Invalid sourceIndex found")) {
@ -165,7 +165,7 @@ module Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 4. Relative sourceColumn 0 based
// 4. Relative sourceColumn 0 based
decodeOfEncodedMapping.sourceColumn += base64VLQFormatDecode();
// Incorrect sourceColumn dont support this map
if (createErrorIfCondition(decodeOfEncodedMapping.sourceColumn < 1, "Invalid sourceLine found")) {
@ -203,19 +203,19 @@ module Harness.SourceMapRecoder {
}
module SourceMapSpanWriter {
var sourceMapRecoder: Compiler.WriterAggregator;
var sourceMapSources: string[];
var sourceMapNames: string[];
let sourceMapRecoder: Compiler.WriterAggregator;
let sourceMapSources: string[];
let sourceMapNames: string[];
var jsFile: Compiler.GeneratedFile;
var jsLineMap: number[];
var tsCode: string;
var tsLineMap: number[];
let jsFile: Compiler.GeneratedFile;
let jsLineMap: number[];
let tsCode: string;
let tsLineMap: number[];
var spansOnSingleLine: SourceMapSpanWithDecodeErrors[];
var prevWrittenSourcePos: number;
var prevWrittenJsLine: number;
var spanMarkerContinues: boolean;
let spansOnSingleLine: SourceMapSpanWithDecodeErrors[];
let prevWrittenSourcePos: number;
let prevWrittenJsLine: number;
let spanMarkerContinues: boolean;
export function intializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: Compiler.GeneratedFile) {
sourceMapRecoder = sourceMapRecordWriter;
@ -244,7 +244,7 @@ module Harness.SourceMapRecoder {
}
function getSourceMapSpanString(mapEntry: ts.SourceMapSpan, getAbsentNameIndex?: boolean) {
var mapString = "Emitted(" + mapEntry.emittedLine + ", " + mapEntry.emittedColumn + ") Source(" + mapEntry.sourceLine + ", " + mapEntry.sourceColumn + ") + SourceIndex(" + mapEntry.sourceIndex + ")";
let mapString = "Emitted(" + mapEntry.emittedLine + ", " + mapEntry.emittedColumn + ") Source(" + mapEntry.sourceLine + ", " + mapEntry.sourceColumn + ") + SourceIndex(" + mapEntry.sourceIndex + ")";
if (mapEntry.nameIndex >= 0 && mapEntry.nameIndex < sourceMapNames.length) {
mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")";
}
@ -259,8 +259,8 @@ module Harness.SourceMapRecoder {
export function recordSourceMapSpan(sourceMapSpan: ts.SourceMapSpan) {
// verify the decoded span is same as the new span
var decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan();
var decodedErrors: string[];
let decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan();
let decodedErrors: string[];
if (decodeResult.error
|| decodeResult.sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine
|| decodeResult.sourceMapSpan.emittedColumn !== sourceMapSpan.emittedColumn
@ -278,7 +278,7 @@ module Harness.SourceMapRecoder {
}
if (spansOnSingleLine.length && spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine) {
// On different line from the one that we have been recording till now,
// On different line from the one that we have been recording till now,
writeRecordedSpans();
spansOnSingleLine = [{ sourceMapSpan: sourceMapSpan, decodeErrors: decodedErrors }];
}
@ -317,8 +317,8 @@ module Harness.SourceMapRecoder {
}
function getTextOfLine(line: number, lineMap: number[], code: string) {
var startPos = lineMap[line];
var endPos = lineMap[line + 1];
let startPos = lineMap[line];
let endPos = lineMap[line + 1];
return code.substring(startPos, endPos);
}
@ -329,14 +329,16 @@ module Harness.SourceMapRecoder {
}
function writeRecordedSpans() {
let markerIds: string[] = [];
function getMarkerId(markerIndex: number) {
var markerId = "";
let markerId = "";
if (spanMarkerContinues) {
assert.isTrue(markerIndex === 0);
markerId = "1->";
}
else {
var markerId = "" + (markerIndex + 1);
markerId = "" + (markerIndex + 1);
if (markerId.length < 2) {
markerId = markerId + " ";
}
@ -345,10 +347,10 @@ module Harness.SourceMapRecoder {
return markerId;
}
var prevEmittedCol: number;
let prevEmittedCol: number;
function iterateSpans(fn: (currentSpan: SourceMapSpanWithDecodeErrors, index: number) => void) {
prevEmittedCol = 1;
for (var i = 0; i < spansOnSingleLine.length; i++) {
for (let i = 0; i < spansOnSingleLine.length; i++) {
fn(spansOnSingleLine[i], i);
prevEmittedCol = spansOnSingleLine[i].sourceMapSpan.emittedColumn;
}
@ -356,18 +358,18 @@ module Harness.SourceMapRecoder {
function writeSourceMapIndent(indentLength: number, indentPrefix: string) {
sourceMapRecoder.Write(indentPrefix);
for (var i = 1; i < indentLength; i++) {
for (let i = 1; i < indentLength; i++) {
sourceMapRecoder.Write(" ");
}
}
function writeSourceMapMarker(currentSpan: SourceMapSpanWithDecodeErrors, index: number, endColumn = currentSpan.sourceMapSpan.emittedColumn, endContinues?: boolean) {
var markerId = getMarkerId(index);
let markerId = getMarkerId(index);
markerIds.push(markerId);
writeSourceMapIndent(prevEmittedCol, markerId);
for (var i = prevEmittedCol; i < endColumn; i++) {
for (let i = prevEmittedCol; i < endColumn; i++) {
sourceMapRecoder.Write("^");
}
if (endContinues) {
@ -378,8 +380,8 @@ module Harness.SourceMapRecoder {
}
function writeSourceMapSourceText(currentSpan: SourceMapSpanWithDecodeErrors, index: number) {
var sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine - 1] + (currentSpan.sourceMapSpan.sourceColumn - 1);
var sourceText = "";
let sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine - 1] + (currentSpan.sourceMapSpan.sourceColumn - 1);
let sourceText = "";
if (prevWrittenSourcePos < sourcePos) {
// Position that goes forward, get text
sourceText = tsCode.substring(prevWrittenSourcePos, sourcePos);
@ -387,14 +389,14 @@ module Harness.SourceMapRecoder {
if (currentSpan.decodeErrors) {
// If there are decode errors, write
for (var i = 0; i < currentSpan.decodeErrors.length; i++) {
for (let i = 0; i < currentSpan.decodeErrors.length; i++) {
writeSourceMapIndent(prevEmittedCol, markerIds[index]);
sourceMapRecoder.WriteLine(currentSpan.decodeErrors[i]);
}
}
var tsCodeLineMap = ts.computeLineStarts(sourceText);
for (var i = 0; i < tsCodeLineMap.length; i++) {
let tsCodeLineMap = ts.computeLineStarts(sourceText);
for (let i = 0; i < tsCodeLineMap.length; i++) {
writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >");
sourceMapRecoder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
if (i === tsCodeLineMap.length - 1) {
@ -410,16 +412,15 @@ module Harness.SourceMapRecoder {
}
if (spansOnSingleLine.length) {
var currentJsLine = spansOnSingleLine[0].sourceMapSpan.emittedLine;
let currentJsLine = spansOnSingleLine[0].sourceMapSpan.emittedLine;
// Write js line
writeJsFileLines(currentJsLine);
// Emit markers
var markerIds: string[] = [];
iterateSpans(writeSourceMapMarker);
var jsFileText = getTextOfLine(currentJsLine, jsLineMap, jsFile.code);
let jsFileText = getTextOfLine(currentJsLine, jsLineMap, jsFile.code);
if (prevEmittedCol < jsFileText.length) {
// There is remaining text on this line that will be part of next source span so write marker that continues
writeSourceMapMarker(undefined, spansOnSingleLine.length, /*endColumn*/ jsFileText.length, /*endContinues*/ true);
@ -437,16 +438,16 @@ module Harness.SourceMapRecoder {
}
export function getSourceMapRecord(sourceMapDataList: ts.SourceMapData[], program: ts.Program, jsFiles: Compiler.GeneratedFile[]) {
var sourceMapRecoder = new Compiler.WriterAggregator();
let sourceMapRecoder = new Compiler.WriterAggregator();
for (var i = 0; i < sourceMapDataList.length; i++) {
var sourceMapData = sourceMapDataList[i];
var prevSourceFile: ts.SourceFile = null;
for (let i = 0; i < sourceMapDataList.length; i++) {
let sourceMapData = sourceMapDataList[i];
let prevSourceFile: ts.SourceFile = null;
SourceMapSpanWriter.intializeSourceMapSpanWriter(sourceMapRecoder, sourceMapData, jsFiles[i]);
for (var j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
var decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
var currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
for (let j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
let decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
let currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
if (currentSourceFile !== prevSourceFile) {
SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
prevSourceFile = currentSourceFile;
@ -455,7 +456,7 @@ module Harness.SourceMapRecoder {
SourceMapSpanWriter.recordSourceMapSpan(decodedSourceMapping);
}
}
SourceMapSpanWriter.close();// If the last spans werent emitted, emit them
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
return sourceMapRecoder.lines.join('\r\n');

View File

@ -27,7 +27,7 @@ class Test262BaselineRunner extends RunnerBase {
describe('test262 test for ' + filePath, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
var testState: {
let testState: {
filename: string;
compilerResult: Harness.Compiler.CompilerResult;
inputFiles: { unitName: string; content: string }[];
@ -35,11 +35,11 @@ class Test262BaselineRunner extends RunnerBase {
};
before(() => {
var content = Harness.IO.readFile(filePath);
var testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
var testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
let content = Harness.IO.readFile(filePath);
let testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
let testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
var inputFiles = testCaseContent.testUnitData.map(unit => {
let inputFiles = testCaseContent.testUnitData.map(unit => {
return { unitName: Test262BaselineRunner.getTestFilePath(unit.name), content: unit.content };
});
@ -63,14 +63,14 @@ class Test262BaselineRunner extends RunnerBase {
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', testState.filename + '.output.js', () => {
var files = testState.compilerResult.files.filter(f=> f.fileName !== Test262BaselineRunner.helpersFilePath);
let files = testState.compilerResult.files.filter(f => f.fileName !== Test262BaselineRunner.helpersFilePath);
return Harness.Compiler.collateOutputs(files);
}, false, Test262BaselineRunner.baselineOptions);
});
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', testState.filename + '.errors.txt', () => {
var errors = testState.compilerResult.errors;
let errors = testState.compilerResult.errors;
if (errors.length === 0) {
return null;
}
@ -79,14 +79,14 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
it('satisfies invariants', () => {
var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
it('satisfies inletiants', () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it('has the expected AST',() => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt',() => {
var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
it('has the expected AST', () => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt', () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
});
@ -96,7 +96,7 @@ class Test262BaselineRunner extends RunnerBase {
public initializeTests() {
// this will set up a series of describe/it blocks to run between the setup and cleanup phases
if (this.tests.length === 0) {
var testFiles = this.enumerateFiles(Test262BaselineRunner.basePath, Test262BaselineRunner.testFileExtensionRegex, { recursive: true });
let testFiles = this.enumerateFiles(Test262BaselineRunner.basePath, Test262BaselineRunner.testFileExtensionRegex, { recursive: true });
testFiles.forEach(fn => {
this.runTest(ts.normalizePath(fn));
});
@ -105,4 +105,4 @@ class Test262BaselineRunner extends RunnerBase {
this.tests.forEach(test => this.runTest(test));
}
}
}
}

View File

@ -13,7 +13,7 @@ class TypeWriterWalker {
private checker: ts.TypeChecker;
constructor(private program: ts.Program, fullTypeCheck: boolean) {
// Consider getting both the diagnostics checker and the non-diagnostics checker to verify
// Consider getting both the diagnostics checker and the non-diagnostics checker to verify
// they are consistent.
this.checker = fullTypeCheck
? program.getDiagnosticsProducingTypeChecker()
@ -21,7 +21,7 @@ class TypeWriterWalker {
}
public getTypeAndSymbols(fileName: string): TypeWriterResult[] {
var sourceFile = this.program.getSourceFile(fileName);
let sourceFile = this.program.getSourceFile(fileName);
this.currentSourceFile = sourceFile;
this.results = [];
this.visitNode(sourceFile);
@ -37,19 +37,19 @@ class TypeWriterWalker {
}
private logTypeAndSymbol(node: ts.Node): void {
var actualPos = ts.skipTrivia(this.currentSourceFile.text, node.pos);
var lineAndCharacter = this.currentSourceFile.getLineAndCharacterOfPosition(actualPos);
var sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node);
let actualPos = ts.skipTrivia(this.currentSourceFile.text, node.pos);
let lineAndCharacter = this.currentSourceFile.getLineAndCharacterOfPosition(actualPos);
let sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node);
// Workaround to ensure we output 'C' instead of 'typeof C' for base class expressions
// var type = this.checker.getTypeAtLocation(node);
var type = node.parent && ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent) && this.checker.getTypeAtLocation(node.parent) || this.checker.getTypeAtLocation(node);
// let type = this.checker.getTypeAtLocation(node);
let type = node.parent && ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent) && this.checker.getTypeAtLocation(node.parent) || this.checker.getTypeAtLocation(node);
ts.Debug.assert(type !== undefined, "type doesn't exist");
var symbol = this.checker.getSymbolAtLocation(node);
let symbol = this.checker.getSymbolAtLocation(node);
var typeString = this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation);
var symbolString: string;
let typeString = this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation);
let symbolString: string;
if (symbol) {
symbolString = "Symbol(" + this.checker.symbolToString(symbol, node.parent);
if (symbol.declarations) {
@ -57,7 +57,7 @@ class TypeWriterWalker {
symbolString += ", ";
let declSourceFile = declaration.getSourceFile();
let declLineAndCharacter = declSourceFile.getLineAndCharacterOfPosition(declaration.pos);
symbolString += `Decl(${ ts.getBaseFileName(declSourceFile.fileName) }, ${ declLineAndCharacter.line }, ${ declLineAndCharacter.character })`
symbolString += `Decl(${ ts.getBaseFileName(declSourceFile.fileName) }, ${ declLineAndCharacter.line }, ${ declLineAndCharacter.character })`;
}
}
symbolString += ")";

View File

@ -839,6 +839,127 @@ namespace ts.server {
exit() {
}
private handlers : Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = {
[CommandNames.Exit]: () => {
this.exit();
return {};
},
[CommandNames.Definition]: (request: protocol.Request) => {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file)};
},
[CommandNames.TypeDefinition]: (request: protocol.Request) => {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file)};
},
[CommandNames.References]: (request: protocol.Request) => {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file)};
},
[CommandNames.Rename]: (request: protocol.Request) => {
var renameArgs = <protocol.RenameRequestArgs>request.arguments;
return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings)}
},
[CommandNames.Open]: (request: protocol.Request) => {
var openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file);
return {}
},
[CommandNames.Quickinfo]: (request: protocol.Request) => {
var quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file)};
},
[CommandNames.Format]: (request: protocol.Request) => {
var formatArgs = <protocol.FormatRequestArgs>request.arguments;
return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file)};
},
[CommandNames.Formatonkey]: (request: protocol.Request) => {
var formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments;
return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file)};
},
[CommandNames.Completions]: (request: protocol.Request) => {
var completionsArgs = <protocol.CompletionsRequestArgs>request.arguments;
return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file)}
},
[CommandNames.CompletionDetails]: (request: protocol.Request) => {
var completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments;
return {response: this.getCompletionEntryDetails(completionDetailsArgs.line,completionDetailsArgs.offset,
completionDetailsArgs.entryNames,completionDetailsArgs.file)}
},
[CommandNames.SignatureHelp]: (request: protocol.Request) => {
var signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments;
return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file)}
},
[CommandNames.Geterr]: (request: protocol.Request) => {
var geterrArgs = <protocol.GeterrRequestArgs>request.arguments;
return {response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false};
},
[CommandNames.Change]: (request: protocol.Request) => {
var changeArgs = <protocol.ChangeRequestArgs>request.arguments;
this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset,
changeArgs.insertString, changeArgs.file);
return {responseRequired: false}
},
[CommandNames.Configure]: (request: protocol.Request) => {
var configureArgs = <protocol.ConfigureRequestArguments>request.arguments;
this.projectService.setHostConfiguration(configureArgs);
this.output(undefined, CommandNames.Configure, request.seq);
return {responseRequired: false}
},
[CommandNames.Reload]: (request: protocol.Request) => {
var reloadArgs = <protocol.ReloadRequestArgs>request.arguments;
this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq);
return {responseRequired: false}
},
[CommandNames.Saveto]: (request: protocol.Request) => {
var savetoArgs = <protocol.SavetoRequestArgs>request.arguments;
this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
return {responseRequired: false}
},
[CommandNames.Close]: (request: protocol.Request) => {
var closeArgs = <protocol.FileRequestArgs>request.arguments;
this.closeClientFile(closeArgs.file);
return {responseRequired: false};
},
[CommandNames.Navto]: (request: protocol.Request) => {
var navtoArgs = <protocol.NavtoRequestArgs>request.arguments;
return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount)};
},
[CommandNames.Brace]: (request: protocol.Request) => {
var braceArguments = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file)};
},
[CommandNames.NavBar]: (request: protocol.Request) => {
var navBarArgs = <protocol.FileRequestArgs>request.arguments;
return {response: this.getNavigationBarItems(navBarArgs.file)};
},
[CommandNames.Occurrences]: (request: protocol.Request) => {
var { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getOccurrences(line, offset, fileName)};
},
[CommandNames.ProjectInfo]: (request: protocol.Request) => {
var { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments;
return {response: this.getProjectInfo(file, needFileNameList)};
},
};
addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) {
if (this.handlers[command]) {
throw new Error(`Protocol handler already exists for command "${command}"`);
}
this.handlers[command] = handler;
}
executeCommand(request: protocol.Request) : {response?: any, responseRequired?: boolean} {
var handler = this.handlers[request.command];
if (handler) {
return handler(request);
} else {
this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request));
this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command);
return {responseRequired: false};
}
}
onMessage(message: string) {
if (this.logger.isVerbose()) {
this.logger.info("request: " + message);
@ -846,142 +967,7 @@ namespace ts.server {
}
try {
var request = <protocol.Request>JSON.parse(message);
var response: any;
var errorMessage: string;
var responseRequired = true;
switch (request.command) {
case CommandNames.Exit: {
this.exit();
responseRequired = false;
break;
}
case CommandNames.Definition: {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getDefinition(defArgs.line, defArgs.offset, defArgs.file);
break;
}
case CommandNames.TypeDefinition: {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file);
break;
}
case CommandNames.References: {
var refArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getReferences(refArgs.line, refArgs.offset, refArgs.file);
break;
}
case CommandNames.Rename: {
var renameArgs = <protocol.RenameRequestArgs>request.arguments;
response = this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings);
break;
}
case CommandNames.Open: {
var openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file);
responseRequired = false;
break;
}
case CommandNames.Quickinfo: {
var quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file);
break;
}
case CommandNames.Format: {
var formatArgs = <protocol.FormatRequestArgs>request.arguments;
response = this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file);
break;
}
case CommandNames.Formatonkey: {
var formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments;
response = this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file);
break;
}
case CommandNames.Completions: {
var completionsArgs = <protocol.CompletionsRequestArgs>request.arguments;
response = this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file);
break;
}
case CommandNames.CompletionDetails: {
var completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments;
response =
this.getCompletionEntryDetails(completionDetailsArgs.line,completionDetailsArgs.offset,
completionDetailsArgs.entryNames,completionDetailsArgs.file);
break;
}
case CommandNames.SignatureHelp: {
var signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments;
response = this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file);
break;
}
case CommandNames.Geterr: {
var geterrArgs = <protocol.GeterrRequestArgs>request.arguments;
response = this.getDiagnostics(geterrArgs.delay, geterrArgs.files);
responseRequired = false;
break;
}
case CommandNames.Change: {
var changeArgs = <protocol.ChangeRequestArgs>request.arguments;
this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset,
changeArgs.insertString, changeArgs.file);
responseRequired = false;
break;
}
case CommandNames.Configure: {
var configureArgs = <protocol.ConfigureRequestArguments>request.arguments;
this.projectService.setHostConfiguration(configureArgs);
this.output(undefined, CommandNames.Configure, request.seq);
responseRequired = false;
break;
}
case CommandNames.Reload: {
var reloadArgs = <protocol.ReloadRequestArgs>request.arguments;
this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq);
responseRequired = false;
break;
}
case CommandNames.Saveto: {
var savetoArgs = <protocol.SavetoRequestArgs>request.arguments;
this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
responseRequired = false;
break;
}
case CommandNames.Close: {
var closeArgs = <protocol.FileRequestArgs>request.arguments;
this.closeClientFile(closeArgs.file);
responseRequired = false;
break;
}
case CommandNames.Navto: {
var navtoArgs = <protocol.NavtoRequestArgs>request.arguments;
response = this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount);
break;
}
case CommandNames.Brace: {
var braceArguments = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file);
break;
}
case CommandNames.NavBar: {
var navBarArgs = <protocol.FileRequestArgs>request.arguments;
response = this.getNavigationBarItems(navBarArgs.file);
break;
}
case CommandNames.Occurrences: {
var { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getOccurrences(line, offset, fileName);
break;
}
case CommandNames.ProjectInfo: {
var { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments;
response = this.getProjectInfo(file, needFileNameList);
break;
}
default: {
this.projectService.log("Unrecognized JSON command: " + message);
this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command);
break;
}
}
var {response, responseRequired} = this.executeCommand(request);
if (this.logger.isVerbose()) {
var elapsed = this.hrtime(start);

View File

@ -480,6 +480,8 @@ namespace ts.formatting {
case SyntaxKind.CloseBraceToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenParenToken:
case SyntaxKind.CloseParenToken:
case SyntaxKind.ElseKeyword:
case SyntaxKind.WhileKeyword:
case SyntaxKind.AtToken:
@ -644,7 +646,7 @@ namespace ts.formatting {
// consume list start token
startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
let indentation =
computeIndentation(tokenInfo.token, startLine, Constants.Unknown, parent, parentDynamicIndentation, startLine);
computeIndentation(tokenInfo.token, startLine, Constants.Unknown, parent, parentDynamicIndentation, parentStartLine);
listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation.indentation, indentation.delta);
consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation);

View File

@ -4546,6 +4546,7 @@ namespace ts {
if (hasKind(node.parent, SyntaxKind.GetAccessor) || hasKind(node.parent, SyntaxKind.SetAccessor)) {
return getGetAndSetOccurrences(<AccessorDeclaration>node.parent);
}
break;
default:
if (isModifier(node.kind) && node.parent &&
(isDeclaration(node.parent) || node.parent.kind === SyntaxKind.VariableStatement)) {
@ -4681,12 +4682,13 @@ namespace ts {
// Make sure we only highlight the keyword when it makes sense to do so.
if (isAccessibilityModifier(modifier)) {
if (!(container.kind === SyntaxKind.ClassDeclaration ||
container.kind === SyntaxKind.ClassExpression ||
(declaration.kind === SyntaxKind.Parameter && hasKind(container, SyntaxKind.Constructor)))) {
return undefined;
}
}
else if (modifier === SyntaxKind.StaticKeyword) {
if (container.kind !== SyntaxKind.ClassDeclaration) {
if (!(container.kind === SyntaxKind.ClassDeclaration || container.kind === SyntaxKind.ClassExpression)) {
return undefined;
}
}
@ -4695,6 +4697,11 @@ namespace ts {
return undefined;
}
}
else if (modifier === SyntaxKind.AbstractKeyword) {
if (!(container.kind === SyntaxKind.ClassDeclaration || declaration.kind === SyntaxKind.ClassDeclaration)) {
return undefined;
}
}
else {
// unsupported modifier
return undefined;
@ -4707,19 +4714,26 @@ namespace ts {
switch (container.kind) {
case SyntaxKind.ModuleBlock:
case SyntaxKind.SourceFile:
nodes = (<Block>container).statements;
// Container is either a class declaration or the declaration is a classDeclaration
if (modifierFlag & NodeFlags.Abstract) {
nodes = (<Node[]>(<ClassDeclaration>declaration).members).concat(declaration);
}
else {
nodes = (<Block>container).statements;
}
break;
case SyntaxKind.Constructor:
nodes = (<Node[]>(<ConstructorDeclaration>container).parameters).concat(
(<ClassDeclaration>container.parent).members);
break;
case SyntaxKind.ClassDeclaration:
nodes = (<ClassDeclaration>container).members;
case SyntaxKind.ClassExpression:
nodes = (<ClassLikeDeclaration>container).members;
// If we're an accessibility modifier, we're in an instance member and should search
// the constructor's parameter list for instance members as well.
if (modifierFlag & NodeFlags.AccessibilityModifier) {
let constructor = forEach((<ClassDeclaration>container).members, member => {
let constructor = forEach((<ClassLikeDeclaration>container).members, member => {
return member.kind === SyntaxKind.Constructor && <ConstructorDeclaration>member;
});
@ -4727,6 +4741,9 @@ namespace ts {
nodes = nodes.concat(constructor.parameters);
}
}
else if (modifierFlag & NodeFlags.Abstract) {
nodes = nodes.concat(container);
}
break;
default:
Debug.fail("Invalid container kind.")
@ -4754,6 +4771,8 @@ namespace ts {
return NodeFlags.Export;
case SyntaxKind.DeclareKeyword:
return NodeFlags.Ambient;
case SyntaxKind.AbstractKeyword:
return NodeFlags.Abstract;
default:
Debug.fail();
}
@ -6574,7 +6593,7 @@ namespace ts {
}
}
return ClassificationType.text;
return ClassificationType.identifier;
}
}

View File

@ -0,0 +1,31 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractClinterfaceAssignability.ts(23,1): error TS2322: Type 'typeof A' is not assignable to type 'IConstructor'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractClinterfaceAssignability.ts (1 errors) ====
interface I {
x: number;
}
interface IConstructor {
new (): I;
y: number;
prototype: I;
}
var I: IConstructor;
abstract class A {
x: number;
static y: number;
}
var AA: typeof A;
AA = I;
var AAA: typeof I;
AAA = A;
~~~
!!! error TS2322: Type 'typeof A' is not assignable to type 'IConstructor'.
!!! error TS2322: Cannot assign an abstract constructor type to a non-abstract constructor type.

View File

@ -0,0 +1,36 @@
//// [classAbstractClinterfaceAssignability.ts]
interface I {
x: number;
}
interface IConstructor {
new (): I;
y: number;
prototype: I;
}
var I: IConstructor;
abstract class A {
x: number;
static y: number;
}
var AA: typeof A;
AA = I;
var AAA: typeof I;
AAA = A;
//// [classAbstractClinterfaceAssignability.js]
var I;
var A = (function () {
function A() {
}
return A;
})();
var AA;
AA = I;
var AAA;
AAA = A;

View File

@ -0,0 +1,30 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractConstructorAssignability.ts(8,5): error TS2322: Type 'typeof B' is not assignable to type 'typeof A'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractConstructorAssignability.ts(10,5): error TS2322: Type 'typeof B' is not assignable to type 'typeof C'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractConstructorAssignability.ts(13,1): error TS2511: Cannot create an instance of the abstract class 'B'.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractConstructorAssignability.ts (3 errors) ====
class A {}
abstract class B extends A {}
class C extends B {}
var AA : typeof A = B;
~~
!!! error TS2322: Type 'typeof B' is not assignable to type 'typeof A'.
!!! error TS2322: Cannot assign an abstract constructor type to a non-abstract constructor type.
var BB : typeof B = A;
var CC : typeof C = B;
~~
!!! error TS2322: Type 'typeof B' is not assignable to type 'typeof C'.
!!! error TS2322: Cannot assign an abstract constructor type to a non-abstract constructor type.
new AA;
new BB;
~~~~~~
!!! error TS2511: Cannot create an instance of the abstract class 'B'.
new CC;

View File

@ -0,0 +1,47 @@
//// [classAbstractConstructorAssignability.ts]
class A {}
abstract class B extends A {}
class C extends B {}
var AA : typeof A = B;
var BB : typeof B = A;
var CC : typeof C = B;
new AA;
new BB;
new CC;
//// [classAbstractConstructorAssignability.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
}
return A;
})();
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
})(A);
var C = (function (_super) {
__extends(C, _super);
function C() {
_super.apply(this, arguments);
}
return C;
})(B);
var AA = B;
var BB = A;
var CC = B;
new AA;
new BB;
new CC;

View File

@ -0,0 +1,22 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractExtends.ts(10,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'bar' from class 'B'.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractExtends.ts (1 errors) ====
class A {
foo() {}
}
abstract class B extends A {
abstract bar();
}
class C extends B { }
~
!!! error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'bar' from class 'B'.
abstract class D extends B {}
class E extends B {
bar() {}
}

View File

@ -0,0 +1,59 @@
//// [classAbstractExtends.ts]
class A {
foo() {}
}
abstract class B extends A {
abstract bar();
}
class C extends B { }
abstract class D extends B {}
class E extends B {
bar() {}
}
//// [classAbstractExtends.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
}
A.prototype.foo = function () { };
return A;
})();
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
})(A);
var C = (function (_super) {
__extends(C, _super);
function C() {
_super.apply(this, arguments);
}
return C;
})(B);
var D = (function (_super) {
__extends(D, _super);
function D() {
_super.apply(this, arguments);
}
return D;
})(B);
var E = (function (_super) {
__extends(E, _super);
function E() {
_super.apply(this, arguments);
}
E.prototype.bar = function () { };
return E;
})(B);

View File

@ -0,0 +1,28 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractFactoryFunction.ts(10,12): error TS2511: Cannot create an instance of the abstract class 'B'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractFactoryFunction.ts(14,6): error TS2345: Argument of type 'typeof B' is not assignable to parameter of type 'typeof A'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractFactoryFunction.ts (2 errors) ====
class A {}
abstract class B extends A {}
function NewA(Factory: typeof A) {
return new A;
}
function NewB(Factory: typeof B) {
return new B;
~~~~~
!!! error TS2511: Cannot create an instance of the abstract class 'B'.
}
NewA(A);
NewA(B);
~
!!! error TS2345: Argument of type 'typeof B' is not assignable to parameter of type 'typeof A'.
!!! error TS2345: Cannot assign an abstract constructor type to a non-abstract constructor type.
NewB(A);
NewB(B);

View File

@ -0,0 +1,47 @@
//// [classAbstractFactoryFunction.ts]
class A {}
abstract class B extends A {}
function NewA(Factory: typeof A) {
return new A;
}
function NewB(Factory: typeof B) {
return new B;
}
NewA(A);
NewA(B);
NewB(A);
NewB(B);
//// [classAbstractFactoryFunction.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
}
return A;
})();
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
})(A);
function NewA(Factory) {
return new A;
}
function NewB(Factory) {
return new B;
}
NewA(A);
NewA(B);
NewB(A);
NewB(B);

View File

@ -1,10 +1,14 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts(8,1): error TS2511: Cannot create an instance of the abstract class 'A'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts(9,1): error TS2511: Cannot create an instance of the abstract class 'A'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts(11,1): error TS2511: Cannot create an instance of the abstract class 'C'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts(12,1): error TS2511: Cannot create an instance of the abstract class 'A'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts(13,1): error TS2511: Cannot create an instance of the abstract class 'A'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts(15,1): error TS2511: Cannot create an instance of the abstract class 'C'.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts (3 errors) ====
//
// Calling new with (non)abstract classes.
//
abstract class A {}
class B extends A {}

View File

@ -1,5 +1,9 @@
//// [classAbstractInstantiations1.ts]
//
// Calling new with (non)abstract classes.
//
abstract class A {}
class B extends A {}
@ -21,6 +25,9 @@ c = new B;
//// [classAbstractInstantiations1.js]
//
// Calling new with (non)abstract classes.
//
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }

View File

@ -1,4 +1,6 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts(10,1): error TS2511: Cannot create an instance of the abstract class 'B'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts(13,5): error TS2322: Type 'typeof B' is not assignable to type 'typeof A'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts(17,5): error TS2511: Cannot create an instance of the abstract class 'B'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts(21,1): error TS2511: Cannot create an instance of the abstract class 'B'.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts(26,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'bar' from class 'B'.
@ -7,7 +9,7 @@ tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbst
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts(50,5): error TS1244: Abstract methods can only appear within an abstract class.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts (7 errors) ====
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts (8 errors) ====
class A {
// ...
}
@ -23,6 +25,9 @@ tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbst
var BB: typeof B = B;
var AA: typeof A = BB; // error, AA is not of abstract type.
~~
!!! error TS2322: Type 'typeof B' is not assignable to type 'typeof A'.
!!! error TS2322: Cannot assign an abstract constructor type to a non-abstract constructor type.
new AA;
function constructB(Factory : typeof B) {

View File

@ -0,0 +1,19 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractMethodInNonAbstractClass.ts(2,5): error TS1244: Abstract methods can only appear within an abstract class.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractMethodInNonAbstractClass.ts(6,5): error TS1244: Abstract methods can only appear within an abstract class.
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractMethodInNonAbstractClass.ts(6,5): error TS1245: Method 'foo' cannot have an implementation because it is marked abstract.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractMethodInNonAbstractClass.ts (3 errors) ====
class A {
abstract foo();
~~~~~~~~
!!! error TS1244: Abstract methods can only appear within an abstract class.
}
class B {
abstract foo() {}
~~~~~~~~
!!! error TS1244: Abstract methods can only appear within an abstract class.
~~~~~~~~~~~~~~~~~
!!! error TS1245: Method 'foo' cannot have an implementation because it is marked abstract.
}

View File

@ -0,0 +1,21 @@
//// [classAbstractMethodInNonAbstractClass.ts]
class A {
abstract foo();
}
class B {
abstract foo() {}
}
//// [classAbstractMethodInNonAbstractClass.js]
var A = (function () {
function A() {
}
return A;
})();
var B = (function () {
function B() {
}
B.prototype.foo = function () { };
return B;
})();

View File

@ -0,0 +1,29 @@
tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractOverrideWithAbstract.ts(19,7): error TS2515: Non-abstract class 'CC' does not implement inherited abstract member 'foo' from class 'BB'.
==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractOverrideWithAbstract.ts (1 errors) ====
class A {
foo() {}
}
abstract class B extends A {
abstract foo();
}
abstract class AA {
foo() {}
abstract bar();
}
abstract class BB extends AA {
abstract foo();
bar () {}
}
class CC extends BB {} // error
~~
!!! error TS2515: Non-abstract class 'CC' does not implement inherited abstract member 'foo' from class 'BB'.
class DD extends BB {
foo() {}
}

View File

@ -0,0 +1,73 @@
//// [classAbstractOverrideWithAbstract.ts]
class A {
foo() {}
}
abstract class B extends A {
abstract foo();
}
abstract class AA {
foo() {}
abstract bar();
}
abstract class BB extends AA {
abstract foo();
bar () {}
}
class CC extends BB {} // error
class DD extends BB {
foo() {}
}
//// [classAbstractOverrideWithAbstract.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
}
A.prototype.foo = function () { };
return A;
})();
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
})(A);
var AA = (function () {
function AA() {
}
AA.prototype.foo = function () { };
return AA;
})();
var BB = (function (_super) {
__extends(BB, _super);
function BB() {
_super.apply(this, arguments);
}
BB.prototype.bar = function () { };
return BB;
})(AA);
var CC = (function (_super) {
__extends(CC, _super);
function CC() {
_super.apply(this, arguments);
}
return CC;
})(BB); // error
var DD = (function (_super) {
__extends(DD, _super);
function DD() {
_super.apply(this, arguments);
}
DD.prototype.foo = function () { };
return DD;
})(BB);

View File

@ -1,16 +1,8 @@
tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts(32,4): error TS2345: Argument of type '[string, number, number]' is not assignable to parameter of type '[undefined, null, undefined]'.
Types of property '0' are incompatible.
Type 'string' is not assignable to type 'undefined'.
tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts(33,4): error TS2345: Argument of type '[[string], number, [[boolean, boolean]]]' is not assignable to parameter of type '[[undefined], undefined, [[undefined, undefined]]]'.
Types of property '0' are incompatible.
Type '[string]' is not assignable to type '[undefined]'.
Types of property '0' are incompatible.
Type 'string' is not assignable to type 'undefined'.
tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts(62,10): error TS2393: Duplicate function implementation.
tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts(63,10): error TS2393: Duplicate function implementation.
==== tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts (4 errors) ====
==== tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts (2 errors) ====
// A parameter declaration may specify either an identifier or a binding pattern.
// The identifiers specified in parameter declarations and binding patterns
// in a parameter list must be unique within that parameter list.
@ -43,17 +35,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.
b2("string", { x: 200, y: "string" });
b2("string", { x: 200, y: true });
b6(["string", 1, 2]); // Shouldn't be an error
~~~~~~~~~~~~~~~~
!!! error TS2345: Argument of type '[string, number, number]' is not assignable to parameter of type '[undefined, null, undefined]'.
!!! error TS2345: Types of property '0' are incompatible.
!!! error TS2345: Type 'string' is not assignable to type 'undefined'.
b7([["string"], 1, [[true, false]]]); // Shouldn't be an error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2345: Argument of type '[[string], number, [[boolean, boolean]]]' is not assignable to parameter of type '[[undefined], undefined, [[undefined, undefined]]]'.
!!! error TS2345: Types of property '0' are incompatible.
!!! error TS2345: Type '[string]' is not assignable to type '[undefined]'.
!!! error TS2345: Types of property '0' are incompatible.
!!! error TS2345: Type 'string' is not assignable to type 'undefined'.
// If the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section 5.1.3)

View File

@ -0,0 +1,12 @@
//// [typeArgumentInferenceApparentType1.ts]
function method<T>(iterable: Iterable<T>): T {
return;
}
var res: string = method("test");
//// [typeArgumentInferenceApparentType1.js]
function method(iterable) {
return;
}
var res = method("test");

View File

@ -0,0 +1,16 @@
=== tests/cases/compiler/typeArgumentInferenceApparentType1.ts ===
function method<T>(iterable: Iterable<T>): T {
>method : Symbol(method, Decl(typeArgumentInferenceApparentType1.ts, 0, 0))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType1.ts, 0, 16))
>iterable : Symbol(iterable, Decl(typeArgumentInferenceApparentType1.ts, 0, 19))
>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1681, 1))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType1.ts, 0, 16))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType1.ts, 0, 16))
return;
}
var res: string = method("test");
>res : Symbol(res, Decl(typeArgumentInferenceApparentType1.ts, 4, 3))
>method : Symbol(method, Decl(typeArgumentInferenceApparentType1.ts, 0, 0))

View File

@ -0,0 +1,18 @@
=== tests/cases/compiler/typeArgumentInferenceApparentType1.ts ===
function method<T>(iterable: Iterable<T>): T {
>method : <T>(iterable: Iterable<T>) => T
>T : T
>iterable : Iterable<T>
>Iterable : Iterable<T>
>T : T
>T : T
return;
}
var res: string = method("test");
>res : string
>method("test") : string
>method : <T>(iterable: Iterable<T>) => T
>"test" : string

View File

@ -0,0 +1,17 @@
//// [typeArgumentInferenceApparentType2.ts]
function method<T>(iterable: Iterable<T>): T {
function inner<U extends Iterable<T>>() {
var u: U;
var res: T = method(u);
}
return;
}
//// [typeArgumentInferenceApparentType2.js]
function method(iterable) {
function inner() {
var u;
var res = method(u);
}
return;
}

View File

@ -0,0 +1,27 @@
=== tests/cases/compiler/typeArgumentInferenceApparentType2.ts ===
function method<T>(iterable: Iterable<T>): T {
>method : Symbol(method, Decl(typeArgumentInferenceApparentType2.ts, 0, 0))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType2.ts, 0, 16))
>iterable : Symbol(iterable, Decl(typeArgumentInferenceApparentType2.ts, 0, 19))
>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1681, 1))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType2.ts, 0, 16))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType2.ts, 0, 16))
function inner<U extends Iterable<T>>() {
>inner : Symbol(inner, Decl(typeArgumentInferenceApparentType2.ts, 0, 46))
>U : Symbol(U, Decl(typeArgumentInferenceApparentType2.ts, 1, 19))
>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1681, 1))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType2.ts, 0, 16))
var u: U;
>u : Symbol(u, Decl(typeArgumentInferenceApparentType2.ts, 2, 11))
>U : Symbol(U, Decl(typeArgumentInferenceApparentType2.ts, 1, 19))
var res: T = method(u);
>res : Symbol(res, Decl(typeArgumentInferenceApparentType2.ts, 3, 11))
>T : Symbol(T, Decl(typeArgumentInferenceApparentType2.ts, 0, 16))
>method : Symbol(method, Decl(typeArgumentInferenceApparentType2.ts, 0, 0))
>u : Symbol(u, Decl(typeArgumentInferenceApparentType2.ts, 2, 11))
}
return;
}

View File

@ -0,0 +1,28 @@
=== tests/cases/compiler/typeArgumentInferenceApparentType2.ts ===
function method<T>(iterable: Iterable<T>): T {
>method : <T>(iterable: Iterable<T>) => T
>T : T
>iterable : Iterable<T>
>Iterable : Iterable<T>
>T : T
>T : T
function inner<U extends Iterable<T>>() {
>inner : <U extends Iterable<T>>() => void
>U : U
>Iterable : Iterable<T>
>T : T
var u: U;
>u : U
>U : U
var res: T = method(u);
>res : T
>T : T
>method(u) : T
>method : <T>(iterable: Iterable<T>) => T
>u : U
}
return;
}

View File

@ -0,0 +1,9 @@
//// [wideningTuples1.ts]
declare function foo<T extends [any]>(x: T): T;
var y = foo([undefined]);
y = [""];
//// [wideningTuples1.js]
var y = foo([undefined]);
y = [""];

View File

@ -0,0 +1,16 @@
=== tests/cases/conformance/types/tuple/wideningTuples1.ts ===
declare function foo<T extends [any]>(x: T): T;
>foo : Symbol(foo, Decl(wideningTuples1.ts, 0, 0))
>T : Symbol(T, Decl(wideningTuples1.ts, 0, 21))
>x : Symbol(x, Decl(wideningTuples1.ts, 0, 38))
>T : Symbol(T, Decl(wideningTuples1.ts, 0, 21))
>T : Symbol(T, Decl(wideningTuples1.ts, 0, 21))
var y = foo([undefined]);
>y : Symbol(y, Decl(wideningTuples1.ts, 2, 3))
>foo : Symbol(foo, Decl(wideningTuples1.ts, 0, 0))
>undefined : Symbol(undefined)
y = [""];
>y : Symbol(y, Decl(wideningTuples1.ts, 2, 3))

View File

@ -0,0 +1,21 @@
=== tests/cases/conformance/types/tuple/wideningTuples1.ts ===
declare function foo<T extends [any]>(x: T): T;
>foo : <T extends [any]>(x: T) => T
>T : T
>x : T
>T : T
>T : T
var y = foo([undefined]);
>y : [any]
>foo([undefined]) : [any]
>foo : <T extends [any]>(x: T) => T
>[undefined] : [undefined]
>undefined : undefined
y = [""];
>y = [""] : [string]
>y : [any]
>[""] : [string]
>"" : string

View File

@ -0,0 +1,13 @@
//// [wideningTuples2.ts]
var foo: () => [any] = function bar() {
let intermediate = bar();
intermediate = [""];
return [undefined];
};
//// [wideningTuples2.js]
var foo = function bar() {
var intermediate = bar();
intermediate = [""];
return [undefined];
};

View File

@ -0,0 +1,16 @@
=== tests/cases/conformance/types/tuple/wideningTuples2.ts ===
var foo: () => [any] = function bar() {
>foo : Symbol(foo, Decl(wideningTuples2.ts, 0, 3))
>bar : Symbol(bar, Decl(wideningTuples2.ts, 0, 22))
let intermediate = bar();
>intermediate : Symbol(intermediate, Decl(wideningTuples2.ts, 1, 7))
>bar : Symbol(bar, Decl(wideningTuples2.ts, 0, 22))
intermediate = [""];
>intermediate : Symbol(intermediate, Decl(wideningTuples2.ts, 1, 7))
return [undefined];
>undefined : Symbol(undefined)
};

View File

@ -0,0 +1,22 @@
=== tests/cases/conformance/types/tuple/wideningTuples2.ts ===
var foo: () => [any] = function bar() {
>foo : () => [any]
>function bar() { let intermediate = bar(); intermediate = [""]; return [undefined];} : () => [any]
>bar : () => [any]
let intermediate = bar();
>intermediate : [any]
>bar() : [any]
>bar : () => [any]
intermediate = [""];
>intermediate = [""] : [string]
>intermediate : [any]
>[""] : [string]
>"" : string
return [undefined];
>[undefined] : [undefined]
>undefined : undefined
};

View File

@ -0,0 +1,9 @@
tests/cases/conformance/types/tuple/wideningTuples3.ts(3,5): error TS7005: Variable 'b' implicitly has an '[any, any]' type.
==== tests/cases/conformance/types/tuple/wideningTuples3.ts (1 errors) ====
var a: [any];
var b = a = [undefined, null];
~
!!! error TS7005: Variable 'b' implicitly has an '[any, any]' type.

View File

@ -0,0 +1,8 @@
//// [wideningTuples3.ts]
var a: [any];
var b = a = [undefined, null];
//// [wideningTuples3.js]
var a;
var b = a = [undefined, null];

View File

@ -0,0 +1,10 @@
//// [wideningTuples4.ts]
var a: [any];
var b = a = [undefined, null];
b = ["", ""];
//// [wideningTuples4.js]
var a;
var b = a = [undefined, null];
b = ["", ""];

View File

@ -0,0 +1,12 @@
=== tests/cases/conformance/types/tuple/wideningTuples4.ts ===
var a: [any];
>a : Symbol(a, Decl(wideningTuples4.ts, 0, 3))
var b = a = [undefined, null];
>b : Symbol(b, Decl(wideningTuples4.ts, 2, 3))
>a : Symbol(a, Decl(wideningTuples4.ts, 0, 3))
>undefined : Symbol(undefined)
b = ["", ""];
>b : Symbol(b, Decl(wideningTuples4.ts, 2, 3))

View File

@ -0,0 +1,19 @@
=== tests/cases/conformance/types/tuple/wideningTuples4.ts ===
var a: [any];
>a : [any]
var b = a = [undefined, null];
>b : [any, any]
>a = [undefined, null] : [undefined, null]
>a : [any]
>[undefined, null] : [undefined, null]
>undefined : undefined
>null : null
b = ["", ""];
>b = ["", ""] : [string, string]
>b : [any, any]
>["", ""] : [string, string]
>"" : string
>"" : string

View File

@ -0,0 +1,10 @@
tests/cases/conformance/types/tuple/wideningTuples5.ts(1,6): error TS7005: Variable 'a' implicitly has an 'any' type.
tests/cases/conformance/types/tuple/wideningTuples5.ts(1,9): error TS7005: Variable 'b' implicitly has an 'any' type.
==== tests/cases/conformance/types/tuple/wideningTuples5.ts (2 errors) ====
var [a, b] = [undefined, null];
~
!!! error TS7005: Variable 'a' implicitly has an 'any' type.
~
!!! error TS7005: Variable 'b' implicitly has an 'any' type.

View File

@ -0,0 +1,5 @@
//// [wideningTuples5.ts]
var [a, b] = [undefined, null];
//// [wideningTuples5.js]
var _a = [undefined, null], a = _a[0], b = _a[1];

View File

@ -0,0 +1,9 @@
//// [wideningTuples6.ts]
var [a, b] = [undefined, null];
a = "";
b = "";
//// [wideningTuples6.js]
var _a = [undefined, null], a = _a[0], b = _a[1];
a = "";
b = "";

View File

@ -0,0 +1,12 @@
=== tests/cases/conformance/types/tuple/wideningTuples6.ts ===
var [a, b] = [undefined, null];
>a : Symbol(a, Decl(wideningTuples6.ts, 0, 5))
>b : Symbol(b, Decl(wideningTuples6.ts, 0, 7))
>undefined : Symbol(undefined)
a = "";
>a : Symbol(a, Decl(wideningTuples6.ts, 0, 5))
b = "";
>b : Symbol(b, Decl(wideningTuples6.ts, 0, 7))

View File

@ -0,0 +1,18 @@
=== tests/cases/conformance/types/tuple/wideningTuples6.ts ===
var [a, b] = [undefined, null];
>a : any
>b : any
>[undefined, null] : [undefined, null]
>undefined : undefined
>null : null
a = "";
>a = "" : string
>a : any
>"" : string
b = "";
>b = "" : string
>b : any
>"" : string

View File

@ -0,0 +1,10 @@
tests/cases/conformance/types/tuple/wideningTuples7.ts(1,20): error TS7010: 'bar', which lacks return-type annotation, implicitly has an '[any]' return type.
==== tests/cases/conformance/types/tuple/wideningTuples7.ts (1 errors) ====
var foo = function bar() {
~~~
!!! error TS7010: 'bar', which lacks return-type annotation, implicitly has an '[any]' return type.
let intermediate: [string];
return intermediate = [undefined];
};

View File

@ -0,0 +1,11 @@
//// [wideningTuples7.ts]
var foo = function bar() {
let intermediate: [string];
return intermediate = [undefined];
};
//// [wideningTuples7.js]
var foo = function bar() {
var intermediate;
return intermediate = [undefined];
};

View File

@ -0,0 +1,6 @@
//@target: ES6
function method<T>(iterable: Iterable<T>): T {
return;
}
var res: string = method("test");

View File

@ -0,0 +1,8 @@
//@target: ES6
function method<T>(iterable: Iterable<T>): T {
function inner<U extends Iterable<T>>() {
var u: U;
var res: T = method(u);
}
return;
}

View File

@ -0,0 +1,23 @@
interface I {
x: number;
}
interface IConstructor {
new (): I;
y: number;
prototype: I;
}
var I: IConstructor;
abstract class A {
x: number;
static y: number;
}
var AA: typeof A;
AA = I;
var AAA: typeof I;
AAA = A;

View File

@ -0,0 +1,14 @@
class A {}
abstract class B extends A {}
class C extends B {}
var AA : typeof A = B;
var BB : typeof B = A;
var CC : typeof C = B;
new AA;
new BB;
new CC;

View File

@ -0,0 +1,16 @@
class A {
foo() {}
}
abstract class B extends A {
abstract bar();
}
class C extends B { }
abstract class D extends B {}
class E extends B {
bar() {}
}

View File

@ -0,0 +1,17 @@
class A {}
abstract class B extends A {}
function NewA(Factory: typeof A) {
return new A;
}
function NewB(Factory: typeof B) {
return new B;
}
NewA(A);
NewA(B);
NewB(A);
NewB(B);

View File

@ -1,4 +1,8 @@
//
// Calling new with (non)abstract classes.
//
abstract class A {}
class B extends A {}

View File

@ -0,0 +1,7 @@
class A {
abstract foo();
}
class B {
abstract foo() {}
}

View File

@ -0,0 +1,23 @@
class A {
foo() {}
}
abstract class B extends A {
abstract foo();
}
abstract class AA {
foo() {}
abstract bar();
}
abstract class BB extends AA {
abstract foo();
bar () {}
}
class CC extends BB {} // error
class DD extends BB {
foo() {}
}

View File

@ -0,0 +1,5 @@
//@noImplicitAny: true
declare function foo<T extends [any]>(x: T): T;
var y = foo([undefined]);
y = [""];

View File

@ -0,0 +1,6 @@
//@noImplicitAny: true
var foo: () => [any] = function bar() {
let intermediate = bar();
intermediate = [""];
return [undefined];
};

View File

@ -0,0 +1,4 @@
//@noImplicitAny: true
var a: [any];
var b = a = [undefined, null];

View File

@ -0,0 +1,4 @@
var a: [any];
var b = a = [undefined, null];
b = ["", ""];

View File

@ -0,0 +1,2 @@
//@noImplicitAny: true
var [a, b] = [undefined, null];

View File

@ -0,0 +1,3 @@
var [a, b] = [undefined, null];
a = "";
b = "";

View File

@ -0,0 +1,5 @@
//@noImplicitAny: true
var foo = function bar() {
let intermediate: [string];
return intermediate = [undefined];
};

View File

@ -18,4 +18,4 @@ goTo.marker("1");
edit.insert("\r\n");
goTo.marker("0");
// Won't-fixed: Smart indent during chained function calls
verify.indentationIs(8);
verify.indentationIs(4);

View File

@ -46,7 +46,7 @@ verify.currentFileContentIs(
" C;\n" +
" class C {\n" +
" constructor(b\n" +
" ) {\n" +
" ) {\n" +
" }\n" +
" foo(a\n" +
" : string) {\n" +
@ -54,7 +54,7 @@ verify.currentFileContentIs(
" || true;\n" +
" }\n" +
" get bar(\n" +
" ) {\n" +
" ) {\n" +
" return 1;\n" +
" }\n" +
" }\n" +

View File

@ -0,0 +1,24 @@
/// <reference path='fourslash.ts' />
////[|abstract|] class Animal {
//// [|abstract|] prop1; // Does not compile
//// [|abstract|] abstract();
//// [|abstract|] walk(): void;
//// [|abstract|] makeSound(): void;
////}
////// Abstract class below should not get highlighted
////abstract class Foo {
//// abstract foo(): void;
//// abstract bar(): void;
////}
const ranges = test.ranges();
for (let r of ranges) {
goTo.position(r.start);
verify.occurrencesAtPositionCount(ranges.length);
for (let range of ranges) {
verify.occurrencesAtPositionContains(range, false);
}
}

View File

@ -0,0 +1,29 @@
/// <reference path='fourslash.ts' />
////// Not valid TS (abstract methods can only appear in abstract classes)
////class Animal {
//// [|abstract|] walk(): void;
//// [|abstract|] makeSound(): void;
////}
////// abstract cannot appear here, won't get highlighted
////let c = /*1*/abstract class Foo {
//// /*2*/abstract foo(): void;
//// abstract bar(): void;
////}
const ranges = test.ranges();
for (let r of ranges) {
goTo.position(r.start);
verify.occurrencesAtPositionCount(ranges.length);
for (let range of ranges) {
verify.occurrencesAtPositionContains(range, false);
}
}
goTo.marker("1");
verify.occurrencesAtPositionCount(0);
goTo.marker("2");
verify.occurrencesAtPositionCount(2);

View File

@ -0,0 +1,23 @@
/// <reference path='fourslash.ts' />
////let A = class Foo {
//// [|constructor|]();
//// [|constructor|](x: number);
//// [|constructor|](y: string);
//// [|constructor|](a?: any) {
//// }
////}
////
////let B = class D {
//// constructor(x: number) {
//// }
////}
const ranges = test.ranges();
for (let r of ranges) {
goTo.position(r.start);
for (let range of ranges) {
verify.occurrencesAtPositionContains(range, false);
}
}

View File

@ -0,0 +1,27 @@
/// <reference path='fourslash.ts' />
////let A = class Foo {
//// [|private|] foo;
//// [|private|] private;
//// constructor([|private|] y: string, public x: string) {
//// }
//// [|private|] method() { }
//// public method2() { }
//// [|private|] static static() { }
////}
////
////let B = class D {
//// constructor(private x: number) {
//// }
//// private test() {}
//// public test2() {}
////}
const ranges = test.ranges();
for (let r of ranges) {
goTo.position(r.start);
for (let range of ranges) {
verify.occurrencesAtPositionContains(range, false);
}
}

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