Merge pull request #6 from Microsoft/master

Sync
This commit is contained in:
Zev Spitz
2015-04-13 14:14:09 +03:00
820 changed files with 50329 additions and 59268 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ Your pull request should:
* Tests should include reasonable permutations of the target fix/change
* Include baseline changes with your change
* All changed code must have 100% code coverage
* Follow the code conventions descriped in [Coding guidlines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidlines)
* Follow the code conventions descriped in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines)
* To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration
## Running the Tests
+22 -64
View File
@@ -105,23 +105,6 @@ var serverSources = [
return path.join(serverDirectory, f);
});
var definitionsRoots = [
"compiler/types.d.ts",
"compiler/scanner.d.ts",
"compiler/parser.d.ts",
"compiler/checker.d.ts",
"compiler/program.d.ts",
"services/services.d.ts",
];
var internalDefinitionsRoots = [
"compiler/core.d.ts",
"compiler/sys.d.ts",
"compiler/utilities.d.ts",
"compiler/commandLineParser.d.ts",
"services/utilities.d.ts",
];
var harnessSources = [
"harness.ts",
"sourceMapRecorder.ts",
@@ -143,7 +126,8 @@ var harnessSources = [
"services/colorization.ts",
"services/documentRegistry.ts",
"services/preProcessFile.ts",
"services/patternMatcher.ts"
"services/patternMatcher.ts",
"versionCache.ts"
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
@@ -222,15 +206,17 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOu
var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory;
var options = "--module commonjs -noImplicitAny";
if (!keepComments) {
options += " -removeComments";
// Keep comments when specifically requested
// or when in debug mode.
if (!(keepComments || useDebugMode)) {
options += " --removeComments";
}
if (generateDeclarations) {
options += " --declaration";
}
if (useDebugMode || preserveConstEnums) {
if (preserveConstEnums || useDebugMode) {
options += " --preserveConstEnums";
}
@@ -350,60 +336,32 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js");
var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts");
var nodePackageFile = path.join(builtLocalDirectory, "typescript.js");
var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts");
compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ false,
/*generateDeclarations*/ true,
/*outDir*/ undefined,
/*preserveConstEnums*/ true,
/*keepComments*/ false,
/*keepComments*/ true,
/*noResolve*/ false,
/*stripInternal*/ false,
/*stripInternal*/ true,
/*callback*/ function () {
jake.cpR(servicesFile, nodePackageFile, {silent: true});
prependFile(copyright, standaloneDefinitionsFile);
// Create the node definition file by replacing 'ts' module with '"typescript"' as a module.
jake.cpR(standaloneDefinitionsFile, nodeDefinitionsFile, {silent: true});
var definitionFileContents = fs.readFileSync(nodeDefinitionsFile).toString();
definitionFileContents = definitionFileContents.replace(/declare module ts/g, 'declare module "typescript"');
fs.writeFileSync(nodeDefinitionsFile, definitionFileContents);
});
var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts");
var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts");
var internalNodeDefinitionsFile = path.join(builtLocalDirectory, "typescript_internal.d.ts");
var internalStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices_internal.d.ts");
var tempDirPath = path.join(builtLocalDirectory, "temptempdir");
compileFile(nodeDefinitionsFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ undefined,
/*useBuiltCompiler*/ true,
/*noOutFile*/ true,
/*generateDeclarations*/ true,
/*outDir*/ tempDirPath,
/*preserveConstEnums*/ true,
/*keepComments*/ true,
/*noResolve*/ true,
/*stripInternal*/ true,
/*callback*/ function () {
function makeDefinitionFiles(definitionsRoots, standaloneDefinitionsFile, nodeDefinitionsFile) {
// Create the standalone definition file
concatenateFiles(standaloneDefinitionsFile, definitionsRoots.map(function (f) {
return path.join(tempDirPath, f);
}));
prependFile(copyright, standaloneDefinitionsFile);
// Create the node definition file by replacing 'ts' module with '"typescript"' as a module.
jake.cpR(standaloneDefinitionsFile, nodeDefinitionsFile, {silent: true});
var definitionFileContents = fs.readFileSync(nodeDefinitionsFile).toString();
definitionFileContents = definitionFileContents.replace(/declare module ts/g, 'declare module "typescript"');
fs.writeFileSync(nodeDefinitionsFile, definitionFileContents);
}
// Create the public definition files
makeDefinitionFiles(definitionsRoots, standaloneDefinitionsFile, nodeDefinitionsFile);
// Create the internal definition files
makeDefinitionFiles(internalDefinitionsRoots, internalStandaloneDefinitionsFile, internalNodeDefinitionsFile);
// Delete the temp dir
jake.rmRf(tempDirPath, {silent: true});
});
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
@@ -465,7 +423,7 @@ task("generate-spec", [specMd])
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, internalNodeDefinitionsFile, internalStandaloneDefinitionsFile].concat(libraryTargets);
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
});
+2 -2
View File
@@ -838,7 +838,7 @@ interface RegExp {
*/
test(string: string): boolean;
/** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */
/** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */
source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
@@ -1183,4 +1183,4 @@ interface TypedPropertyDescriptor<T> {
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
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: Function, propertyKey: string | symbol, parameterIndex: number) => void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
+39 -32
View File
@@ -838,7 +838,7 @@ interface RegExp {
*/
test(string: string): boolean;
/** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */
/** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */
source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
@@ -1183,7 +1183,7 @@ interface TypedPropertyDescriptor<T> {
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
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: Function, propertyKey: string | symbol, parameterIndex: number) => void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PropertyKey = string | number | symbol;
interface Symbol {
@@ -1236,26 +1236,21 @@ interface SymbolConstructor {
*/
isConcatSpreadable: symbol;
/**
* A Boolean value that if true indicates that an object may be used as a regular expression.
*/
isRegExp: symbol;
/**
* A method that returns the default iterator for an object.Called by the semantics of the
* for-of statement.
* for-of statement.
*/
iterator: symbol;
/**
* A method that converts an object to a corresponding primitive value.Called by the ToPrimitive
* abstract operation.
* abstract operation.
*/
toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built- in method Object.prototype.toString.
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
toStringTag: symbol;
@@ -1297,7 +1292,7 @@ interface ObjectConstructor {
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
@@ -1784,8 +1779,6 @@ interface Math {
}
interface RegExp {
[Symbol.isRegExp]: boolean;
/**
* Matches a string with a regular expression, and returns an array containing the results of
* that search.
@@ -1817,6 +1810,20 @@ interface RegExp {
*/
split(string: string, limit?: number): string[];
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
@@ -4699,27 +4706,27 @@ interface ProxyHandler<T> {
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handeler: ProxyHandler<T>): T
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
declare var Reflect: {
apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
construct(target: Function, argumentsList: ArrayLike<any>): any;
defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
deleteProperty(target: any, propertyKey: PropertyKey): boolean;
enumerate(target: any): IterableIterator<any>;
get(target: any, propertyKey: PropertyKey, receiver?: any): any;
getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
getPrototypeOf(target: any): any;
has(target: any, propertyKey: string): boolean;
has(target: any, propertyKey: symbol): boolean;
isExtensible(target: any): boolean;
ownKeys(target: any): Array<PropertyKey>;
preventExtensions(target: any): boolean;
set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
setPrototypeOf(target: any, proto: any): boolean;
};
declare module Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function enumerate(target: any): IterableIterator<any>;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
/**
* Represents the completion of an asynchronous operation
+160 -10
View File
@@ -838,7 +838,7 @@ interface RegExp {
*/
test(string: string): boolean;
/** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */
/** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */
source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
@@ -1183,7 +1183,7 @@ interface TypedPropertyDescriptor<T> {
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
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: Function, propertyKey: string | symbol, parameterIndex: number) => void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
/////////////////////////////
/// IE10 ECMAScript Extensions
@@ -14223,7 +14223,11 @@ declare function importScripts(...urls: string[]): void;
/// Windows Script Host APIS
/////////////////////////////
declare var ActiveXObject: { new (s: string): any; };
interface ActiveXObject {
new (s: string): any;
}
declare var ActiveXObject: ActiveXObject;
interface ITextWriter {
Write(s: string): void;
@@ -14231,11 +14235,157 @@ interface ITextWriter {
Close(): void;
}
declare var WScript: {
Echo(s: any): void;
StdErr: ITextWriter;
StdOut: ITextWriter;
Arguments: { length: number; Item(n: number): string; };
ScriptFullName: string;
Quit(exitCode?: number): number;
interface TextStreamBase {
/**
* The column number of the current character position in an input stream.
*/
Column: number;
/**
* The current line number in an input stream.
*/
Line: number;
/**
* Closes a text stream.
* It is not necessary to close standard streams; they close automatically when the process ends. If you close a standard stream, be aware that any other pointers to that standard stream become invalid.
*/
Close(): void;
}
interface TextStreamWriter extends TextStreamBase {
/**
* Sends a string to an output stream.
*/
Write(s: string): void;
/**
* Sends a specified number of blank lines (newline characters) to an output stream.
*/
WriteBlankLines(intLines: number): void;
/**
* Sends a string followed by a newline character to an output stream.
*/
WriteLine(s: string): void;
}
interface TextStreamReader extends TextStreamBase {
/**
* Returns a specified number of characters from an input stream, beginning at the current pointer position.
* Does not return until the ENTER key is pressed.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
Read(characters: number): string;
/**
* Returns all characters from an input stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadAll(): string;
/**
* Returns an entire line from an input stream.
* Although this method extracts the newline character, it does not add it to the returned string.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadLine(): string;
/**
* Skips a specified number of characters when reading from an input text stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
* @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)
*/
Skip(characters: number): void;
/**
* Skips the next line when reading from an input text stream.
* Can only be used on a stream in reading mode, not writing or appending mode.
*/
SkipLine(): void;
/**
* Indicates whether the stream pointer position is at the end of a line.
*/
AtEndOfLine: boolean;
/**
* Indicates whether the stream pointer position is at the end of a stream.
*/
AtEndOfStream: boolean;
}
declare var WScript: {
/**
* Outputs text to either a message box (under WScript.exe) or the command console window followed by a newline (under CScript.ext).
*/
Echo(s: any): void;
/**
* Exposes the write-only error output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdErr: TextStreamWriter;
/**
* Exposes the write-only output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdOut: TextStreamWriter;
Arguments: { length: number; Item(n: number): string; };
/**
* The full path of the currently running script.
*/
ScriptFullName: string;
/**
* Forces the script to stop immediately, with an optional exit code.
*/
Quit(exitCode?: number): number;
/**
* The Windows Script Host build version number.
*/
BuildVersion: number;
/**
* Fully qualified path of the host executable.
*/
FullName: string;
/**
* Gets/sets the script mode - interactive(true) or batch(false).
*/
Interactive: boolean;
/**
* The name of the host executable (WScript.exe or CScript.exe).
*/
Name: string;
/**
* Path of the directory containing the host executable.
*/
Path: string;
/**
* The filename of the currently running script.
*/
ScriptName: string;
/**
* Exposes the read-only input stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdIn: TextStreamReader;
/**
* Windows Script Host version
*/
Version: string;
/**
* Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.
*/
ConnectObject(objEventSource: any, strPrefix: string): void;
/**
* Creates a COM object.
* @param strProgiID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
CreateObject(strProgID: string, strPrefix?: string): any;
/**
* Disconnects a COM object from its event sources.
*/
DisconnectObject(obj: any): void;
/**
* Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.
* @param strPathname Fully qualified path to the file containing the object persisted to disk. For objects in memory, pass a zero-length string.
* @param strProgID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;
/**
* Suspends script execution for a specified length of time, then continues execution.
* @param intTime Interval (in milliseconds) to suspend script execution.
*/
Sleep(intTime: number): void;
};
+197 -40
View File
@@ -838,7 +838,7 @@ interface RegExp {
*/
test(string: string): boolean;
/** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */
/** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */
source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
@@ -1183,7 +1183,7 @@ interface TypedPropertyDescriptor<T> {
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
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: Function, propertyKey: string | symbol, parameterIndex: number) => void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PropertyKey = string | number | symbol;
interface Symbol {
@@ -1236,26 +1236,21 @@ interface SymbolConstructor {
*/
isConcatSpreadable: symbol;
/**
* A Boolean value that if true indicates that an object may be used as a regular expression.
*/
isRegExp: symbol;
/**
* A method that returns the default iterator for an object.Called by the semantics of the
* for-of statement.
* for-of statement.
*/
iterator: symbol;
/**
* A method that converts an object to a corresponding primitive value.Called by the ToPrimitive
* abstract operation.
* abstract operation.
*/
toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built- in method Object.prototype.toString.
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
toStringTag: symbol;
@@ -1297,7 +1292,7 @@ interface ObjectConstructor {
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
@@ -1784,8 +1779,6 @@ interface Math {
}
interface RegExp {
[Symbol.isRegExp]: boolean;
/**
* Matches a string with a regular expression, and returns an array containing the results of
* that search.
@@ -1817,6 +1810,20 @@ interface RegExp {
*/
split(string: string, limit?: number): string[];
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
@@ -4699,27 +4706,27 @@ interface ProxyHandler<T> {
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handeler: ProxyHandler<T>): T
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
declare var Reflect: {
apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
construct(target: Function, argumentsList: ArrayLike<any>): any;
defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
deleteProperty(target: any, propertyKey: PropertyKey): boolean;
enumerate(target: any): IterableIterator<any>;
get(target: any, propertyKey: PropertyKey, receiver?: any): any;
getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
getPrototypeOf(target: any): any;
has(target: any, propertyKey: string): boolean;
has(target: any, propertyKey: symbol): boolean;
isExtensible(target: any): boolean;
ownKeys(target: any): Array<PropertyKey>;
preventExtensions(target: any): boolean;
set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
setPrototypeOf(target: any, proto: any): boolean;
};
declare module Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function enumerate(target: any): IterableIterator<any>;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
/**
* Represents the completion of an asynchronous operation
@@ -17205,7 +17212,11 @@ declare function importScripts(...urls: string[]): void;
/// Windows Script Host APIS
/////////////////////////////
declare var ActiveXObject: { new (s: string): any; };
interface ActiveXObject {
new (s: string): any;
}
declare var ActiveXObject: ActiveXObject;
interface ITextWriter {
Write(s: string): void;
@@ -17213,11 +17224,157 @@ interface ITextWriter {
Close(): void;
}
declare var WScript: {
Echo(s: any): void;
StdErr: ITextWriter;
StdOut: ITextWriter;
Arguments: { length: number; Item(n: number): string; };
ScriptFullName: string;
Quit(exitCode?: number): number;
interface TextStreamBase {
/**
* The column number of the current character position in an input stream.
*/
Column: number;
/**
* The current line number in an input stream.
*/
Line: number;
/**
* Closes a text stream.
* It is not necessary to close standard streams; they close automatically when the process ends. If you close a standard stream, be aware that any other pointers to that standard stream become invalid.
*/
Close(): void;
}
interface TextStreamWriter extends TextStreamBase {
/**
* Sends a string to an output stream.
*/
Write(s: string): void;
/**
* Sends a specified number of blank lines (newline characters) to an output stream.
*/
WriteBlankLines(intLines: number): void;
/**
* Sends a string followed by a newline character to an output stream.
*/
WriteLine(s: string): void;
}
interface TextStreamReader extends TextStreamBase {
/**
* Returns a specified number of characters from an input stream, beginning at the current pointer position.
* Does not return until the ENTER key is pressed.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
Read(characters: number): string;
/**
* Returns all characters from an input stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadAll(): string;
/**
* Returns an entire line from an input stream.
* Although this method extracts the newline character, it does not add it to the returned string.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadLine(): string;
/**
* Skips a specified number of characters when reading from an input text stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
* @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)
*/
Skip(characters: number): void;
/**
* Skips the next line when reading from an input text stream.
* Can only be used on a stream in reading mode, not writing or appending mode.
*/
SkipLine(): void;
/**
* Indicates whether the stream pointer position is at the end of a line.
*/
AtEndOfLine: boolean;
/**
* Indicates whether the stream pointer position is at the end of a stream.
*/
AtEndOfStream: boolean;
}
declare var WScript: {
/**
* Outputs text to either a message box (under WScript.exe) or the command console window followed by a newline (under CScript.ext).
*/
Echo(s: any): void;
/**
* Exposes the write-only error output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdErr: TextStreamWriter;
/**
* Exposes the write-only output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdOut: TextStreamWriter;
Arguments: { length: number; Item(n: number): string; };
/**
* The full path of the currently running script.
*/
ScriptFullName: string;
/**
* Forces the script to stop immediately, with an optional exit code.
*/
Quit(exitCode?: number): number;
/**
* The Windows Script Host build version number.
*/
BuildVersion: number;
/**
* Fully qualified path of the host executable.
*/
FullName: string;
/**
* Gets/sets the script mode - interactive(true) or batch(false).
*/
Interactive: boolean;
/**
* The name of the host executable (WScript.exe or CScript.exe).
*/
Name: string;
/**
* Path of the directory containing the host executable.
*/
Path: string;
/**
* The filename of the currently running script.
*/
ScriptName: string;
/**
* Exposes the read-only input stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdIn: TextStreamReader;
/**
* Windows Script Host version
*/
Version: string;
/**
* Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.
*/
ConnectObject(objEventSource: any, strPrefix: string): void;
/**
* Creates a COM object.
* @param strProgiID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
CreateObject(strProgID: string, strPrefix?: string): any;
/**
* Disconnects a COM object from its event sources.
*/
DisconnectObject(obj: any): void;
/**
* Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.
* @param strPathname Fully qualified path to the file containing the object persisted to disk. For objects in memory, pass a zero-length string.
* @param strProgID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;
/**
* Suspends script execution for a specified length of time, then continues execution.
* @param intTime Interval (in milliseconds) to suspend script execution.
*/
Sleep(intTime: number): void;
};
+158 -8
View File
@@ -20,7 +20,11 @@ and limitations under the License.
/// Windows Script Host APIS
/////////////////////////////
declare var ActiveXObject: { new (s: string): any; };
interface ActiveXObject {
new (s: string): any;
}
declare var ActiveXObject: ActiveXObject;
interface ITextWriter {
Write(s: string): void;
@@ -28,11 +32,157 @@ interface ITextWriter {
Close(): void;
}
declare var WScript: {
Echo(s: any): void;
StdErr: ITextWriter;
StdOut: ITextWriter;
Arguments: { length: number; Item(n: number): string; };
ScriptFullName: string;
Quit(exitCode?: number): number;
interface TextStreamBase {
/**
* The column number of the current character position in an input stream.
*/
Column: number;
/**
* The current line number in an input stream.
*/
Line: number;
/**
* Closes a text stream.
* It is not necessary to close standard streams; they close automatically when the process ends. If you close a standard stream, be aware that any other pointers to that standard stream become invalid.
*/
Close(): void;
}
interface TextStreamWriter extends TextStreamBase {
/**
* Sends a string to an output stream.
*/
Write(s: string): void;
/**
* Sends a specified number of blank lines (newline characters) to an output stream.
*/
WriteBlankLines(intLines: number): void;
/**
* Sends a string followed by a newline character to an output stream.
*/
WriteLine(s: string): void;
}
interface TextStreamReader extends TextStreamBase {
/**
* Returns a specified number of characters from an input stream, beginning at the current pointer position.
* Does not return until the ENTER key is pressed.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
Read(characters: number): string;
/**
* Returns all characters from an input stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadAll(): string;
/**
* Returns an entire line from an input stream.
* Although this method extracts the newline character, it does not add it to the returned string.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadLine(): string;
/**
* Skips a specified number of characters when reading from an input text stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
* @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)
*/
Skip(characters: number): void;
/**
* Skips the next line when reading from an input text stream.
* Can only be used on a stream in reading mode, not writing or appending mode.
*/
SkipLine(): void;
/**
* Indicates whether the stream pointer position is at the end of a line.
*/
AtEndOfLine: boolean;
/**
* Indicates whether the stream pointer position is at the end of a stream.
*/
AtEndOfStream: boolean;
}
declare var WScript: {
/**
* Outputs text to either a message box (under WScript.exe) or the command console window followed by a newline (under CScript.ext).
*/
Echo(s: any): void;
/**
* Exposes the write-only error output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdErr: TextStreamWriter;
/**
* Exposes the write-only output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdOut: TextStreamWriter;
Arguments: { length: number; Item(n: number): string; };
/**
* The full path of the currently running script.
*/
ScriptFullName: string;
/**
* Forces the script to stop immediately, with an optional exit code.
*/
Quit(exitCode?: number): number;
/**
* The Windows Script Host build version number.
*/
BuildVersion: number;
/**
* Fully qualified path of the host executable.
*/
FullName: string;
/**
* Gets/sets the script mode - interactive(true) or batch(false).
*/
Interactive: boolean;
/**
* The name of the host executable (WScript.exe or CScript.exe).
*/
Name: string;
/**
* Path of the directory containing the host executable.
*/
Path: string;
/**
* The filename of the currently running script.
*/
ScriptName: string;
/**
* Exposes the read-only input stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdIn: TextStreamReader;
/**
* Windows Script Host version
*/
Version: string;
/**
* Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.
*/
ConnectObject(objEventSource: any, strPrefix: string): void;
/**
* Creates a COM object.
* @param strProgiID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
CreateObject(strProgID: string, strPrefix?: string): any;
/**
* Disconnects a COM object from its event sources.
*/
DisconnectObject(obj: any): void;
/**
* Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.
* @param strPathname Fully qualified path to the file containing the object persisted to disk. For objects in memory, pass a zero-length string.
* @param strProgID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;
/**
* Suspends script execution for a specified length of time, then continues execution.
* @param intTime Interval (in milliseconds) to suspend script execution.
*/
Sleep(intTime: number): void;
};
+3391 -2514
View File
File diff suppressed because it is too large Load Diff
+3805 -2801
View File
File diff suppressed because it is too large Load Diff
+188 -407
View File
@@ -196,59 +196,62 @@ declare module "typescript" {
TemplateExpression = 171,
YieldExpression = 172,
SpreadElementExpression = 173,
OmittedExpression = 174,
TemplateSpan = 175,
Block = 176,
VariableStatement = 177,
EmptyStatement = 178,
ExpressionStatement = 179,
IfStatement = 180,
DoStatement = 181,
WhileStatement = 182,
ForStatement = 183,
ForInStatement = 184,
ForOfStatement = 185,
ContinueStatement = 186,
BreakStatement = 187,
ReturnStatement = 188,
WithStatement = 189,
SwitchStatement = 190,
LabeledStatement = 191,
ThrowStatement = 192,
TryStatement = 193,
DebuggerStatement = 194,
VariableDeclaration = 195,
VariableDeclarationList = 196,
FunctionDeclaration = 197,
ClassDeclaration = 198,
InterfaceDeclaration = 199,
TypeAliasDeclaration = 200,
EnumDeclaration = 201,
ModuleDeclaration = 202,
ModuleBlock = 203,
CaseBlock = 204,
ImportEqualsDeclaration = 205,
ImportDeclaration = 206,
ImportClause = 207,
NamespaceImport = 208,
NamedImports = 209,
ImportSpecifier = 210,
ExportAssignment = 211,
ExportDeclaration = 212,
NamedExports = 213,
ExportSpecifier = 214,
MissingDeclaration = 215,
ExternalModuleReference = 216,
CaseClause = 217,
DefaultClause = 218,
HeritageClause = 219,
CatchClause = 220,
PropertyAssignment = 221,
ShorthandPropertyAssignment = 222,
EnumMember = 223,
SourceFile = 224,
SyntaxList = 225,
Count = 226,
ClassExpression = 174,
OmittedExpression = 175,
TemplateSpan = 176,
HeritageClauseElement = 177,
SemicolonClassElement = 178,
Block = 179,
VariableStatement = 180,
EmptyStatement = 181,
ExpressionStatement = 182,
IfStatement = 183,
DoStatement = 184,
WhileStatement = 185,
ForStatement = 186,
ForInStatement = 187,
ForOfStatement = 188,
ContinueStatement = 189,
BreakStatement = 190,
ReturnStatement = 191,
WithStatement = 192,
SwitchStatement = 193,
LabeledStatement = 194,
ThrowStatement = 195,
TryStatement = 196,
DebuggerStatement = 197,
VariableDeclaration = 198,
VariableDeclarationList = 199,
FunctionDeclaration = 200,
ClassDeclaration = 201,
InterfaceDeclaration = 202,
TypeAliasDeclaration = 203,
EnumDeclaration = 204,
ModuleDeclaration = 205,
ModuleBlock = 206,
CaseBlock = 207,
ImportEqualsDeclaration = 208,
ImportDeclaration = 209,
ImportClause = 210,
NamespaceImport = 211,
NamedImports = 212,
ImportSpecifier = 213,
ExportAssignment = 214,
ExportDeclaration = 215,
NamedExports = 216,
ExportSpecifier = 217,
MissingDeclaration = 218,
ExternalModuleReference = 219,
CaseClause = 220,
DefaultClause = 221,
HeritageClause = 222,
CatchClause = 223,
PropertyAssignment = 224,
ShorthandPropertyAssignment = 225,
EnumMember = 226,
SourceFile = 227,
SyntaxList = 228,
Count = 229,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
@@ -292,34 +295,12 @@ declare module "typescript" {
AccessibilityModifier = 112,
BlockScoped = 12288,
}
const enum ParserContextFlags {
StrictMode = 1,
DisallowIn = 2,
Yield = 4,
GeneratorParameter = 8,
Decorator = 16,
ThisNodeHasError = 32,
ParserGeneratedFlags = 63,
ThisNodeOrAnySubNodesHasError = 64,
HasAggregatedChildData = 128,
}
const enum RelationComparisonResult {
Succeeded = 1,
Failed = 2,
FailedAndReported = 3,
}
interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
parserContextFlags?: ParserContextFlags;
decorators?: NodeArray<Decorator>;
modifiers?: ModifiersArray;
id?: number;
parent?: Node;
symbol?: Symbol;
locals?: SymbolTable;
nextContainer?: Node;
localSymbol?: Symbol;
}
interface NodeArray<T> extends Array<T>, TextRange {
hasTrailingComma?: boolean;
@@ -432,6 +413,9 @@ declare module "typescript" {
interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement {
body?: Block;
}
interface SemicolonClassElement extends ClassElement {
_semicolonClassElementBrand: any;
}
interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
_accessorDeclarationBrand: any;
body: Block;
@@ -570,6 +554,10 @@ declare module "typescript" {
typeArguments?: NodeArray<TypeNode>;
arguments: NodeArray<Expression>;
}
interface HeritageClauseElement extends Node {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
}
interface NewExpression extends CallExpression, PrimaryExpression {
}
interface TaggedTemplateExpression extends MemberExpression {
@@ -664,12 +652,16 @@ declare module "typescript" {
interface ModuleElement extends Node {
_moduleElementBrand: any;
}
interface ClassDeclaration extends Declaration, ModuleElement {
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
members: NodeArray<ClassElement>;
}
interface ClassDeclaration extends ClassLikeDeclaration, Statement {
}
interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
}
interface ClassElement extends Declaration {
_classElementBrand: any;
}
@@ -681,7 +673,7 @@ declare module "typescript" {
}
interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray<TypeReferenceNode>;
types?: NodeArray<HeritageClauseElement>;
}
interface TypeAliasDeclaration extends Declaration, ModuleElement {
name: Identifier;
@@ -709,7 +701,7 @@ declare module "typescript" {
interface ExternalModuleReference extends Node {
expression?: Expression;
}
interface ImportDeclaration extends Statement, ModuleElement {
interface ImportDeclaration extends ModuleElement {
importClause?: ImportClause;
moduleSpecifier: Expression;
}
@@ -737,14 +729,14 @@ declare module "typescript" {
type ExportSpecifier = ImportOrExportSpecifier;
interface ExportAssignment extends Declaration, ModuleElement {
isExportEquals?: boolean;
expression?: Expression;
type?: TypeNode;
expression: Expression;
}
interface FileReference extends TextRange {
fileName: string;
}
interface CommentRange extends TextRange {
hasTrailingNewLine?: boolean;
kind: SyntaxKind;
}
interface SourceFile extends Declaration {
statements: NodeArray<ModuleElement>;
@@ -758,9 +750,7 @@ declare module "typescript" {
amdModuleName: string;
referencedFiles: FileReference[];
hasNoDefaultLib: boolean;
externalModuleIndicator: Node;
languageVersion: ScriptTarget;
identifiers: Map<string>;
}
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
@@ -771,6 +761,9 @@ declare module "typescript" {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
interface Program extends ScriptReferenceHost {
/**
* Get a list of files in the program
*/
getSourceFiles(): SourceFile[];
/**
* Emits the JavaScript and declaration files. If targetSourceFile is not specified, then
@@ -787,15 +780,23 @@ declare module "typescript" {
getGlobalDiagnostics(): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
getTypeChecker(): TypeChecker;
getCommonSourceDirectory(): string;
}
interface SourceMapSpan {
/** Line number in the .js file. */
emittedLine: number;
/** Column number in the .js file. */
emittedColumn: number;
/** Line number in the .ts file. */
sourceLine: number;
/** Column number in the .ts file. */
sourceColumn: number;
/** Optional name (index into names array) associated with this span. */
nameIndex?: number;
/** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
interface SourceMapData {
@@ -809,6 +810,7 @@ declare module "typescript" {
sourceMapMappings: string;
sourceMapDecodedMappings: SourceMapSpan[];
}
/** Return code used by getEmitOutput function to indicate status of the function */
enum ExitStatus {
Success = 0,
DiagnosticsPresent_OutputsSkipped = 1,
@@ -817,7 +819,6 @@ declare module "typescript" {
interface EmitResult {
emitSkipped: boolean;
diagnostics: Diagnostic[];
sourceMaps: SourceMapData[];
}
interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
@@ -851,7 +852,7 @@ declare module "typescript" {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfExternalModule(node: ImportDeclaration): Symbol[];
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -894,40 +895,6 @@ declare module "typescript" {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
}
const enum SymbolAccessibility {
Accessible = 0,
NotAccessible = 1,
CannotBeNamed = 2,
}
type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
interface SymbolVisibilityResult {
accessibility: SymbolAccessibility;
aliasesToMakeVisible?: AnyImportSyntax[];
errorSymbolName?: string;
errorNode?: Node;
}
interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string;
}
interface EmitResolver {
hasGlobalName(name: string): boolean;
getExpressionNameSubstitution(node: Identifier, getGeneratedNameForNode: (node: Node) => string): string;
isValueAliasDeclaration(node: Node): boolean;
isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean;
isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean;
getNodeCheckFlags(node: Node): NodeCheckFlags;
isDeclarationVisible(node: Declaration): boolean;
collectLinkedAliases(node: Identifier): Node[];
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
resolvesToSomeValue(location: Node, name: string): boolean;
getBlockScopedVariableId(node: Identifier): number;
}
const enum SymbolFlags {
FunctionScopedVariable = 1,
BlockScopedVariable = 2,
@@ -997,57 +964,14 @@ declare module "typescript" {
interface Symbol {
flags: SymbolFlags;
name: string;
id?: number;
mergeId?: number;
declarations?: Declaration[];
parent?: Symbol;
members?: SymbolTable;
exports?: SymbolTable;
exportSymbol?: Symbol;
valueDeclaration?: Declaration;
constEnumOnlyModule?: boolean;
}
interface SymbolLinks {
target?: Symbol;
type?: Type;
declaredType?: Type;
mapper?: TypeMapper;
referenced?: boolean;
unionType?: UnionType;
resolvedExports?: SymbolTable;
exportsChecked?: boolean;
}
interface TransientSymbol extends Symbol, SymbolLinks {
}
interface SymbolTable {
[index: string]: Symbol;
}
const enum NodeCheckFlags {
TypeChecked = 1,
LexicalThis = 2,
CaptureThis = 4,
EmitExtends = 8,
SuperInstance = 16,
SuperStatic = 32,
ContextChecked = 64,
EnumValuesComputed = 128,
BlockScopedBindingInLoop = 256,
EmitDecorate = 512,
}
interface NodeLinks {
resolvedType?: Type;
resolvedSignature?: Signature;
resolvedSymbol?: Symbol;
flags?: NodeCheckFlags;
enumMemberValue?: number;
isIllegalTypeReferenceInConstraint?: boolean;
isVisible?: boolean;
generatedName?: string;
generatedNames?: Map<string>;
assignmentChecks?: Map<boolean>;
hasReportedStatementInAmbientContext?: boolean;
importOnRightSide?: Symbol;
}
const enum TypeFlags {
Any = 1,
String = 2,
@@ -1065,26 +989,16 @@ declare module "typescript" {
Tuple = 8192,
Union = 16384,
Anonymous = 32768,
FromSignature = 65536,
ObjectLiteral = 131072,
ContainsUndefinedOrNull = 262144,
ContainsObjectLiteral = 524288,
ESSymbol = 1048576,
Intrinsic = 1048703,
Primitive = 1049086,
StringLike = 258,
NumberLike = 132,
ObjectType = 48128,
RequiresWidening = 786432,
}
interface Type {
flags: TypeFlags;
id: number;
symbol?: Symbol;
}
interface IntrinsicType extends Type {
intrinsicName: string;
}
interface StringLiteralType extends Type {
text: string;
}
@@ -1104,7 +1018,6 @@ declare module "typescript" {
typeArguments: Type[];
}
interface GenericType extends InterfaceType, TypeReference {
instantiations: Map<TypeReference>;
}
interface TupleType extends ObjectType {
elementTypes: Type[];
@@ -1112,20 +1025,9 @@ declare module "typescript" {
}
interface UnionType extends Type {
types: Type[];
resolvedProperties: SymbolTable;
}
interface ResolvedType extends ObjectType, UnionType {
members: SymbolTable;
properties: Symbol[];
callSignatures: Signature[];
constructSignatures: Signature[];
stringIndexType: Type;
numberIndexType: Type;
}
interface TypeParameter extends Type {
constraint: Type;
target?: TypeParameter;
mapper?: TypeMapper;
}
const enum SignatureKind {
Call = 0,
@@ -1135,28 +1037,22 @@ declare module "typescript" {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
resolvedReturnType: Type;
minArgumentCount: number;
hasRestParameter: boolean;
hasStringLiterals: boolean;
target?: Signature;
mapper?: TypeMapper;
unionSignatures?: Signature[];
erasedSignatureCache?: Signature;
isolatedSignatureType?: ObjectType;
}
const enum IndexKind {
String = 0,
Number = 1,
}
interface TypeMapper {
(t: Type): Type;
}
interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
code: number;
}
/**
* A linked list of formatted diagnostic messages to be used as part of a multiline message.
* It is built from the bottom up, leaving the head to be the "main" diagnostic.
* While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
* the difference is that messages are all preformatted in DMC.
*/
interface DiagnosticMessageChain {
messageText: string;
category: DiagnosticCategory;
@@ -1179,7 +1075,6 @@ declare module "typescript" {
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
codepage?: number;
declaration?: boolean;
diagnostics?: boolean;
emitBOM?: boolean;
@@ -1193,7 +1088,6 @@ declare module "typescript" {
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noLib?: boolean;
noLibCheck?: boolean;
noResolve?: boolean;
out?: string;
outDir?: string;
@@ -1206,6 +1100,8 @@ declare module "typescript" {
target?: ScriptTarget;
version?: boolean;
watch?: boolean;
separateCompilation?: boolean;
emitDecoratorMetadata?: boolean;
[option: string]: string | number | boolean;
}
const enum ModuleKind {
@@ -1228,142 +1124,6 @@ declare module "typescript" {
fileNames: string[];
errors: Diagnostic[];
}
interface CommandLineOption {
name: string;
type: string | Map<number>;
isFilePath?: boolean;
shortName?: string;
description?: DiagnosticMessage;
paramType?: DiagnosticMessage;
error?: DiagnosticMessage;
experimental?: boolean;
}
const enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 127,
lineFeed = 10,
carriageReturn = 13,
lineSeparator = 8232,
paragraphSeparator = 8233,
nextLine = 133,
space = 32,
nonBreakingSpace = 160,
enQuad = 8192,
emQuad = 8193,
enSpace = 8194,
emSpace = 8195,
threePerEmSpace = 8196,
fourPerEmSpace = 8197,
sixPerEmSpace = 8198,
figureSpace = 8199,
punctuationSpace = 8200,
thinSpace = 8201,
hairSpace = 8202,
zeroWidthSpace = 8203,
narrowNoBreakSpace = 8239,
ideographicSpace = 12288,
mathematicalSpace = 8287,
ogham = 5760,
_ = 95,
$ = 36,
_0 = 48,
_1 = 49,
_2 = 50,
_3 = 51,
_4 = 52,
_5 = 53,
_6 = 54,
_7 = 55,
_8 = 56,
_9 = 57,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
ampersand = 38,
asterisk = 42,
at = 64,
backslash = 92,
backtick = 96,
bar = 124,
caret = 94,
closeBrace = 125,
closeBracket = 93,
closeParen = 41,
colon = 58,
comma = 44,
dot = 46,
doubleQuote = 34,
equals = 61,
exclamation = 33,
greaterThan = 62,
hash = 35,
lessThan = 60,
minus = 45,
openBrace = 123,
openBracket = 91,
openParen = 40,
percent = 37,
plus = 43,
question = 63,
semicolon = 59,
singleQuote = 39,
slash = 47,
tilde = 126,
backspace = 8,
formFeed = 12,
byteOrderMark = 65279,
tab = 9,
verticalTab = 11,
}
interface CancellationToken {
isCancellationRequested(): boolean;
}
@@ -1387,49 +1147,39 @@ declare module "typescript" {
}
}
declare module "typescript" {
interface ErrorCallback {
(message: DiagnosticMessage, length: number): void;
interface System {
args: string[];
newLine: string;
useCaseSensitiveFileNames: boolean;
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: (path: string) => void): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(path: string): void;
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string): string[];
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
interface Scanner {
getStartPos(): number;
getToken(): SyntaxKind;
getTextPos(): number;
getTokenPos(): number;
getTokenText(): string;
getTokenValue(): string;
hasExtendedUnicodeEscape(): boolean;
hasPrecedingLineBreak(): boolean;
isIdentifier(): boolean;
isReservedWord(): boolean;
isUnterminated(): boolean;
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scan(): SyntaxKind;
setText(text: string): void;
setTextPos(textPos: number): void;
lookAhead<T>(callback: () => T): T;
tryScan<T>(callback: () => T): T;
interface FileWatcher {
close(): void;
}
var sys: System;
}
declare module "typescript" {
function tokenToString(t: SyntaxKind): string;
function computeLineStarts(text: string): number[];
function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number;
function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number): number;
function getLineStarts(sourceFile: SourceFile): number[];
function computeLineAndCharacterOfPosition(lineStarts: number[], position: number): {
line: number;
character: number;
};
function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter;
function isWhiteSpace(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function isOctalDigit(ch: number): boolean;
function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[];
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback): Scanner;
}
declare module "typescript" {
function getNodeConstructor(kind: SyntaxKind): new () => Node;
@@ -1442,18 +1192,30 @@ declare module "typescript" {
function isLeftHandSideExpression(expr: Expression): boolean;
function isAssignmentOperator(token: SyntaxKind): boolean;
}
declare module "typescript" {
function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker;
}
declare module "typescript" {
/** The version of the TypeScript compiler release */
let version: string;
const version: string;
function findConfigFile(searchPath: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
declare module "typescript" {
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readConfigFile(fileName: string): any;
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseConfigFile(json: any, basePath?: string): ParsedCommandLine;
}
declare module "typescript" {
/** The version of the language service API */
let servicesVersion: string;
@@ -1562,8 +1324,10 @@ declare module "typescript" {
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[];
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[];
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[];
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
findReferences(fileName: string, position: number): ReferencedSymbol[];
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[];
/** @deprecated */
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
getOutliningSpans(fileName: string): OutliningSpan[];
@@ -1614,6 +1378,20 @@ declare module "typescript" {
fileName: string;
isWriteAccess: boolean;
}
interface DocumentHighlights {
fileName: string;
highlightSpans: HighlightSpan[];
}
module HighlightSpanKind {
const none: string;
const definition: string;
const reference: string;
const writtenReference: string;
}
interface HighlightSpan {
textSpan: TextSpan;
kind: string;
}
interface NavigateToItem {
name: string;
kind: string;
@@ -1738,6 +1516,7 @@ declare module "typescript" {
name: string;
kind: string;
kindModifiers: string;
sortText: string;
}
interface CompletionEntryDetails {
name: string;
@@ -1878,43 +1657,44 @@ declare module "typescript" {
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
}
class ScriptElementKind {
static unknown: string;
static keyword: string;
static scriptElement: string;
static moduleElement: string;
static classElement: string;
static interfaceElement: string;
static typeElement: string;
static enumElement: string;
static variableElement: string;
static localVariableElement: string;
static functionElement: string;
static localFunctionElement: string;
static memberFunctionElement: string;
static memberGetAccessorElement: string;
static memberSetAccessorElement: string;
static memberVariableElement: string;
static constructorImplementationElement: string;
static callSignatureElement: string;
static indexSignatureElement: string;
static constructSignatureElement: string;
static parameterElement: string;
static typeParameterElement: string;
static primitiveType: string;
static label: string;
static alias: string;
static constElement: string;
static letElement: string;
module ScriptElementKind {
const unknown: string;
const warning: string;
const keyword: string;
const scriptElement: string;
const moduleElement: string;
const classElement: string;
const interfaceElement: string;
const typeElement: string;
const enumElement: string;
const variableElement: string;
const localVariableElement: string;
const functionElement: string;
const localFunctionElement: string;
const memberFunctionElement: string;
const memberGetAccessorElement: string;
const memberSetAccessorElement: string;
const memberVariableElement: string;
const constructorImplementationElement: string;
const callSignatureElement: string;
const indexSignatureElement: string;
const constructSignatureElement: string;
const parameterElement: string;
const typeParameterElement: string;
const primitiveType: string;
const label: string;
const alias: string;
const constElement: string;
const letElement: string;
}
class ScriptElementKindModifier {
static none: string;
static publicMemberModifier: string;
static privateMemberModifier: string;
static protectedMemberModifier: string;
static exportedModifier: string;
static ambientModifier: string;
static staticModifier: string;
module ScriptElementKindModifier {
const none: string;
const publicMemberModifier: string;
const privateMemberModifier: string;
const protectedMemberModifier: string;
const exportedModifier: string;
const ambientModifier: string;
const staticModifier: string;
}
class ClassificationTypeNames {
static comment: string;
@@ -1947,6 +1727,7 @@ declare module "typescript" {
isCancellationRequested(): boolean;
throwIfCancellationRequested(): void;
}
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
+13543 -7153
View File
File diff suppressed because one or more lines are too long
+188 -407
View File
@@ -196,59 +196,62 @@ declare module ts {
TemplateExpression = 171,
YieldExpression = 172,
SpreadElementExpression = 173,
OmittedExpression = 174,
TemplateSpan = 175,
Block = 176,
VariableStatement = 177,
EmptyStatement = 178,
ExpressionStatement = 179,
IfStatement = 180,
DoStatement = 181,
WhileStatement = 182,
ForStatement = 183,
ForInStatement = 184,
ForOfStatement = 185,
ContinueStatement = 186,
BreakStatement = 187,
ReturnStatement = 188,
WithStatement = 189,
SwitchStatement = 190,
LabeledStatement = 191,
ThrowStatement = 192,
TryStatement = 193,
DebuggerStatement = 194,
VariableDeclaration = 195,
VariableDeclarationList = 196,
FunctionDeclaration = 197,
ClassDeclaration = 198,
InterfaceDeclaration = 199,
TypeAliasDeclaration = 200,
EnumDeclaration = 201,
ModuleDeclaration = 202,
ModuleBlock = 203,
CaseBlock = 204,
ImportEqualsDeclaration = 205,
ImportDeclaration = 206,
ImportClause = 207,
NamespaceImport = 208,
NamedImports = 209,
ImportSpecifier = 210,
ExportAssignment = 211,
ExportDeclaration = 212,
NamedExports = 213,
ExportSpecifier = 214,
MissingDeclaration = 215,
ExternalModuleReference = 216,
CaseClause = 217,
DefaultClause = 218,
HeritageClause = 219,
CatchClause = 220,
PropertyAssignment = 221,
ShorthandPropertyAssignment = 222,
EnumMember = 223,
SourceFile = 224,
SyntaxList = 225,
Count = 226,
ClassExpression = 174,
OmittedExpression = 175,
TemplateSpan = 176,
HeritageClauseElement = 177,
SemicolonClassElement = 178,
Block = 179,
VariableStatement = 180,
EmptyStatement = 181,
ExpressionStatement = 182,
IfStatement = 183,
DoStatement = 184,
WhileStatement = 185,
ForStatement = 186,
ForInStatement = 187,
ForOfStatement = 188,
ContinueStatement = 189,
BreakStatement = 190,
ReturnStatement = 191,
WithStatement = 192,
SwitchStatement = 193,
LabeledStatement = 194,
ThrowStatement = 195,
TryStatement = 196,
DebuggerStatement = 197,
VariableDeclaration = 198,
VariableDeclarationList = 199,
FunctionDeclaration = 200,
ClassDeclaration = 201,
InterfaceDeclaration = 202,
TypeAliasDeclaration = 203,
EnumDeclaration = 204,
ModuleDeclaration = 205,
ModuleBlock = 206,
CaseBlock = 207,
ImportEqualsDeclaration = 208,
ImportDeclaration = 209,
ImportClause = 210,
NamespaceImport = 211,
NamedImports = 212,
ImportSpecifier = 213,
ExportAssignment = 214,
ExportDeclaration = 215,
NamedExports = 216,
ExportSpecifier = 217,
MissingDeclaration = 218,
ExternalModuleReference = 219,
CaseClause = 220,
DefaultClause = 221,
HeritageClause = 222,
CatchClause = 223,
PropertyAssignment = 224,
ShorthandPropertyAssignment = 225,
EnumMember = 226,
SourceFile = 227,
SyntaxList = 228,
Count = 229,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
@@ -292,34 +295,12 @@ declare module ts {
AccessibilityModifier = 112,
BlockScoped = 12288,
}
const enum ParserContextFlags {
StrictMode = 1,
DisallowIn = 2,
Yield = 4,
GeneratorParameter = 8,
Decorator = 16,
ThisNodeHasError = 32,
ParserGeneratedFlags = 63,
ThisNodeOrAnySubNodesHasError = 64,
HasAggregatedChildData = 128,
}
const enum RelationComparisonResult {
Succeeded = 1,
Failed = 2,
FailedAndReported = 3,
}
interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
parserContextFlags?: ParserContextFlags;
decorators?: NodeArray<Decorator>;
modifiers?: ModifiersArray;
id?: number;
parent?: Node;
symbol?: Symbol;
locals?: SymbolTable;
nextContainer?: Node;
localSymbol?: Symbol;
}
interface NodeArray<T> extends Array<T>, TextRange {
hasTrailingComma?: boolean;
@@ -432,6 +413,9 @@ declare module ts {
interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement {
body?: Block;
}
interface SemicolonClassElement extends ClassElement {
_semicolonClassElementBrand: any;
}
interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
_accessorDeclarationBrand: any;
body: Block;
@@ -570,6 +554,10 @@ declare module ts {
typeArguments?: NodeArray<TypeNode>;
arguments: NodeArray<Expression>;
}
interface HeritageClauseElement extends Node {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
}
interface NewExpression extends CallExpression, PrimaryExpression {
}
interface TaggedTemplateExpression extends MemberExpression {
@@ -664,12 +652,16 @@ declare module ts {
interface ModuleElement extends Node {
_moduleElementBrand: any;
}
interface ClassDeclaration extends Declaration, ModuleElement {
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
members: NodeArray<ClassElement>;
}
interface ClassDeclaration extends ClassLikeDeclaration, Statement {
}
interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
}
interface ClassElement extends Declaration {
_classElementBrand: any;
}
@@ -681,7 +673,7 @@ declare module ts {
}
interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray<TypeReferenceNode>;
types?: NodeArray<HeritageClauseElement>;
}
interface TypeAliasDeclaration extends Declaration, ModuleElement {
name: Identifier;
@@ -709,7 +701,7 @@ declare module ts {
interface ExternalModuleReference extends Node {
expression?: Expression;
}
interface ImportDeclaration extends Statement, ModuleElement {
interface ImportDeclaration extends ModuleElement {
importClause?: ImportClause;
moduleSpecifier: Expression;
}
@@ -737,14 +729,14 @@ declare module ts {
type ExportSpecifier = ImportOrExportSpecifier;
interface ExportAssignment extends Declaration, ModuleElement {
isExportEquals?: boolean;
expression?: Expression;
type?: TypeNode;
expression: Expression;
}
interface FileReference extends TextRange {
fileName: string;
}
interface CommentRange extends TextRange {
hasTrailingNewLine?: boolean;
kind: SyntaxKind;
}
interface SourceFile extends Declaration {
statements: NodeArray<ModuleElement>;
@@ -758,9 +750,7 @@ declare module ts {
amdModuleName: string;
referencedFiles: FileReference[];
hasNoDefaultLib: boolean;
externalModuleIndicator: Node;
languageVersion: ScriptTarget;
identifiers: Map<string>;
}
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
@@ -771,6 +761,9 @@ declare module ts {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
interface Program extends ScriptReferenceHost {
/**
* Get a list of files in the program
*/
getSourceFiles(): SourceFile[];
/**
* Emits the JavaScript and declaration files. If targetSourceFile is not specified, then
@@ -787,15 +780,23 @@ declare module ts {
getGlobalDiagnostics(): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
getTypeChecker(): TypeChecker;
getCommonSourceDirectory(): string;
}
interface SourceMapSpan {
/** Line number in the .js file. */
emittedLine: number;
/** Column number in the .js file. */
emittedColumn: number;
/** Line number in the .ts file. */
sourceLine: number;
/** Column number in the .ts file. */
sourceColumn: number;
/** Optional name (index into names array) associated with this span. */
nameIndex?: number;
/** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
interface SourceMapData {
@@ -809,6 +810,7 @@ declare module ts {
sourceMapMappings: string;
sourceMapDecodedMappings: SourceMapSpan[];
}
/** Return code used by getEmitOutput function to indicate status of the function */
enum ExitStatus {
Success = 0,
DiagnosticsPresent_OutputsSkipped = 1,
@@ -817,7 +819,6 @@ declare module ts {
interface EmitResult {
emitSkipped: boolean;
diagnostics: Diagnostic[];
sourceMaps: SourceMapData[];
}
interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
@@ -851,7 +852,7 @@ declare module ts {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfExternalModule(node: ImportDeclaration): Symbol[];
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -894,40 +895,6 @@ declare module ts {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
}
const enum SymbolAccessibility {
Accessible = 0,
NotAccessible = 1,
CannotBeNamed = 2,
}
type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
interface SymbolVisibilityResult {
accessibility: SymbolAccessibility;
aliasesToMakeVisible?: AnyImportSyntax[];
errorSymbolName?: string;
errorNode?: Node;
}
interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string;
}
interface EmitResolver {
hasGlobalName(name: string): boolean;
getExpressionNameSubstitution(node: Identifier, getGeneratedNameForNode: (node: Node) => string): string;
isValueAliasDeclaration(node: Node): boolean;
isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean;
isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean;
getNodeCheckFlags(node: Node): NodeCheckFlags;
isDeclarationVisible(node: Declaration): boolean;
collectLinkedAliases(node: Identifier): Node[];
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
resolvesToSomeValue(location: Node, name: string): boolean;
getBlockScopedVariableId(node: Identifier): number;
}
const enum SymbolFlags {
FunctionScopedVariable = 1,
BlockScopedVariable = 2,
@@ -997,57 +964,14 @@ declare module ts {
interface Symbol {
flags: SymbolFlags;
name: string;
id?: number;
mergeId?: number;
declarations?: Declaration[];
parent?: Symbol;
members?: SymbolTable;
exports?: SymbolTable;
exportSymbol?: Symbol;
valueDeclaration?: Declaration;
constEnumOnlyModule?: boolean;
}
interface SymbolLinks {
target?: Symbol;
type?: Type;
declaredType?: Type;
mapper?: TypeMapper;
referenced?: boolean;
unionType?: UnionType;
resolvedExports?: SymbolTable;
exportsChecked?: boolean;
}
interface TransientSymbol extends Symbol, SymbolLinks {
}
interface SymbolTable {
[index: string]: Symbol;
}
const enum NodeCheckFlags {
TypeChecked = 1,
LexicalThis = 2,
CaptureThis = 4,
EmitExtends = 8,
SuperInstance = 16,
SuperStatic = 32,
ContextChecked = 64,
EnumValuesComputed = 128,
BlockScopedBindingInLoop = 256,
EmitDecorate = 512,
}
interface NodeLinks {
resolvedType?: Type;
resolvedSignature?: Signature;
resolvedSymbol?: Symbol;
flags?: NodeCheckFlags;
enumMemberValue?: number;
isIllegalTypeReferenceInConstraint?: boolean;
isVisible?: boolean;
generatedName?: string;
generatedNames?: Map<string>;
assignmentChecks?: Map<boolean>;
hasReportedStatementInAmbientContext?: boolean;
importOnRightSide?: Symbol;
}
const enum TypeFlags {
Any = 1,
String = 2,
@@ -1065,26 +989,16 @@ declare module ts {
Tuple = 8192,
Union = 16384,
Anonymous = 32768,
FromSignature = 65536,
ObjectLiteral = 131072,
ContainsUndefinedOrNull = 262144,
ContainsObjectLiteral = 524288,
ESSymbol = 1048576,
Intrinsic = 1048703,
Primitive = 1049086,
StringLike = 258,
NumberLike = 132,
ObjectType = 48128,
RequiresWidening = 786432,
}
interface Type {
flags: TypeFlags;
id: number;
symbol?: Symbol;
}
interface IntrinsicType extends Type {
intrinsicName: string;
}
interface StringLiteralType extends Type {
text: string;
}
@@ -1104,7 +1018,6 @@ declare module ts {
typeArguments: Type[];
}
interface GenericType extends InterfaceType, TypeReference {
instantiations: Map<TypeReference>;
}
interface TupleType extends ObjectType {
elementTypes: Type[];
@@ -1112,20 +1025,9 @@ declare module ts {
}
interface UnionType extends Type {
types: Type[];
resolvedProperties: SymbolTable;
}
interface ResolvedType extends ObjectType, UnionType {
members: SymbolTable;
properties: Symbol[];
callSignatures: Signature[];
constructSignatures: Signature[];
stringIndexType: Type;
numberIndexType: Type;
}
interface TypeParameter extends Type {
constraint: Type;
target?: TypeParameter;
mapper?: TypeMapper;
}
const enum SignatureKind {
Call = 0,
@@ -1135,28 +1037,22 @@ declare module ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
resolvedReturnType: Type;
minArgumentCount: number;
hasRestParameter: boolean;
hasStringLiterals: boolean;
target?: Signature;
mapper?: TypeMapper;
unionSignatures?: Signature[];
erasedSignatureCache?: Signature;
isolatedSignatureType?: ObjectType;
}
const enum IndexKind {
String = 0,
Number = 1,
}
interface TypeMapper {
(t: Type): Type;
}
interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
code: number;
}
/**
* A linked list of formatted diagnostic messages to be used as part of a multiline message.
* It is built from the bottom up, leaving the head to be the "main" diagnostic.
* While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
* the difference is that messages are all preformatted in DMC.
*/
interface DiagnosticMessageChain {
messageText: string;
category: DiagnosticCategory;
@@ -1179,7 +1075,6 @@ declare module ts {
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
codepage?: number;
declaration?: boolean;
diagnostics?: boolean;
emitBOM?: boolean;
@@ -1193,7 +1088,6 @@ declare module ts {
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noLib?: boolean;
noLibCheck?: boolean;
noResolve?: boolean;
out?: string;
outDir?: string;
@@ -1206,6 +1100,8 @@ declare module ts {
target?: ScriptTarget;
version?: boolean;
watch?: boolean;
separateCompilation?: boolean;
emitDecoratorMetadata?: boolean;
[option: string]: string | number | boolean;
}
const enum ModuleKind {
@@ -1228,142 +1124,6 @@ declare module ts {
fileNames: string[];
errors: Diagnostic[];
}
interface CommandLineOption {
name: string;
type: string | Map<number>;
isFilePath?: boolean;
shortName?: string;
description?: DiagnosticMessage;
paramType?: DiagnosticMessage;
error?: DiagnosticMessage;
experimental?: boolean;
}
const enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 127,
lineFeed = 10,
carriageReturn = 13,
lineSeparator = 8232,
paragraphSeparator = 8233,
nextLine = 133,
space = 32,
nonBreakingSpace = 160,
enQuad = 8192,
emQuad = 8193,
enSpace = 8194,
emSpace = 8195,
threePerEmSpace = 8196,
fourPerEmSpace = 8197,
sixPerEmSpace = 8198,
figureSpace = 8199,
punctuationSpace = 8200,
thinSpace = 8201,
hairSpace = 8202,
zeroWidthSpace = 8203,
narrowNoBreakSpace = 8239,
ideographicSpace = 12288,
mathematicalSpace = 8287,
ogham = 5760,
_ = 95,
$ = 36,
_0 = 48,
_1 = 49,
_2 = 50,
_3 = 51,
_4 = 52,
_5 = 53,
_6 = 54,
_7 = 55,
_8 = 56,
_9 = 57,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
ampersand = 38,
asterisk = 42,
at = 64,
backslash = 92,
backtick = 96,
bar = 124,
caret = 94,
closeBrace = 125,
closeBracket = 93,
closeParen = 41,
colon = 58,
comma = 44,
dot = 46,
doubleQuote = 34,
equals = 61,
exclamation = 33,
greaterThan = 62,
hash = 35,
lessThan = 60,
minus = 45,
openBrace = 123,
openBracket = 91,
openParen = 40,
percent = 37,
plus = 43,
question = 63,
semicolon = 59,
singleQuote = 39,
slash = 47,
tilde = 126,
backspace = 8,
formFeed = 12,
byteOrderMark = 65279,
tab = 9,
verticalTab = 11,
}
interface CancellationToken {
isCancellationRequested(): boolean;
}
@@ -1387,49 +1147,39 @@ declare module ts {
}
}
declare module ts {
interface ErrorCallback {
(message: DiagnosticMessage, length: number): void;
interface System {
args: string[];
newLine: string;
useCaseSensitiveFileNames: boolean;
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: (path: string) => void): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(path: string): void;
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string): string[];
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
interface Scanner {
getStartPos(): number;
getToken(): SyntaxKind;
getTextPos(): number;
getTokenPos(): number;
getTokenText(): string;
getTokenValue(): string;
hasExtendedUnicodeEscape(): boolean;
hasPrecedingLineBreak(): boolean;
isIdentifier(): boolean;
isReservedWord(): boolean;
isUnterminated(): boolean;
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scan(): SyntaxKind;
setText(text: string): void;
setTextPos(textPos: number): void;
lookAhead<T>(callback: () => T): T;
tryScan<T>(callback: () => T): T;
interface FileWatcher {
close(): void;
}
var sys: System;
}
declare module ts {
function tokenToString(t: SyntaxKind): string;
function computeLineStarts(text: string): number[];
function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number;
function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number): number;
function getLineStarts(sourceFile: SourceFile): number[];
function computeLineAndCharacterOfPosition(lineStarts: number[], position: number): {
line: number;
character: number;
};
function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter;
function isWhiteSpace(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function isOctalDigit(ch: number): boolean;
function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[];
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback): Scanner;
}
declare module ts {
function getNodeConstructor(kind: SyntaxKind): new () => Node;
@@ -1442,18 +1192,30 @@ declare module ts {
function isLeftHandSideExpression(expr: Expression): boolean;
function isAssignmentOperator(token: SyntaxKind): boolean;
}
declare module ts {
function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker;
}
declare module ts {
/** The version of the TypeScript compiler release */
let version: string;
const version: string;
function findConfigFile(searchPath: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
declare module ts {
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readConfigFile(fileName: string): any;
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseConfigFile(json: any, basePath?: string): ParsedCommandLine;
}
declare module ts {
/** The version of the language service API */
let servicesVersion: string;
@@ -1562,8 +1324,10 @@ declare module ts {
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[];
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[];
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[];
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
findReferences(fileName: string, position: number): ReferencedSymbol[];
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[];
/** @deprecated */
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
getOutliningSpans(fileName: string): OutliningSpan[];
@@ -1614,6 +1378,20 @@ declare module ts {
fileName: string;
isWriteAccess: boolean;
}
interface DocumentHighlights {
fileName: string;
highlightSpans: HighlightSpan[];
}
module HighlightSpanKind {
const none: string;
const definition: string;
const reference: string;
const writtenReference: string;
}
interface HighlightSpan {
textSpan: TextSpan;
kind: string;
}
interface NavigateToItem {
name: string;
kind: string;
@@ -1738,6 +1516,7 @@ declare module ts {
name: string;
kind: string;
kindModifiers: string;
sortText: string;
}
interface CompletionEntryDetails {
name: string;
@@ -1878,43 +1657,44 @@ declare module ts {
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
}
class ScriptElementKind {
static unknown: string;
static keyword: string;
static scriptElement: string;
static moduleElement: string;
static classElement: string;
static interfaceElement: string;
static typeElement: string;
static enumElement: string;
static variableElement: string;
static localVariableElement: string;
static functionElement: string;
static localFunctionElement: string;
static memberFunctionElement: string;
static memberGetAccessorElement: string;
static memberSetAccessorElement: string;
static memberVariableElement: string;
static constructorImplementationElement: string;
static callSignatureElement: string;
static indexSignatureElement: string;
static constructSignatureElement: string;
static parameterElement: string;
static typeParameterElement: string;
static primitiveType: string;
static label: string;
static alias: string;
static constElement: string;
static letElement: string;
module ScriptElementKind {
const unknown: string;
const warning: string;
const keyword: string;
const scriptElement: string;
const moduleElement: string;
const classElement: string;
const interfaceElement: string;
const typeElement: string;
const enumElement: string;
const variableElement: string;
const localVariableElement: string;
const functionElement: string;
const localFunctionElement: string;
const memberFunctionElement: string;
const memberGetAccessorElement: string;
const memberSetAccessorElement: string;
const memberVariableElement: string;
const constructorImplementationElement: string;
const callSignatureElement: string;
const indexSignatureElement: string;
const constructSignatureElement: string;
const parameterElement: string;
const typeParameterElement: string;
const primitiveType: string;
const label: string;
const alias: string;
const constElement: string;
const letElement: string;
}
class ScriptElementKindModifier {
static none: string;
static publicMemberModifier: string;
static privateMemberModifier: string;
static protectedMemberModifier: string;
static exportedModifier: string;
static ambientModifier: string;
static staticModifier: string;
module ScriptElementKindModifier {
const none: string;
const publicMemberModifier: string;
const privateMemberModifier: string;
const protectedMemberModifier: string;
const exportedModifier: string;
const ambientModifier: string;
const staticModifier: string;
}
class ClassificationTypeNames {
static comment: string;
@@ -1947,6 +1727,7 @@ declare module ts {
isCancellationRequested(): boolean;
throwIfCancellationRequested(): void;
}
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
+13543 -7153
View File
File diff suppressed because one or more lines are too long
-388
View File
@@ -1,388 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare module ts {
const enum Ternary {
False = 0,
Maybe = 1,
True = -1,
}
const enum Comparison {
LessThan = -1,
EqualTo = 0,
GreaterThan = 1,
}
interface StringSet extends Map<any> {
}
function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U;
function contains<T>(array: T[], value: T): boolean;
function indexOf<T>(array: T[], value: T): number;
function countWhere<T>(array: T[], predicate: (x: T) => boolean): number;
function filter<T>(array: T[], f: (x: T) => boolean): T[];
function map<T, U>(array: T[], f: (x: T) => U): U[];
function concatenate<T>(array1: T[], array2: T[]): T[];
function deduplicate<T>(array: T[]): T[];
function sum(array: any[], prop: string): number;
function addRange<T>(to: T[], from: T[]): void;
/**
* Returns the last element of an array if non-empty, undefined otherwise.
*/
function lastOrUndefined<T>(array: T[]): T;
function binarySearch(array: number[], value: number): number;
function reduceLeft<T>(array: T[], f: (a: T, x: T) => T): T;
function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
function reduceRight<T>(array: T[], f: (a: T, x: T) => T): T;
function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
function hasProperty<T>(map: Map<T>, key: string): boolean;
function getProperty<T>(map: Map<T>, key: string): T;
function isEmpty<T>(map: Map<T>): boolean;
function clone<T>(object: T): T;
function extend<T>(first: Map<T>, second: Map<T>): Map<T>;
function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U;
function forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U;
function lookUp<T>(map: Map<T>, key: string): T;
function copyMap<T>(source: Map<T>, target: Map<T>): void;
/**
* Creates a map from the elements of an array.
*
* @param array the array of input elements.
* @param makeKey a function that produces a key for a given element.
*
* This function makes no effort to avoid collisions; if any two elements produce
* the same key with the given 'makeKey' function, then the element with the higher
* index in the array will be the one associated with the produced key.
*/
function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T>;
let localizedDiagnosticMessages: Map<string>;
function getLocaleSpecificMessage(message: string): string;
function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic;
function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic;
function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain;
function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain;
function compareValues<T>(a: T, b: T): Comparison;
function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison;
function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[];
function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[];
function normalizeSlashes(path: string): string;
function getRootLength(path: string): number;
let directorySeparator: string;
function normalizePath(path: string): string;
function getDirectoryPath(path: string): string;
function isUrl(path: string): boolean;
function isRootedDiskPath(path: string): boolean;
function getNormalizedPathComponents(path: string, currentDirectory: string): string[];
function getNormalizedAbsolutePath(fileName: string, currentDirectory: string): string;
function getNormalizedPathFromPathComponents(pathComponents: string[]): string;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean): string;
function getBaseFileName(path: string): string;
function combinePaths(path1: string, path2: string): string;
function fileExtensionIs(path: string, extension: string): boolean;
function removeFileExtension(path: string): string;
function getDefaultLibFileName(options: CompilerOptions): string;
interface ObjectAllocator {
getNodeConstructor(kind: SyntaxKind): new () => Node;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
}
let objectAllocator: ObjectAllocator;
const enum AssertionLevel {
None = 0,
Normal = 1,
Aggressive = 2,
VeryAggressive = 3,
}
module Debug {
function shouldAssert(level: AssertionLevel): boolean;
function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void;
function fail(message?: string): void;
}
}
declare module ts {
interface System {
args: string[];
newLine: string;
useCaseSensitiveFileNames: boolean;
write(s: string): void;
readFile(fileName: string, encoding?: string): string;
writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(fileName: string, callback: (fileName: string) => void): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(directoryName: string): void;
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string): string[];
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
interface FileWatcher {
close(): void;
}
var sys: System;
}
declare module ts {
interface ReferencePathMatchResult {
fileReference?: FileReference;
diagnosticMessage?: DiagnosticMessage;
isNoDefaultLib?: boolean;
}
interface SynthesizedNode extends Node {
leadingCommentRanges?: CommentRange[];
trailingCommentRanges?: CommentRange[];
startsOnNewLine: boolean;
}
function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration;
interface StringSymbolWriter extends SymbolWriter {
string(): string;
}
interface EmitHost extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
getCommonSourceDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
writeFile: WriteFileCallback;
}
function getSingleLineStringWriter(): StringSymbolWriter;
function releaseStringWriter(writer: StringSymbolWriter): void;
function getFullWidth(node: Node): number;
function containsParseError(node: Node): boolean;
function getSourceFileOfNode(node: Node): SourceFile;
function getStartPositionOfLine(line: number, sourceFile: SourceFile): number;
function nodePosToString(node: Node): string;
function getStartPosOfNode(node: Node): number;
function nodeIsMissing(node: Node): boolean;
function nodeIsPresent(node: Node): boolean;
function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number;
function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string;
function getTextOfNodeFromSourceText(sourceText: string, node: Node): string;
function getTextOfNode(node: Node): string;
function escapeIdentifier(identifier: string): string;
function unescapeIdentifier(identifier: string): string;
function makeIdentifierFromModuleName(moduleName: string): string;
function isBlockOrCatchScoped(declaration: Declaration): boolean;
function getEnclosingBlockScopeContainer(node: Node): Node;
function isCatchClauseVariableDeclaration(declaration: Declaration): boolean;
function declarationNameToString(name: DeclarationName): string;
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic;
function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic;
function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan;
function isExternalModule(file: SourceFile): boolean;
function isDeclarationFile(file: SourceFile): boolean;
function isConstEnumDeclaration(node: Node): boolean;
function getCombinedNodeFlags(node: Node): NodeFlags;
function isConst(node: Node): boolean;
function isLet(node: Node): boolean;
function isPrologueDirective(node: Node): boolean;
function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
function getJsDocComments(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
let fullTripleSlashReferencePathRegEx: RegExp;
function forEachReturnStatement<T>(body: Block, visitor: (stmt: ReturnStatement) => T): T;
function isFunctionLike(node: Node): boolean;
function isFunctionBlock(node: Node): boolean;
function isObjectLiteralMethod(node: Node): boolean;
function getContainingFunction(node: Node): FunctionLikeDeclaration;
function getThisContainer(node: Node, includeArrowFunctions: boolean): Node;
function getSuperContainer(node: Node, includeFunctions: boolean): Node;
function getInvokedExpression(node: CallLikeExpression): Expression;
function nodeCanBeDecorated(node: Node): boolean;
function nodeIsDecorated(node: Node): boolean;
function childIsDecorated(node: Node): boolean;
function nodeOrChildIsDecorated(node: Node): boolean;
function isExpression(node: Node): boolean;
function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean;
function isExternalModuleImportEqualsDeclaration(node: Node): boolean;
function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression;
function isInternalModuleImportEqualsDeclaration(node: Node): boolean;
function getExternalModuleName(node: Node): Expression;
function hasDotDotDotToken(node: Node): boolean;
function hasQuestionToken(node: Node): boolean;
function hasRestParameters(s: SignatureDeclaration): boolean;
function isLiteralKind(kind: SyntaxKind): boolean;
function isTextualLiteralKind(kind: SyntaxKind): boolean;
function isTemplateLiteralKind(kind: SyntaxKind): boolean;
function isBindingPattern(node: Node): boolean;
function isInAmbientContext(node: Node): boolean;
function isDeclaration(node: Node): boolean;
function isStatement(n: Node): boolean;
function isClassElement(n: Node): boolean;
function isDeclarationName(name: Node): boolean;
function isAliasSymbolDeclaration(node: Node): boolean;
function getClassBaseTypeNode(node: ClassDeclaration): TypeReferenceNode;
function getClassImplementedTypeNodes(node: ClassDeclaration): NodeArray<TypeReferenceNode>;
function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<TypeReferenceNode>;
function getHeritageClause(clauses: NodeArray<HeritageClause>, kind: SyntaxKind): HeritageClause;
function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile;
function getAncestor(node: Node, kind: SyntaxKind): Node;
function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult;
function isKeyword(token: SyntaxKind): boolean;
function isTrivia(token: SyntaxKind): boolean;
/**
* A declaration has a dynamic name if both of the following are true:
* 1. The declaration has a computed property name
* 2. The computed name is *not* expressed as Symbol.<name>, where name
* is a property of the Symbol constructor that denotes a built in
* Symbol.
*/
function hasDynamicName(declaration: Declaration): boolean;
/**
* Checks if the expression is of the form:
* Symbol.name
* where Symbol is literally the word "Symbol", and name is any identifierName
*/
function isWellKnownSymbolSyntactically(node: Expression): boolean;
function getPropertyNameForPropertyNameNode(name: DeclarationName): string;
function getPropertyNameForKnownSymbolName(symbolName: string): string;
/**
* Includes the word "Symbol" with unicode escapes
*/
function isESSymbolIdentifier(node: Node): boolean;
function isModifier(token: SyntaxKind): boolean;
function textSpanEnd(span: TextSpan): number;
function textSpanIsEmpty(span: TextSpan): boolean;
function textSpanContainsPosition(span: TextSpan, position: number): boolean;
function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan;
function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean;
function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean;
function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan;
function createTextSpan(start: number, length: number): TextSpan;
function createTextSpanFromBounds(start: number, end: number): TextSpan;
function textChangeRangeNewSpan(range: TextChangeRange): TextSpan;
function textChangeRangeIsUnchanged(range: TextChangeRange): boolean;
function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange;
let unchangedTextChangeRange: TextChangeRange;
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function nodeStartsNewLexicalEnvironment(n: Node): boolean;
function nodeIsSynthesized(node: Node): boolean;
function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node;
/**
* Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
* but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
* Note that this doesn't actually wrap the input in double quotes.
*/
function escapeString(s: string): string;
function escapeNonAsciiCharacters(s: string): string;
interface EmitTextWriter {
write(s: string): void;
writeTextOfNode(sourceFile: SourceFile, node: Node): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
getText(): string;
rawWrite(s: string): void;
writeLiteral(s: string): void;
getTextPos(): number;
getLine(): number;
getColumn(): number;
getIndent(): number;
}
function getIndentString(level: number): string;
function getIndentSize(): number;
function createTextWriter(newLine: String): EmitTextWriter;
function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string;
function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string;
function writeFile(host: EmitHost, diagnostics: Diagnostic[], fileName: string, data: string, writeByteOrderMark: boolean): void;
function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number;
function getFirstConstructorWithBody(node: ClassDeclaration): ConstructorDeclaration;
function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean;
function getAllAccessorDeclarations(declarations: NodeArray<Declaration>, accessor: AccessorDeclaration): {
firstAccessor: AccessorDeclaration;
secondAccessor: AccessorDeclaration;
getAccessor: AccessorDeclaration;
setAccessor: AccessorDeclaration;
};
function emitNewLineBeforeLeadingComments(currentSourceFile: SourceFile, writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]): void;
function emitComments(currentSourceFile: SourceFile, writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string, writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void): void;
function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string): void;
}
declare module ts {
var optionDeclarations: CommandLineOption[];
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
function readConfigFile(fileName: string): any;
function parseConfigFile(json: any, basePath?: string): ParsedCommandLine;
}
declare module ts {
interface ListItemInfo {
listItemIndex: number;
list: Node;
}
function getEndLinePosition(line: number, sourceFile: SourceFile): number;
function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number;
function rangeContainsRange(r1: TextRange, r2: TextRange): boolean;
function startEndContainsRange(start: number, end: number, range: TextRange): boolean;
function rangeContainsStartEnd(range: TextRange, start: number, end: number): boolean;
function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number): boolean;
function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number): boolean;
function positionBelongsToNode(candidate: Node, position: number, sourceFile: SourceFile): boolean;
function isCompletedNode(n: Node, sourceFile: SourceFile): boolean;
function findListItemInfo(node: Node): ListItemInfo;
function hasChildOfKind(n: Node, kind: SyntaxKind, sourceFile?: SourceFile): boolean;
function findChildOfKind(n: Node, kind: SyntaxKind, sourceFile?: SourceFile): Node;
function findContainingList(node: Node): Node;
function getTouchingWord(sourceFile: SourceFile, position: number): Node;
function getTouchingPropertyName(sourceFile: SourceFile, position: number): Node;
/** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */
function getTouchingToken(sourceFile: SourceFile, position: number, includeItemAtEndPosition?: (n: Node) => boolean): Node;
/** Returns a token if position is in [start-of-leading-trivia, end) */
function getTokenAtPosition(sourceFile: SourceFile, position: number): Node;
/**
* The token on the left of the position is the token that strictly includes the position
* or sits to the left of the cursor if it is on a boundary. For example
*
* fo|o -> will return foo
* foo <comment> |bar -> will return foo
*
*/
function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node;
function findNextToken(previousToken: Node, parent: Node): Node;
function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node): Node;
function getNodeModifiers(node: Node): string;
function getTypeArgumentOrTypeParameterList(node: Node): NodeArray<Node>;
function isToken(n: Node): boolean;
function isWord(kind: SyntaxKind): boolean;
function isComment(kind: SyntaxKind): boolean;
function isPunctuation(kind: SyntaxKind): boolean;
function isInsideTemplateLiteral(node: LiteralExpression, position: number): boolean;
function isAccessibilityModifier(kind: SyntaxKind): boolean;
function compareDataObjects(dst: any, src: any): boolean;
}
declare module ts {
function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean;
function symbolPart(text: string, symbol: Symbol): SymbolDisplayPart;
function displayPart(text: string, kind: SymbolDisplayPartKind, symbol?: Symbol): SymbolDisplayPart;
function spacePart(): SymbolDisplayPart;
function keywordPart(kind: SyntaxKind): SymbolDisplayPart;
function punctuationPart(kind: SyntaxKind): SymbolDisplayPart;
function operatorPart(kind: SyntaxKind): SymbolDisplayPart;
function textOrKeywordPart(text: string): SymbolDisplayPart;
function textPart(text: string): SymbolDisplayPart;
function lineBreakPart(): SymbolDisplayPart;
function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[];
function typeToDisplayParts(typechecker: TypeChecker, type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[];
function symbolToDisplayParts(typeChecker: TypeChecker, symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): SymbolDisplayPart[];
function signatureToDisplayParts(typechecker: TypeChecker, signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[];
}
-388
View File
@@ -1,388 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare module "typescript" {
const enum Ternary {
False = 0,
Maybe = 1,
True = -1,
}
const enum Comparison {
LessThan = -1,
EqualTo = 0,
GreaterThan = 1,
}
interface StringSet extends Map<any> {
}
function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U;
function contains<T>(array: T[], value: T): boolean;
function indexOf<T>(array: T[], value: T): number;
function countWhere<T>(array: T[], predicate: (x: T) => boolean): number;
function filter<T>(array: T[], f: (x: T) => boolean): T[];
function map<T, U>(array: T[], f: (x: T) => U): U[];
function concatenate<T>(array1: T[], array2: T[]): T[];
function deduplicate<T>(array: T[]): T[];
function sum(array: any[], prop: string): number;
function addRange<T>(to: T[], from: T[]): void;
/**
* Returns the last element of an array if non-empty, undefined otherwise.
*/
function lastOrUndefined<T>(array: T[]): T;
function binarySearch(array: number[], value: number): number;
function reduceLeft<T>(array: T[], f: (a: T, x: T) => T): T;
function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
function reduceRight<T>(array: T[], f: (a: T, x: T) => T): T;
function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
function hasProperty<T>(map: Map<T>, key: string): boolean;
function getProperty<T>(map: Map<T>, key: string): T;
function isEmpty<T>(map: Map<T>): boolean;
function clone<T>(object: T): T;
function extend<T>(first: Map<T>, second: Map<T>): Map<T>;
function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U;
function forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U;
function lookUp<T>(map: Map<T>, key: string): T;
function copyMap<T>(source: Map<T>, target: Map<T>): void;
/**
* Creates a map from the elements of an array.
*
* @param array the array of input elements.
* @param makeKey a function that produces a key for a given element.
*
* This function makes no effort to avoid collisions; if any two elements produce
* the same key with the given 'makeKey' function, then the element with the higher
* index in the array will be the one associated with the produced key.
*/
function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T>;
let localizedDiagnosticMessages: Map<string>;
function getLocaleSpecificMessage(message: string): string;
function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic;
function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic;
function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain;
function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain;
function compareValues<T>(a: T, b: T): Comparison;
function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison;
function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[];
function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[];
function normalizeSlashes(path: string): string;
function getRootLength(path: string): number;
let directorySeparator: string;
function normalizePath(path: string): string;
function getDirectoryPath(path: string): string;
function isUrl(path: string): boolean;
function isRootedDiskPath(path: string): boolean;
function getNormalizedPathComponents(path: string, currentDirectory: string): string[];
function getNormalizedAbsolutePath(fileName: string, currentDirectory: string): string;
function getNormalizedPathFromPathComponents(pathComponents: string[]): string;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean): string;
function getBaseFileName(path: string): string;
function combinePaths(path1: string, path2: string): string;
function fileExtensionIs(path: string, extension: string): boolean;
function removeFileExtension(path: string): string;
function getDefaultLibFileName(options: CompilerOptions): string;
interface ObjectAllocator {
getNodeConstructor(kind: SyntaxKind): new () => Node;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
}
let objectAllocator: ObjectAllocator;
const enum AssertionLevel {
None = 0,
Normal = 1,
Aggressive = 2,
VeryAggressive = 3,
}
module Debug {
function shouldAssert(level: AssertionLevel): boolean;
function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void;
function fail(message?: string): void;
}
}
declare module "typescript" {
interface System {
args: string[];
newLine: string;
useCaseSensitiveFileNames: boolean;
write(s: string): void;
readFile(fileName: string, encoding?: string): string;
writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(fileName: string, callback: (fileName: string) => void): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(directoryName: string): void;
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string): string[];
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
interface FileWatcher {
close(): void;
}
var sys: System;
}
declare module "typescript" {
interface ReferencePathMatchResult {
fileReference?: FileReference;
diagnosticMessage?: DiagnosticMessage;
isNoDefaultLib?: boolean;
}
interface SynthesizedNode extends Node {
leadingCommentRanges?: CommentRange[];
trailingCommentRanges?: CommentRange[];
startsOnNewLine: boolean;
}
function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration;
interface StringSymbolWriter extends SymbolWriter {
string(): string;
}
interface EmitHost extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
getCommonSourceDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
writeFile: WriteFileCallback;
}
function getSingleLineStringWriter(): StringSymbolWriter;
function releaseStringWriter(writer: StringSymbolWriter): void;
function getFullWidth(node: Node): number;
function containsParseError(node: Node): boolean;
function getSourceFileOfNode(node: Node): SourceFile;
function getStartPositionOfLine(line: number, sourceFile: SourceFile): number;
function nodePosToString(node: Node): string;
function getStartPosOfNode(node: Node): number;
function nodeIsMissing(node: Node): boolean;
function nodeIsPresent(node: Node): boolean;
function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number;
function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string;
function getTextOfNodeFromSourceText(sourceText: string, node: Node): string;
function getTextOfNode(node: Node): string;
function escapeIdentifier(identifier: string): string;
function unescapeIdentifier(identifier: string): string;
function makeIdentifierFromModuleName(moduleName: string): string;
function isBlockOrCatchScoped(declaration: Declaration): boolean;
function getEnclosingBlockScopeContainer(node: Node): Node;
function isCatchClauseVariableDeclaration(declaration: Declaration): boolean;
function declarationNameToString(name: DeclarationName): string;
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic;
function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic;
function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan;
function isExternalModule(file: SourceFile): boolean;
function isDeclarationFile(file: SourceFile): boolean;
function isConstEnumDeclaration(node: Node): boolean;
function getCombinedNodeFlags(node: Node): NodeFlags;
function isConst(node: Node): boolean;
function isLet(node: Node): boolean;
function isPrologueDirective(node: Node): boolean;
function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
function getJsDocComments(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
let fullTripleSlashReferencePathRegEx: RegExp;
function forEachReturnStatement<T>(body: Block, visitor: (stmt: ReturnStatement) => T): T;
function isFunctionLike(node: Node): boolean;
function isFunctionBlock(node: Node): boolean;
function isObjectLiteralMethod(node: Node): boolean;
function getContainingFunction(node: Node): FunctionLikeDeclaration;
function getThisContainer(node: Node, includeArrowFunctions: boolean): Node;
function getSuperContainer(node: Node, includeFunctions: boolean): Node;
function getInvokedExpression(node: CallLikeExpression): Expression;
function nodeCanBeDecorated(node: Node): boolean;
function nodeIsDecorated(node: Node): boolean;
function childIsDecorated(node: Node): boolean;
function nodeOrChildIsDecorated(node: Node): boolean;
function isExpression(node: Node): boolean;
function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean;
function isExternalModuleImportEqualsDeclaration(node: Node): boolean;
function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression;
function isInternalModuleImportEqualsDeclaration(node: Node): boolean;
function getExternalModuleName(node: Node): Expression;
function hasDotDotDotToken(node: Node): boolean;
function hasQuestionToken(node: Node): boolean;
function hasRestParameters(s: SignatureDeclaration): boolean;
function isLiteralKind(kind: SyntaxKind): boolean;
function isTextualLiteralKind(kind: SyntaxKind): boolean;
function isTemplateLiteralKind(kind: SyntaxKind): boolean;
function isBindingPattern(node: Node): boolean;
function isInAmbientContext(node: Node): boolean;
function isDeclaration(node: Node): boolean;
function isStatement(n: Node): boolean;
function isClassElement(n: Node): boolean;
function isDeclarationName(name: Node): boolean;
function isAliasSymbolDeclaration(node: Node): boolean;
function getClassBaseTypeNode(node: ClassDeclaration): TypeReferenceNode;
function getClassImplementedTypeNodes(node: ClassDeclaration): NodeArray<TypeReferenceNode>;
function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<TypeReferenceNode>;
function getHeritageClause(clauses: NodeArray<HeritageClause>, kind: SyntaxKind): HeritageClause;
function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile;
function getAncestor(node: Node, kind: SyntaxKind): Node;
function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult;
function isKeyword(token: SyntaxKind): boolean;
function isTrivia(token: SyntaxKind): boolean;
/**
* A declaration has a dynamic name if both of the following are true:
* 1. The declaration has a computed property name
* 2. The computed name is *not* expressed as Symbol.<name>, where name
* is a property of the Symbol constructor that denotes a built in
* Symbol.
*/
function hasDynamicName(declaration: Declaration): boolean;
/**
* Checks if the expression is of the form:
* Symbol.name
* where Symbol is literally the word "Symbol", and name is any identifierName
*/
function isWellKnownSymbolSyntactically(node: Expression): boolean;
function getPropertyNameForPropertyNameNode(name: DeclarationName): string;
function getPropertyNameForKnownSymbolName(symbolName: string): string;
/**
* Includes the word "Symbol" with unicode escapes
*/
function isESSymbolIdentifier(node: Node): boolean;
function isModifier(token: SyntaxKind): boolean;
function textSpanEnd(span: TextSpan): number;
function textSpanIsEmpty(span: TextSpan): boolean;
function textSpanContainsPosition(span: TextSpan, position: number): boolean;
function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan;
function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean;
function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean;
function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan;
function createTextSpan(start: number, length: number): TextSpan;
function createTextSpanFromBounds(start: number, end: number): TextSpan;
function textChangeRangeNewSpan(range: TextChangeRange): TextSpan;
function textChangeRangeIsUnchanged(range: TextChangeRange): boolean;
function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange;
let unchangedTextChangeRange: TextChangeRange;
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function nodeStartsNewLexicalEnvironment(n: Node): boolean;
function nodeIsSynthesized(node: Node): boolean;
function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node;
/**
* Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
* but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
* Note that this doesn't actually wrap the input in double quotes.
*/
function escapeString(s: string): string;
function escapeNonAsciiCharacters(s: string): string;
interface EmitTextWriter {
write(s: string): void;
writeTextOfNode(sourceFile: SourceFile, node: Node): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
getText(): string;
rawWrite(s: string): void;
writeLiteral(s: string): void;
getTextPos(): number;
getLine(): number;
getColumn(): number;
getIndent(): number;
}
function getIndentString(level: number): string;
function getIndentSize(): number;
function createTextWriter(newLine: String): EmitTextWriter;
function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string;
function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string;
function writeFile(host: EmitHost, diagnostics: Diagnostic[], fileName: string, data: string, writeByteOrderMark: boolean): void;
function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number;
function getFirstConstructorWithBody(node: ClassDeclaration): ConstructorDeclaration;
function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean;
function getAllAccessorDeclarations(declarations: NodeArray<Declaration>, accessor: AccessorDeclaration): {
firstAccessor: AccessorDeclaration;
secondAccessor: AccessorDeclaration;
getAccessor: AccessorDeclaration;
setAccessor: AccessorDeclaration;
};
function emitNewLineBeforeLeadingComments(currentSourceFile: SourceFile, writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]): void;
function emitComments(currentSourceFile: SourceFile, writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string, writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void): void;
function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string): void;
}
declare module "typescript" {
var optionDeclarations: CommandLineOption[];
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
function readConfigFile(fileName: string): any;
function parseConfigFile(json: any, basePath?: string): ParsedCommandLine;
}
declare module "typescript" {
interface ListItemInfo {
listItemIndex: number;
list: Node;
}
function getEndLinePosition(line: number, sourceFile: SourceFile): number;
function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number;
function rangeContainsRange(r1: TextRange, r2: TextRange): boolean;
function startEndContainsRange(start: number, end: number, range: TextRange): boolean;
function rangeContainsStartEnd(range: TextRange, start: number, end: number): boolean;
function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number): boolean;
function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number): boolean;
function positionBelongsToNode(candidate: Node, position: number, sourceFile: SourceFile): boolean;
function isCompletedNode(n: Node, sourceFile: SourceFile): boolean;
function findListItemInfo(node: Node): ListItemInfo;
function hasChildOfKind(n: Node, kind: SyntaxKind, sourceFile?: SourceFile): boolean;
function findChildOfKind(n: Node, kind: SyntaxKind, sourceFile?: SourceFile): Node;
function findContainingList(node: Node): Node;
function getTouchingWord(sourceFile: SourceFile, position: number): Node;
function getTouchingPropertyName(sourceFile: SourceFile, position: number): Node;
/** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */
function getTouchingToken(sourceFile: SourceFile, position: number, includeItemAtEndPosition?: (n: Node) => boolean): Node;
/** Returns a token if position is in [start-of-leading-trivia, end) */
function getTokenAtPosition(sourceFile: SourceFile, position: number): Node;
/**
* The token on the left of the position is the token that strictly includes the position
* or sits to the left of the cursor if it is on a boundary. For example
*
* fo|o -> will return foo
* foo <comment> |bar -> will return foo
*
*/
function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node;
function findNextToken(previousToken: Node, parent: Node): Node;
function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node): Node;
function getNodeModifiers(node: Node): string;
function getTypeArgumentOrTypeParameterList(node: Node): NodeArray<Node>;
function isToken(n: Node): boolean;
function isWord(kind: SyntaxKind): boolean;
function isComment(kind: SyntaxKind): boolean;
function isPunctuation(kind: SyntaxKind): boolean;
function isInsideTemplateLiteral(node: LiteralExpression, position: number): boolean;
function isAccessibilityModifier(kind: SyntaxKind): boolean;
function compareDataObjects(dst: any, src: any): boolean;
}
declare module "typescript" {
function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean;
function symbolPart(text: string, symbol: Symbol): SymbolDisplayPart;
function displayPart(text: string, kind: SymbolDisplayPartKind, symbol?: Symbol): SymbolDisplayPart;
function spacePart(): SymbolDisplayPart;
function keywordPart(kind: SyntaxKind): SymbolDisplayPart;
function punctuationPart(kind: SyntaxKind): SymbolDisplayPart;
function operatorPart(kind: SyntaxKind): SymbolDisplayPart;
function textOrKeywordPart(text: string): SymbolDisplayPart;
function textPart(text: string): SymbolDisplayPart;
function lineBreakPart(): SymbolDisplayPart;
function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[];
function typeToDisplayParts(typechecker: TypeChecker, type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[];
function symbolToDisplayParts(typeChecker: TypeChecker, symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): SymbolDisplayPart[];
function signatureToDisplayParts(typechecker: TypeChecker, signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[];
}
+21 -11
View File
@@ -1,7 +1,8 @@
/// <reference path="parser.ts"/>
/* @internal */
module ts {
/* @internal */ export let bindTime = 0;
export let bindTime = 0;
export const enum ModuleInstanceState {
NonInstantiated = 0,
@@ -168,7 +169,7 @@ module ts {
addDeclarationToSymbol(symbol, node, includes);
symbol.parent = parent;
if (node.kind === SyntaxKind.ClassDeclaration && symbol.exports) {
if ((node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression) && symbol.exports) {
// TypeScript 1.0 spec (April 2014): 8.4
// Every class automatically contains a static property member named 'prototype',
// the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
@@ -286,6 +287,7 @@ module ts {
case SyntaxKind.ArrowFunction:
declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes);
break;
case SyntaxKind.ClassExpression:
case SyntaxKind.ClassDeclaration:
if (node.flags & NodeFlags.Static) {
declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes);
@@ -387,23 +389,28 @@ module ts {
bindChildren(node, /*symbolKind:*/ 0, /*isBlockScopeContainer:*/ true);
}
function bindBlockScopedVariableDeclaration(node: Declaration) {
function bindBlockScopedDeclaration(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags) {
switch (blockScopeContainer.kind) {
case SyntaxKind.ModuleDeclaration:
declareModuleMember(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes);
declareModuleMember(node, symbolKind, symbolExcludes);
break;
case SyntaxKind.SourceFile:
if (isExternalModule(<SourceFile>container)) {
declareModuleMember(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes);
declareModuleMember(node, symbolKind, symbolExcludes);
break;
}
// fall through.
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = {};
}
declareSymbol(blockScopeContainer.locals, undefined, node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes);
declareSymbol(blockScopeContainer.locals, undefined, node, symbolKind, symbolExcludes);
}
bindChildren(node, SymbolFlags.BlockScopedVariable, /*isBlockScopeContainer*/ false);
bindChildren(node, symbolKind, /*isBlockScopeContainer*/ false);
}
function bindBlockScopedVariableDeclaration(node: Declaration) {
bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes);
}
function getDestructuringParameterName(node: Declaration) {
@@ -485,11 +492,14 @@ module ts {
case SyntaxKind.ArrowFunction:
bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, "__function", /*isBlockScopeContainer*/ true);
break;
case SyntaxKind.ClassExpression:
bindAnonymousDeclaration(<ClassExpression>node, SymbolFlags.Class, "__class", /*isBlockScopeContainer*/ false);
break;
case SyntaxKind.CatchClause:
bindCatchVariableDeclaration(<CatchClause>node);
break;
case SyntaxKind.ClassDeclaration:
bindDeclaration(<Declaration>node, SymbolFlags.Class, SymbolFlags.ClassExcludes, /*isBlockScopeContainer*/ false);
bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.Class, SymbolFlags.ClassExcludes);
break;
case SyntaxKind.InterfaceDeclaration:
bindDeclaration(<Declaration>node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes, /*isBlockScopeContainer*/ false);
@@ -530,7 +540,7 @@ module ts {
bindChildren(node, 0, /*isBlockScopeContainer*/ false);
break;
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).expression && (<ExportAssignment>node).expression.kind === SyntaxKind.Identifier) {
if ((<ExportAssignment>node).expression.kind === SyntaxKind.Identifier) {
// An export default clause with an identifier exports all meanings of that identifier
declareSymbol(container.symbol.exports, container.symbol, <Declaration>node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
@@ -584,9 +594,9 @@ module ts {
// containing class.
if (node.flags & NodeFlags.AccessibilityModifier &&
node.parent.kind === SyntaxKind.Constructor &&
node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
(node.parent.parent.kind === SyntaxKind.ClassDeclaration || node.parent.parent.kind === SyntaxKind.ClassExpression)) {
let classDeclaration = <ClassDeclaration>node.parent.parent;
let classDeclaration = <ClassLikeDeclaration>node.parent.parent;
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
}
+838 -259
View File
File diff suppressed because it is too large Load Diff
+21 -1
View File
@@ -4,6 +4,7 @@
/// <reference path="scanner.ts"/>
module ts {
/* @internal */
export var optionDeclarations: CommandLineOption[] = [
{
name: "charset",
@@ -109,6 +110,10 @@ module ts {
type: "boolean",
description: Diagnostics.Do_not_emit_comments_to_output,
},
{
name: "separateCompilation",
type: "boolean",
},
{
name: "sourceMap",
type: "boolean",
@@ -151,9 +156,14 @@ module ts {
shortName: "w",
type: "boolean",
description: Diagnostics.Watch_input_files,
},
{
name: "emitDecoratorMetadata",
type: "boolean",
experimental: true
}
];
export function parseCommandLine(commandLine: string[]): ParsedCommandLine {
var options: CompilerOptions = {};
var fileNames: string[] = [];
@@ -263,6 +273,10 @@ module ts {
}
}
/**
* Read tsconfig.json file
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string): any {
try {
var text = sys.readFile(fileName);
@@ -272,6 +286,12 @@ module ts {
}
}
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseConfigFile(json: any, basePath?: string): ParsedCommandLine {
var errors: Diagnostic[] = [];
+4 -2
View File
@@ -1,7 +1,7 @@
/// <reference path="types.ts"/>
/* @internal */
module ts {
// Ternary values are defined such that
// x & y is False if either x or y is False.
// x & y is Maybe if either x or y is Maybe, but neither x or y is False.
@@ -434,7 +434,7 @@ module ts {
return path.replace(/\\/g, "/");
}
// Returns length of path root (i.e. length of "/", "x:/", "//server/share/")
// Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
export function getRootLength(path: string): number {
if (path.charCodeAt(0) === CharacterCodes.slash) {
if (path.charCodeAt(1) !== CharacterCodes.slash) return 1;
@@ -448,6 +448,8 @@ module ts {
if (path.charCodeAt(2) === CharacterCodes.slash) return 3;
return 2;
}
let idx = path.indexOf('://');
if (idx !== -1) return idx + 3
return 0;
}
+60 -24
View File
@@ -1,7 +1,7 @@
/// <reference path="checker.ts"/>
/* @internal */
module ts {
interface ModuleElementDeclarationEmitInfo {
node: Node;
outputPos: number;
@@ -314,12 +314,12 @@ module ts {
}
}
function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type: TypeNode | EntityName, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) {
function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type: TypeNode | EntityName | HeritageClauseElement, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) {
writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic;
emitType(type);
}
function emitType(type: TypeNode | StringLiteralExpression | Identifier | QualifiedName) {
function emitType(type: TypeNode | StringLiteralExpression | Identifier | QualifiedName | HeritageClauseElement) {
switch (type.kind) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.StringKeyword:
@@ -329,6 +329,8 @@ module ts {
case SyntaxKind.VoidKeyword:
case SyntaxKind.StringLiteral:
return writeTextOfNode(currentSourceFile, type);
case SyntaxKind.HeritageClauseElement:
return emitHeritageClauseElement(<HeritageClauseElement>type);
case SyntaxKind.TypeReference:
return emitTypeReference(<TypeReferenceNode>type);
case SyntaxKind.TypeQuery:
@@ -350,11 +352,9 @@ module ts {
return emitEntityName(<Identifier>type);
case SyntaxKind.QualifiedName:
return emitEntityName(<QualifiedName>type);
default:
Debug.fail("Unknown type annotation: " + type.kind);
}
function emitEntityName(entityName: EntityName) {
function emitEntityName(entityName: EntityName | PropertyAccessExpression) {
let visibilityResult = resolver.isEntityNameVisible(entityName,
// Aliases can be written asynchronously so use correct enclosing declaration
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
@@ -362,15 +362,28 @@ module ts {
handleSymbolAccessibilityError(visibilityResult);
writeEntityName(entityName);
function writeEntityName(entityName: EntityName) {
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
let qualifiedName = <QualifiedName>entityName;
writeEntityName(qualifiedName.left);
let left = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).left : (<PropertyAccessExpression>entityName).expression;
let right = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).right : (<PropertyAccessExpression>entityName).name;
writeEntityName(left);
write(".");
writeTextOfNode(currentSourceFile, qualifiedName.right);
writeTextOfNode(currentSourceFile, right);
}
}
}
function emitHeritageClauseElement(node: HeritageClauseElement) {
if (isSupportedHeritageClauseElement(node)) {
Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression);
emitEntityName(<Identifier | PropertyAccessExpression>node.expression);
if (node.typeArguments) {
write("<");
emitCommaList(node.typeArguments, emitType);
write(">");
}
}
}
@@ -429,20 +442,41 @@ module ts {
emitLines(node.statements);
}
// Return a temp variable name to be used in `export default` statements.
// The temp name will be of the form _default_counter.
// Note that export default is only allowed at most once in a module, so we
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName(): string {
let baseName = "_default";
if (!hasProperty(currentSourceFile.identifiers, baseName)) {
return baseName;
}
let count = 0;
while (true) {
let name = baseName + "_" + (++count);
if (!hasProperty(currentSourceFile.identifiers, name)) {
return name;
}
}
}
function emitExportAssignment(node: ExportAssignment) {
write(node.isExportEquals ? "export = " : "export default ");
if (node.expression.kind === SyntaxKind.Identifier) {
write(node.isExportEquals ? "export = " : "export default ");
writeTextOfNode(currentSourceFile, node.expression);
}
else {
// Expression
let tempVarName = getExportDefaultTempVariableName();
write("declare var ");
write(tempVarName);
write(": ");
if (node.type) {
emitType(node.type);
}
else {
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
}
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
write(tempVarName);
}
write(";");
writeLine();
@@ -827,14 +861,16 @@ module ts {
}
}
function emitHeritageClause(typeReferences: TypeReferenceNode[], isImplementsList: boolean) {
function emitHeritageClause(typeReferences: HeritageClauseElement[], isImplementsList: boolean) {
if (typeReferences) {
write(isImplementsList ? " implements " : " extends ");
emitCommaList(typeReferences, emitTypeOfTypeReference);
}
function emitTypeOfTypeReference(node: TypeReferenceNode) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
function emitTypeOfTypeReference(node: HeritageClauseElement) {
if (isSupportedHeritageClauseElement(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
}
function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
@@ -877,11 +913,11 @@ module ts {
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
let baseTypeNode = getClassBaseTypeNode(node);
let baseTypeNode = getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
emitHeritageClause([baseTypeNode], /*isImplementsList*/ false);
}
emitHeritageClause(getClassImplementedTypeNodes(node), /*isImplementsList*/ true);
emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true);
write(" {");
writeLine();
increaseIndent();
@@ -1525,7 +1561,7 @@ module ts {
}
}
// @internal
/* @internal */
export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) {
let emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile);
// TODO(shkamat): Should we not write any declaration file if any of them can produce error,
@@ -1,5 +1,6 @@
// <auto-generated />
/// <reference path="types.ts" />
/* @internal */
module ts {
export var Diagnostics = {
Unterminated_string_literal: { code: 1002, category: DiagnosticCategory.Error, key: "Unterminated string literal." },
@@ -158,13 +159,22 @@ module ts {
An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: DiagnosticCategory.Error, key: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." },
Unterminated_Unicode_escape_sequence: { code: 1199, category: DiagnosticCategory.Error, key: "Unterminated Unicode escape sequence." },
Line_terminator_not_permitted_before_arrow: { code: 1200, category: DiagnosticCategory.Error, key: "Line terminator not permitted before arrow." },
A_type_annotation_on_an_export_statement_is_only_allowed_in_an_ambient_external_module_declaration: { code: 1201, category: DiagnosticCategory.Error, key: "A type annotation on an export statement is only allowed in an ambient external module declaration." },
Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_or_import_d_from_mod_instead: { code: 1202, category: DiagnosticCategory.Error, key: "Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"' or 'import d from \"mod\"' instead." },
Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_export_default_instead: { code: 1203, category: DiagnosticCategory.Error, key: "Export assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'export default' instead." },
Cannot_compile_external_modules_into_amd_or_commonjs_when_targeting_es6_or_higher: { code: 1204, category: DiagnosticCategory.Error, key: "Cannot compile external modules into amd or commonjs when targeting es6 or higher." },
Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." },
Decorators_are_not_valid_here: { code: 1206, category: DiagnosticCategory.Error, key: "Decorators are not valid here." },
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: DiagnosticCategory.Error, key: "Decorators cannot be applied to multiple get/set accessors of the same name." },
Cannot_compile_non_external_modules_when_the_separateCompilation_flag_is_provided: { code: 1208, category: DiagnosticCategory.Error, key: "Cannot compile non-external modules when the '--separateCompilation' flag is provided." },
Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided: { code: 1209, category: DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--separateCompilation' flag is provided." },
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: DiagnosticCategory.Error, key: "Invalid use of '{0}'. Class definitions are automatically in strict mode." },
A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: DiagnosticCategory.Error, key: "A class declaration without the 'default' modifier must have a name" },
Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode" },
Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." },
Identifier_expected_0_is_a_reserved_word_in_strict_mode_External_Module_is_automatically_in_strict_mode: { code: 1214, category: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. External Module is automatically in strict mode." },
Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" },
Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." },
Type_expected_0_is_a_reserved_word_in_strict_mode_Module_is_automatically_in_strict_mode: { code: 1217, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode. Module is automatically in strict mode." },
Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." },
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." },
@@ -340,8 +350,8 @@ module ts {
The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." },
The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." },
Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...of' statement." },
The_right_hand_side_of_a_for_of_statement_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: DiagnosticCategory.Error, key: "The right-hand side of a 'for...of' statement must have a '[Symbol.iterator]()' method that returns an iterator." },
The_iterator_returned_by_the_right_hand_side_of_a_for_of_statement_must_have_a_next_method: { code: 2489, category: DiagnosticCategory.Error, key: "The iterator returned by the right-hand side of a 'for...of' statement must have a 'next()' method." },
Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: DiagnosticCategory.Error, key: "Type must have a '[Symbol.iterator]()' method that returns an iterator." },
An_iterator_must_have_a_next_method: { code: 2489, category: DiagnosticCategory.Error, key: "An iterator must have a 'next()' method." },
The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: DiagnosticCategory.Error, key: "The type returned by the 'next()' method of an iterator must have a 'value' property." },
The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." },
Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: DiagnosticCategory.Error, key: "Cannot redeclare identifier '{0}' in catch clause" },
@@ -351,6 +361,8 @@ module ts {
The_arguments_object_cannot_be_referenced_in_an_arrow_function_Consider_using_a_standard_function_expression: { code: 2496, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression." },
External_module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: DiagnosticCategory.Error, key: "External module '{0}' resolves to a non-module entity and cannot be imported using this construct." },
External_module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: DiagnosticCategory.Error, key: "External module '{0}' uses 'export =' and cannot be used with 'export *'." },
An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." },
A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -434,6 +446,11 @@ module ts {
Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." },
Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." },
Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." },
Option_sourceMap_cannot_be_specified_with_option_separateCompilation: { code: 5043, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'separateCompilation'." },
Option_declaration_cannot_be_specified_with_option_separateCompilation: { code: 5044, category: DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'separateCompilation'." },
Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation: { code: 5045, category: DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'." },
Option_out_cannot_be_specified_with_option_separateCompilation: { code: 5046, category: DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'separateCompilation'." },
Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: DiagnosticCategory.Error, key: "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." },
Concatenate_and_emit_output_to_single_file: { code: 6001, category: DiagnosticCategory.Message, key: "Concatenate and emit output to single file." },
Generates_corresponding_d_ts_file: { code: 6002, category: DiagnosticCategory.Message, key: "Generates corresponding '.d.ts' file." },
Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate map files instead of generated locations." },
@@ -496,7 +513,26 @@ module ts {
Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." },
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: DiagnosticCategory.Error, key: "You cannot rename elements that are defined in the standard TypeScript library." },
import_can_only_be_used_in_a_ts_file: { code: 8002, category: DiagnosticCategory.Error, key: "'import ... =' can only be used in a .ts file." },
export_can_only_be_used_in_a_ts_file: { code: 8003, category: DiagnosticCategory.Error, key: "'export=' can only be used in a .ts file." },
type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: DiagnosticCategory.Error, key: "'type parameter declarations' can only be used in a .ts file." },
implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: DiagnosticCategory.Error, key: "'implements clauses' can only be used in a .ts file." },
interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: DiagnosticCategory.Error, key: "'interface declarations' can only be used in a .ts file." },
module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: DiagnosticCategory.Error, key: "'module declarations' can only be used in a .ts file." },
type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: DiagnosticCategory.Error, key: "'type aliases' can only be used in a .ts file." },
_0_can_only_be_used_in_a_ts_file: { code: 8009, category: DiagnosticCategory.Error, key: "'{0}' can only be used in a .ts file." },
types_can_only_be_used_in_a_ts_file: { code: 8010, category: DiagnosticCategory.Error, key: "'types' can only be used in a .ts file." },
type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: DiagnosticCategory.Error, key: "'type arguments' can only be used in a .ts file." },
parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: DiagnosticCategory.Error, key: "'parameter modifiers' can only be used in a .ts file." },
can_only_be_used_in_a_ts_file: { code: 8013, category: DiagnosticCategory.Error, key: "'?' can only be used in a .ts file." },
property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." },
enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." },
type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." },
decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." },
yield_expressions_are_not_currently_supported: { code: 9000, category: DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." },
Generators_are_not_currently_supported: { code: 9001, category: DiagnosticCategory.Error, key: "Generators are not currently supported." },
Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." },
class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." },
class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration: { code: 9004, category: DiagnosticCategory.Error, key: "'class' declarations are only supported directly inside a module or as a top level declaration." },
};
}
+147 -7
View File
@@ -623,10 +623,6 @@
"category": "Error",
"code": 1200
},
"A type annotation on an export statement is only allowed in an ambient external module declaration.": {
"category": "Error",
"code": 1201
},
"Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"' or 'import d from \"mod\"' instead.": {
"category": "Error",
"code": 1202
@@ -651,7 +647,46 @@
"category": "Error",
"code": 1207
},
"Cannot compile non-external modules when the '--separateCompilation' flag is provided.": {
"category": "Error",
"code": 1208
},
"Ambient const enums are not allowed when the '--separateCompilation' flag is provided.": {
"category": "Error",
"code": 1209
},
"Invalid use of '{0}'. Class definitions are automatically in strict mode.": {
"category": "Error",
"code": 1210
},
"A class declaration without the 'default' modifier must have a name": {
"category": "Error",
"code": 1211
},
"Identifier expected. '{0}' is a reserved word in strict mode": {
"category": "Error",
"code": 1212
},
"Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode.": {
"category": "Error",
"code": 1213
},
"Identifier expected. '{0}' is a reserved word in strict mode. External Module is automatically in strict mode.": {
"category": "Error",
"code": 1214
},
"Type expected. '{0}' is a reserved word in strict mode": {
"category": "Error",
"code": 1215
},
"Type expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode.": {
"category": "Error",
"code": 1216
},
"Type expected. '{0}' is a reserved word in strict mode. Module is automatically in strict mode.": {
"category": "Error",
"code": 1217
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -1352,11 +1387,11 @@
"category": "Error",
"code": 2487
},
"The right-hand side of a 'for...of' statement must have a '[Symbol.iterator]()' method that returns an iterator.": {
"Type must have a '[Symbol.iterator]()' method that returns an iterator.": {
"category": "Error",
"code": 2488
},
"The iterator returned by the right-hand side of a 'for...of' statement must have a 'next()' method.": {
"An iterator must have a 'next()' method.": {
"category": "Error",
"code": 2489
},
@@ -1396,6 +1431,14 @@
"category": "Error",
"code": 2498
},
"An interface can only extend an identifier/qualified-name with optional type arguments.": {
"category": "Error",
"code": 2499
},
"A class can only implement an identifier/qualified-name with optional type arguments.": {
"category": "Error",
"code": 2500
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -1729,6 +1772,26 @@
"category": "Error",
"code": 5042
},
"Option 'sourceMap' cannot be specified with option 'separateCompilation'.": {
"category": "Error",
"code": 5043
},
"Option 'declaration' cannot be specified with option 'separateCompilation'.": {
"category": "Error",
"code": 5044
},
"Option 'noEmitOnError' cannot be specified with option 'separateCompilation'.": {
"category": "Error",
"code": 5045
},
"Option 'out' cannot be specified with option 'separateCompilation'.": {
"category": "Error",
"code": 5046
},
"Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher.": {
"category": "Error",
"code": 5047
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@@ -1978,6 +2041,71 @@
"category": "Error",
"code": 8001
},
"'import ... =' can only be used in a .ts file.": {
"category": "Error",
"code": 8002
},
"'export=' can only be used in a .ts file.": {
"category": "Error",
"code": 8003
},
"'type parameter declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8004
},
"'implements clauses' can only be used in a .ts file.": {
"category": "Error",
"code": 8005
},
"'interface declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8006
},
"'module declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8007
},
"'type aliases' can only be used in a .ts file.": {
"category": "Error",
"code": 8008
},
"'{0}' can only be used in a .ts file.": {
"category": "Error",
"code": 8009
},
"'types' can only be used in a .ts file.": {
"category": "Error",
"code": 8010
},
"'type arguments' can only be used in a .ts file.": {
"category": "Error",
"code": 8011
},
"'parameter modifiers' can only be used in a .ts file.": {
"category": "Error",
"code": 8012
},
"'?' can only be used in a .ts file.": {
"category": "Error",
"code": 8013
},
"'property declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8014
},
"'enum declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8015
},
"'type assertion expressions' can only be used in a .ts file.": {
"category": "Error",
"code": 8016
},
"'decorators' can only be used in a .ts file.": {
"category": "Error",
"code": 8017
},
"'yield' expressions are not currently supported.": {
"category": "Error",
"code": 9000
@@ -1985,5 +2113,17 @@
"Generators are not currently supported.": {
"category": "Error",
"code": 9001
},
"Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": {
"category": "Error",
"code": 9002
},
"'class' expressions are not currently supported.": {
"category": "Error",
"code": 9003
},
"'class' declarations are only supported directly inside a module or as a top level declaration.": {
"category": "Error",
"code": 9004
}
}
+697 -469
View File
File diff suppressed because it is too large Load Diff
+194 -58
View File
@@ -237,12 +237,13 @@ module ts {
case SyntaxKind.Decorator:
return visitNode(cbNode, (<Decorator>node).expression);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, (<ClassDeclaration>node).name) ||
visitNodes(cbNodes, (<ClassDeclaration>node).typeParameters) ||
visitNodes(cbNodes, (<ClassDeclaration>node).heritageClauses) ||
visitNodes(cbNodes, (<ClassDeclaration>node).members);
visitNode(cbNode, (<ClassLikeDeclaration>node).name) ||
visitNodes(cbNodes, (<ClassLikeDeclaration>node).typeParameters) ||
visitNodes(cbNodes, (<ClassLikeDeclaration>node).heritageClauses) ||
visitNodes(cbNodes, (<ClassLikeDeclaration>node).members);
case SyntaxKind.InterfaceDeclaration:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
@@ -298,8 +299,7 @@ module ts {
case SyntaxKind.ExportAssignment:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, (<ExportAssignment>node).expression) ||
visitNode(cbNode, (<ExportAssignment>node).type);
visitNode(cbNode, (<ExportAssignment>node).expression);
case SyntaxKind.TemplateExpression:
return visitNode(cbNode, (<TemplateExpression>node).head) || visitNodes(cbNodes, (<TemplateExpression>node).templateSpans);
case SyntaxKind.TemplateSpan:
@@ -308,6 +308,9 @@ module ts {
return visitNode(cbNode, (<ComputedPropertyName>node).expression);
case SyntaxKind.HeritageClause:
return visitNodes(cbNodes, (<HeritageClause>node).types);
case SyntaxKind.HeritageClauseElement:
return visitNode(cbNode, (<HeritageClauseElement>node).expression) ||
visitNodes(cbNodes, (<HeritageClauseElement>node).typeArguments);
case SyntaxKind.ExternalModuleReference:
return visitNode(cbNode, (<ExternalModuleReference>node).expression);
case SyntaxKind.MissingDeclaration:
@@ -324,7 +327,7 @@ module ts {
TypeMembers, // Members in interface or type literal
ClassMembers, // Members in class declaration
EnumMembers, // Members in enum declaration
TypeReferences, // Type references in extends or implements clause
HeritageClauseElement, // Elements in a heritage clause
VariableDeclarations, // Variable declarations in variable statement
ObjectBindingElements, // Binding elements in object binding list
ArrayBindingElements, // Binding elements in array binding list
@@ -356,7 +359,7 @@ module ts {
case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected;
case ParsingContext.ClassMembers: return Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
case ParsingContext.EnumMembers: return Diagnostics.Enum_member_expected;
case ParsingContext.TypeReferences: return Diagnostics.Type_reference_expected;
case ParsingContext.HeritageClauseElement: return Diagnostics.Expression_expected;
case ParsingContext.VariableDeclarations: return Diagnostics.Variable_declaration_expected;
case ParsingContext.ObjectBindingElements: return Diagnostics.Property_destructuring_pattern_expected;
case ParsingContext.ArrayBindingElements: return Diagnostics.Array_element_destructuring_pattern_expected;
@@ -824,7 +827,7 @@ module ts {
// to reuse are already at the appropriate position in the new text. That way when we
// reuse them, we don't have to figure out if they need to be adjusted. Second, it makes
// it very easy to determine if we can reuse a node. If the node's position is at where
// we are in the text, then we can reuse it. Otherwise we can't. If hte node's position
// we are in the text, then we can reuse it. Otherwise we can't. If the node's position
// is ahead of us, then we'll need to rescan tokens. If the node's position is behind
// us, then we'll need to skip it or crumble it as appropriate
//
@@ -1029,7 +1032,7 @@ module ts {
// that some tokens that would be considered identifiers may be considered keywords.
//
// When adding more parser context flags, consider which is the more common case that the
// flag will be in. This should be hte 'false' state for that flag. The reason for this is
// flag will be in. This should be the 'false' state for that flag. The reason for this is
// that we don't store data in our nodes unless the value is in the *non-default* state. So,
// for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
// 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
@@ -1040,7 +1043,7 @@ module ts {
//
// An important thing about these context concepts. By default they are effectively inherited
// while parsing through every grammar production. i.e. if you don't change them, then when
// you parse a sub-production, it will have the same context values as hte parent production.
// you parse a sub-production, it will have the same context values as the parent production.
// This is great most of the time. After all, consider all the 'expression' grammar productions
// and how nearly all of them pass along the 'in' and 'yield' context values:
//
@@ -1346,6 +1349,7 @@ module ts {
return speculationHelper(callback, /*isLookAhead:*/ false);
}
// Ignore strict mode flag because we will report an error in type checker instead.
function isIdentifier(): boolean {
if (token === SyntaxKind.Identifier) {
return true;
@@ -1357,7 +1361,7 @@ module ts {
return false;
}
return inStrictModeContext() ? token > SyntaxKind.LastFutureReservedWord : token > SyntaxKind.LastReservedWord;
return token > SyntaxKind.LastReservedWord;
}
function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage): boolean {
@@ -1481,6 +1485,11 @@ module ts {
identifierCount++;
if (isIdentifier) {
let node = <Identifier>createNode(SyntaxKind.Identifier);
// Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
if (token !== SyntaxKind.Identifier) {
node.originalKeywordKind = token;
}
node.text = internIdentifier(scanner.getTokenValue());
nextToken();
return finishNode(node);
@@ -1605,7 +1614,11 @@ module ts {
case ParsingContext.TypeMembers:
return isStartOfTypeMember();
case ParsingContext.ClassMembers:
return lookAhead(isClassMemberStart);
// We allow semicolons as class elements (as specified by ES6) as long as we're
// not in error recovery. If we're in error recovery, we don't want an errant
// semicolon to be treated as a class member (since they're almost always used
// for statements.
return lookAhead(isClassMemberStart) || (token === SyntaxKind.SemicolonToken && !inErrorRecovery);
case ParsingContext.EnumMembers:
// Include open bracket computed properties. This technically also lets in indexers,
// which would be a candidate for improved error reporting.
@@ -1614,10 +1627,22 @@ module ts {
return token === SyntaxKind.OpenBracketToken || token === SyntaxKind.AsteriskToken || isLiteralPropertyName();
case ParsingContext.ObjectBindingElements:
return isLiteralPropertyName();
case ParsingContext.TypeReferences:
// We want to make sure that the "extends" in "extends foo" or the "implements" in
// "implements foo" is not considered a type name.
return isIdentifier() && !isNotHeritageClauseTypeName();
case ParsingContext.HeritageClauseElement:
// If we see { } then only consume it as an expression if it is followed by , or {
// That way we won't consume the body of a class in its heritage clause.
if (token === SyntaxKind.OpenBraceToken) {
return lookAhead(isValidHeritageClauseObjectLiteral);
}
if (!inErrorRecovery) {
return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
}
else {
// If we're in error recovery we tighten up what we're willing to match.
// That way we don't treat something like "this" as a valid heritage clause
// element during recovery.
return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
}
case ParsingContext.VariableDeclarations:
return isIdentifierOrPattern();
case ParsingContext.ArrayBindingElements:
@@ -1641,21 +1666,44 @@ module ts {
Debug.fail("Non-exhaustive case in 'isListElement'.");
}
function isValidHeritageClauseObjectLiteral() {
Debug.assert(token === SyntaxKind.OpenBraceToken);
if (nextToken() === SyntaxKind.CloseBraceToken) {
// if we see "extends {}" then only treat the {} as what we're extending (and not
// the class body) if we have:
//
// extends {} {
// extends {},
// extends {} extends
// extends {} implements
let next = nextToken();
return next === SyntaxKind.CommaToken || next === SyntaxKind.OpenBraceToken || next === SyntaxKind.ExtendsKeyword || next === SyntaxKind.ImplementsKeyword;
}
return true;
}
function nextTokenIsIdentifier() {
nextToken();
return isIdentifier();
}
function isNotHeritageClauseTypeName(): boolean {
function isHeritageClauseExtendsOrImplementsKeyword(): boolean {
if (token === SyntaxKind.ImplementsKeyword ||
token === SyntaxKind.ExtendsKeyword) {
return lookAhead(nextTokenIsIdentifier);
return lookAhead(nextTokenIsStartOfExpression);
}
return false;
}
function nextTokenIsStartOfExpression() {
nextToken();
return isStartOfExpression();
}
// True if positioned at a list terminator
function isListTerminator(kind: ParsingContext): boolean {
if (token === SyntaxKind.EndOfFileToken) {
@@ -1676,7 +1724,7 @@ module ts {
return token === SyntaxKind.CloseBraceToken;
case ParsingContext.SwitchClauseStatements:
return token === SyntaxKind.CloseBraceToken || token === SyntaxKind.CaseKeyword || token === SyntaxKind.DefaultKeyword;
case ParsingContext.TypeReferences:
case ParsingContext.HeritageClauseElement:
return token === SyntaxKind.OpenBraceToken || token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword;
case ParsingContext.VariableDeclarations:
return isVariableDeclaratorListTerminator();
@@ -1793,7 +1841,7 @@ module ts {
// some node, then we cannot get a node from the old source tree. This is because we
// want to mark the next node we encounter as being unusable.
//
// Note: This may be too conservative. Perhaps we could reuse hte node and set the bit
// Note: This may be too conservative. Perhaps we could reuse the node and set the bit
// on it (or its leftmost child) as having the error. For now though, being conservative
// is nice and likely won't ever affect perf.
if (parseErrorBeforeNextFinishedNode) {
@@ -1891,12 +1939,6 @@ module ts {
// This would probably be safe to reuse. There is no speculative parsing with
// heritage clauses.
case ParsingContext.TypeReferences:
// This would probably be safe to reuse. There is no speculative parsing with
// type names in a heritage clause. There can be generic names in the type
// name list. But because it is a type context, we never use speculative
// parsing on the type argument list.
case ParsingContext.TypeParameters:
// This would probably be safe to reuse. There is no speculative parsing with
// type parameters. Note that that's because type *parameters* only occur in
@@ -1923,6 +1965,12 @@ module ts {
// cases. i.e. a property assignment may end with an expression, and thus might
// have lookahead far beyond it's old node.
case ParsingContext.ObjectLiteralMembers:
// This is probably not safe to reuse. There can be speculative parsing with
// type names in a heritage clause. There can be generic names in the type
// name list, and there can be left hand side expressions (which can have type
// arguments.)
case ParsingContext.HeritageClauseElement:
}
return false;
@@ -1957,6 +2005,7 @@ module ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.SemicolonClassElement:
return true;
}
}
@@ -2846,8 +2895,7 @@ module ts {
}
// EXPRESSIONS
function isStartOfExpression(): boolean {
function isStartOfLeftHandSideExpression(): boolean {
switch (token) {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
@@ -2862,9 +2910,23 @@ module ts {
case SyntaxKind.OpenBracketToken:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.ClassKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.Identifier:
return true;
default:
return isIdentifier();
}
}
function isStartOfExpression(): boolean {
if (isStartOfLeftHandSideExpression()) {
return true;
}
switch (token) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
@@ -2875,7 +2937,6 @@ module ts {
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.Identifier:
case SyntaxKind.YieldKeyword:
// Yield always starts an expression. Either it is an identifier (in which case
// it is definitely an expression). Or it's a keyword (either because we're in
@@ -2895,8 +2956,12 @@ module ts {
}
function isStartOfExpressionStatement(): boolean {
// As per the grammar, neither '{' nor 'function' can start an expression statement.
return token !== SyntaxKind.OpenBraceToken && token !== SyntaxKind.FunctionKeyword && token !== SyntaxKind.AtToken && isStartOfExpression();
// As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
return token !== SyntaxKind.OpenBraceToken &&
token !== SyntaxKind.FunctionKeyword &&
token !== SyntaxKind.ClassKeyword &&
token !== SyntaxKind.AtToken &&
isStartOfExpression();
}
function parseExpression(): Expression {
@@ -3161,6 +3226,16 @@ module ts {
}
}
// If encounter "([" or "({", this could be the start of a binding pattern.
// Examples:
// ([ x ]) => { }
// ({ x }) => { }
// ([ x ])
// ({ x })
if (second === SyntaxKind.OpenBracketToken || second === SyntaxKind.OpenBraceToken) {
return Tristate.Unknown;
}
// Simple case: "(..."
// This is an arrow function with a rest parameter.
if (second === SyntaxKind.DotDotDotToken) {
@@ -3241,8 +3316,12 @@ module ts {
return parseFunctionBlock(/*allowYield:*/ false, /* ignoreMissingOpenBrace */ false);
}
if (isStartOfStatement(/*inErrorRecovery:*/ true) && !isStartOfExpressionStatement() && token !== SyntaxKind.FunctionKeyword) {
// Check if we got a plain statement (i.e. no expression-statements, no functions expressions/declarations)
if (isStartOfStatement(/*inErrorRecovery:*/ true) &&
!isStartOfExpressionStatement() &&
token !== SyntaxKind.FunctionKeyword &&
token !== SyntaxKind.ClassKeyword) {
// Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
//
// Here we try to recover from a potential error situation in the case where the
// user meant to supply a block. For example, if the user wrote:
@@ -3667,7 +3746,6 @@ module ts {
case SyntaxKind.CloseBracketToken: // foo<x>]
case SyntaxKind.ColonToken: // foo<x>:
case SyntaxKind.SemicolonToken: // foo<x>;
case SyntaxKind.CommaToken: // foo<x>,
case SyntaxKind.QuestionToken: // foo<x>?
case SyntaxKind.EqualsEqualsToken: // foo<x> ==
case SyntaxKind.EqualsEqualsEqualsToken: // foo<x> ===
@@ -3685,6 +3763,12 @@ module ts {
// treat it as such.
return true;
case SyntaxKind.CommaToken: // foo<x>,
case SyntaxKind.OpenBraceToken: // foo<x> {
// We don't want to treat these as type arguments. Otherwise we'll parse this
// as an invocation expression. Instead, we want to parse out the expression
// in isolation from the type arguments.
default:
// Anything else treat as an expression.
return false;
@@ -3709,6 +3793,8 @@ module ts {
return parseArrayLiteralExpression();
case SyntaxKind.OpenBraceToken:
return parseObjectLiteralExpression();
case SyntaxKind.ClassKeyword:
return parseClassExpression();
case SyntaxKind.FunctionKeyword:
return parseFunctionExpression();
case SyntaxKind.NewKeyword:
@@ -4129,13 +4215,14 @@ module ts {
}
function isStartOfStatement(inErrorRecovery: boolean): boolean {
// Functions and variable statements are allowed as a statement. But as per the grammar,
// they also allow modifiers. So we have to check for those statements that might be
// following modifiers.This ensures that things work properly when incrementally parsing
// as the parser will produce the same FunctionDeclaraiton or VariableStatement if it has
// the same text regardless of whether it is inside a block or not.
// Functions, variable statements and classes are allowed as a statement. But as per
// the grammar, they also allow modifiers. So we have to check for those statements
// that might be following modifiers.This ensures that things work properly when
// incrementally parsing as the parser will produce the same FunctionDeclaraiton,
// VariableStatement or ClassDeclaration, if it has the same text regardless of whether
// it is inside a block or not.
if (isModifier(token)) {
let result = lookAhead(parseVariableStatementOrFunctionDeclarationWithDecoratorsOrModifiers);
let result = lookAhead(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers);
if (result) {
return true;
}
@@ -4154,6 +4241,7 @@ module ts {
case SyntaxKind.VarKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.ClassKeyword:
case SyntaxKind.IfKeyword:
case SyntaxKind.DoKeyword:
case SyntaxKind.WhileKeyword:
@@ -4178,7 +4266,6 @@ module ts {
let isConstEnum = lookAhead(nextTokenIsEnumKeyword);
return !isConstEnum;
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.ClassKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.TypeKeyword:
@@ -4222,6 +4309,8 @@ module ts {
return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined);
case SyntaxKind.FunctionKeyword:
return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined);
case SyntaxKind.ClassKeyword:
return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined);
case SyntaxKind.SemicolonToken:
return parseEmptyStatement();
case SyntaxKind.IfKeyword:
@@ -4267,7 +4356,7 @@ module ts {
// Even though variable statements and function declarations cannot have decorators,
// we parse them here to provide better error recovery.
if (isModifier(token) || token === SyntaxKind.AtToken) {
let result = tryParse(parseVariableStatementOrFunctionDeclarationWithDecoratorsOrModifiers);
let result = tryParse(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers);
if (result) {
return result;
}
@@ -4277,7 +4366,7 @@ module ts {
}
}
function parseVariableStatementOrFunctionDeclarationWithDecoratorsOrModifiers(): FunctionDeclaration | VariableStatement {
function parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers(): FunctionDeclaration | VariableStatement | ClassDeclaration {
let start = scanner.getStartPos();
let decorators = parseDecorators();
let modifiers = parseModifiers();
@@ -4297,8 +4386,12 @@ module ts {
case SyntaxKind.VarKeyword:
return parseVariableStatement(start, decorators, modifiers);
case SyntaxKind.FunctionKeyword:
return parseFunctionDeclaration(start, decorators, modifiers);
case SyntaxKind.ClassKeyword:
return parseClassDeclaration(start, decorators, modifiers);
}
return undefined;
@@ -4512,6 +4605,18 @@ module ts {
return finishNode(node);
}
function isClassMemberModifier(idToken: SyntaxKind) {
switch (idToken) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.StaticKeyword:
return true;
default:
return false;
}
}
function isClassMemberStart(): boolean {
let idToken: SyntaxKind;
@@ -4522,6 +4627,16 @@ module ts {
// Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
while (isModifier(token)) {
idToken = token;
// If the idToken is a class modifier (protected, private, public, and static), it is
// certain that we are starting to parse class member. This allows better error recovery
// Example:
// public foo() ... // true
// public @dec blah ... // true; we will then report an error later
// export public ... // true; we will then report an error later
if (isClassMemberModifier(idToken)) {
return true;
}
nextToken();
}
@@ -4619,6 +4734,12 @@ module ts {
}
function parseClassElement(): ClassElement {
if (token === SyntaxKind.SemicolonToken) {
let result = <SemicolonClassElement>createNode(SyntaxKind.SemicolonClassElement);
nextToken();
return finishNode(result);
}
let fullStart = getNodePos();
let decorators = parseDecorators();
let modifiers = parseModifiers();
@@ -4657,18 +4778,28 @@ module ts {
Debug.fail("Should not have attempted to parse class member declaration.");
}
function parseClassExpression(): ClassExpression {
return <ClassExpression>parseClassDeclarationOrExpression(
/*fullStart:*/ scanner.getStartPos(),
/*decorators:*/ undefined,
/*modifiers:*/ undefined,
SyntaxKind.ClassExpression);
}
function parseClassDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ClassDeclaration {
return <ClassDeclaration>parseClassDeclarationOrExpression(fullStart, decorators, modifiers, SyntaxKind.ClassDeclaration);
}
function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration {
// In ES6 specification, All parts of a ClassDeclaration or a ClassExpression are strict mode code
let savedStrictModeContext = inStrictModeContext();
if (languageVersion >= ScriptTarget.ES6) {
setStrictModeContext(true);
}
setStrictModeContext(true);
var node = <ClassDeclaration>createNode(SyntaxKind.ClassDeclaration, fullStart);
var node = <ClassLikeDeclaration>createNode(kind, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
parseExpected(SyntaxKind.ClassKeyword);
node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier();
node.name = parseOptionalIdentifier();
node.typeParameters = parseTypeParameters();
node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause:*/ true);
@@ -4714,13 +4845,23 @@ module ts {
let node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
node.token = token;
nextToken();
node.types = parseDelimitedList(ParsingContext.TypeReferences, parseTypeReference);
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseHeritageClauseElement);
return finishNode(node);
}
return undefined;
}
function parseHeritageClauseElement(): HeritageClauseElement {
let node = <HeritageClauseElement>createNode(SyntaxKind.HeritageClauseElement);
node.expression = parseLeftHandSideExpressionOrHigher();
if (token === SyntaxKind.LessThanToken) {
node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
}
return finishNode(node);
}
function isHeritageClause(): boolean {
return token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword;
}
@@ -5019,17 +5160,11 @@ module ts {
setModifiers(node, modifiers);
if (parseOptional(SyntaxKind.EqualsToken)) {
node.isExportEquals = true;
node.expression = parseAssignmentExpressionOrHigher();
}
else {
parseExpected(SyntaxKind.DefaultKeyword);
if (parseOptional(SyntaxKind.ColonToken)) {
node.type = parseType();
}
else {
node.expression = parseAssignmentExpressionOrHigher();
}
}
node.expression = parseAssignmentExpressionOrHigher();
parseSemicolon();
return finishNode(node);
}
@@ -5195,7 +5330,7 @@ module ts {
break;
}
let range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos() };
let range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() };
let comment = sourceText.substring(range.pos, range.end);
let referencePathMatchResult = getFileReferenceFromReferencePath(comment, range);
@@ -5263,6 +5398,7 @@ module ts {
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ClassExpression:
case SyntaxKind.FunctionExpression:
case SyntaxKind.Identifier:
case SyntaxKind.RegularExpressionLiteral:
+34 -7
View File
@@ -8,7 +8,7 @@ module ts {
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
export let version = "1.5.0";
export const version = "1.5.0";
export function findConfigFile(searchPath: string): string {
var fileName = "tsconfig.json";
@@ -454,6 +454,24 @@ module ts {
}
function verifyCompilerOptions() {
if (options.separateCompilation) {
if (options.sourceMap) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceMap_cannot_be_specified_with_option_separateCompilation));
}
if (options.declaration) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_declaration_cannot_be_specified_with_option_separateCompilation));
}
if (options.noEmitOnError) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation));
}
if (options.out) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_out_cannot_be_specified_with_option_separateCompilation));
}
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
@@ -468,12 +486,21 @@ module ts {
let languageVersion = options.target || ScriptTarget.ES3;
let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (firstExternalModuleSourceFile && !options.module) {
if (options.separateCompilation) {
if (!options.module && languageVersion < ScriptTarget.ES6) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher));
}
let firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
if (firstNonExternalModuleSourceFile) {
let span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
diagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_non_external_modules_when_the_separateCompilation_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided));
}
// Cannot specify module gen target when in es6 or above
@@ -481,11 +508,11 @@ module ts {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_external_modules_into_amd_or_commonjs_when_targeting_es6_or_higher));
}
// there has to be common source directory if user specified --outdir || --sourcRoot
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
options.sourceRoot || // there is --sourceRoot specified
(options.mapRoot && // there is --mapRoot Specified and there would be multiple js files generated
(options.mapRoot && // there is --mapRoot specified and there would be multiple js files generated
(!options.out || firstExternalModuleSourceFile !== undefined))) {
let commonPathComponents: string[];
+11 -2
View File
@@ -2,11 +2,12 @@
/// <reference path="diagnosticInformationMap.generated.ts"/>
module ts {
/* @internal */
export interface ErrorCallback {
(message: DiagnosticMessage, length: number): void;
}
/* @internal */
export interface Scanner {
getStartPos(): number;
getToken(): SyntaxKind;
@@ -262,6 +263,7 @@ module ts {
return textToToken[s];
}
/* @internal */
export function computeLineStarts(text: string): number[] {
let result: number[] = new Array();
let pos = 0;
@@ -293,15 +295,18 @@ module ts {
return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character);
}
/* @internal */
export function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number): number {
Debug.assert(line >= 0 && line < lineStarts.length);
return lineStarts[line] + character;
}
/* @internal */
export function getLineStarts(sourceFile: SourceFile): number[] {
return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
}
/* @internal */
export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) {
let lineNumber = binarySearch(lineStarts, position);
if (lineNumber < 0) {
@@ -362,10 +367,12 @@ module ts {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
}
/* @internal */
export function isOctalDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
}
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
while (true) {
let ch = text.charCodeAt(pos);
@@ -523,6 +530,7 @@ module ts {
let nextChar = text.charCodeAt(pos + 1);
let hasTrailingNewLine = false;
if (nextChar === CharacterCodes.slash || nextChar === CharacterCodes.asterisk) {
let kind = nextChar === CharacterCodes.slash ? SyntaxKind.SingleLineCommentTrivia : SyntaxKind.MultiLineCommentTrivia;
let startPos = pos;
pos += 2;
if (nextChar === CharacterCodes.slash) {
@@ -548,7 +556,7 @@ module ts {
result = [];
}
result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine });
result.push({ pos: startPos, end: pos, hasTrailingNewLine, kind });
}
continue;
}
@@ -587,6 +595,7 @@ module ts {
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback): Scanner {
let pos: number; // Current position (end position of text of current token)
let len: number; // Length of text
+5 -5
View File
@@ -6,17 +6,17 @@ module ts {
newLine: string;
useCaseSensitiveFileNames: boolean;
write(s: string): void;
readFile(fileName: string, encoding?: string): string;
writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void;
watchFile? (fileName: string, callback: (fileName: string) => void): FileWatcher;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: (path: string) => void): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(directoryName: string): void;
createDirectory(path: string): void;
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string): string[];
getMemoryUsage? (): number;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
+127 -54
View File
@@ -203,9 +203,12 @@ module ts {
TemplateExpression,
YieldExpression,
SpreadElementExpression,
ClassExpression,
OmittedExpression,
// Misc
TemplateSpan,
HeritageClauseElement,
SemicolonClassElement,
// Element
Block,
VariableStatement,
@@ -317,6 +320,7 @@ module ts {
BlockScoped = Let | Const
}
/* @internal */
export const enum ParserContextFlags {
// Set if this node was parsed in strict mode. Used for grammar error checks, as well as
// checking if the node can be reused in incremental settings.
@@ -352,6 +356,7 @@ module ts {
HasAggregatedChildData = 1 << 7
}
/* @internal */
export const enum RelationComparisonResult {
Succeeded = 1, // Should be truthy
Failed = 2,
@@ -363,15 +368,15 @@ module ts {
flags: NodeFlags;
// Specific context the parser was in when this node was created. Normally undefined.
// Only set when the parser was in some interesting context (like async/yield).
parserContextFlags?: ParserContextFlags;
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
modifiers?: ModifiersArray; // Array of modifiers
id?: number; // Unique id (used to look up NodeLinks)
parent?: Node; // Parent node (initialized by binding)
symbol?: Symbol; // Symbol declared by node (initialized by binding)
locals?: SymbolTable; // Locals associated with node (initialized by binding)
nextContainer?: Node; // Next container in declaration order (initialized by binding)
localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
/* @internal */ parserContextFlags?: ParserContextFlags;
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
modifiers?: ModifiersArray; // Array of modifiers
/* @internal */ id?: number; // Unique id (used to look up NodeLinks)
parent?: Node; // Parent node (initialized by binding)
/* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding)
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
/* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
}
export interface NodeArray<T> extends Array<T>, TextRange {
@@ -383,7 +388,8 @@ module ts {
}
export interface Identifier extends PrimaryExpression {
text: string; // Text of identifier (with escapes converted to characters)
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
}
export interface QualifiedName extends Node {
@@ -536,6 +542,11 @@ module ts {
body?: Block;
}
// For when we encounter a semicolon in a class declaration. ES6 allows these as class elements.
export interface SemicolonClassElement extends ClassElement {
_semicolonClassElementBrand: any;
}
// See the comment on MethodDeclaration for the intuition behind AccessorDeclaration being a
// ClassElement and an ObjectLiteralElement.
export interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
@@ -728,6 +739,11 @@ module ts {
arguments: NodeArray<Expression>;
}
export interface HeritageClauseElement extends Node {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
}
export interface NewExpression extends CallExpression, PrimaryExpression { }
export interface TaggedTemplateExpression extends MemberExpression {
@@ -849,13 +865,19 @@ module ts {
_moduleElementBrand: any;
}
export interface ClassDeclaration extends Declaration, ModuleElement {
export interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
members: NodeArray<ClassElement>;
}
export interface ClassDeclaration extends ClassLikeDeclaration, Statement {
}
export interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
}
export interface ClassElement extends Declaration {
_classElementBrand: any;
}
@@ -869,7 +891,7 @@ module ts {
export interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray<TypeReferenceNode>;
types?: NodeArray<HeritageClauseElement>;
}
export interface TypeAliasDeclaration extends Declaration, ModuleElement {
@@ -914,7 +936,7 @@ module ts {
// import "mod" => importClause = undefined, moduleSpecifier = "mod"
// In rest of the cases, module specifier is string literal corresponding to module
// ImportClause information is shown at its declaration below.
export interface ImportDeclaration extends Statement, ModuleElement {
export interface ImportDeclaration extends ModuleElement {
importClause?: ImportClause;
moduleSpecifier: Expression;
}
@@ -956,8 +978,7 @@ module ts {
export interface ExportAssignment extends Declaration, ModuleElement {
isExportEquals?: boolean;
expression?: Expression;
type?: TypeNode;
expression: Expression;
}
export interface FileReference extends TextRange {
@@ -966,6 +987,7 @@ module ts {
export interface CommentRange extends TextRange {
hasTrailingNewLine?: boolean;
kind: SyntaxKind;
}
// Source files are declarations when they are external modules.
@@ -982,11 +1004,12 @@ module ts {
hasNoDefaultLib: boolean;
// The first node that causes this file to be an external module
externalModuleIndicator: Node;
languageVersion: ScriptTarget;
identifiers: Map<string>;
// The first node that causes this file to be an external module
/* @internal */ externalModuleIndicator: Node;
/* @internal */ identifiers: Map<string>;
/* @internal */ nodeCount: number;
/* @internal */ identifierCount: number;
/* @internal */ symbolCount: number;
@@ -1014,6 +1037,9 @@ module ts {
}
export interface Program extends ScriptReferenceHost {
/**
* Get a list of files in the program
*/
getSourceFiles(): SourceFile[];
/**
@@ -1033,10 +1059,12 @@ module ts {
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
// Gets a type checker that can be used to semantically analyze source fils in the program.
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
getTypeChecker(): TypeChecker;
getCommonSourceDirectory(): string;
/* @internal */ getCommonSourceDirectory(): string;
// For testing purposes only. Should not be used by any other consumers (including the
// language service).
@@ -1049,12 +1077,18 @@ module ts {
}
export interface SourceMapSpan {
emittedLine: number; // Line number in the .js file
emittedColumn: number; // Column number in the .js file
sourceLine: number; // Line number in the .ts file
sourceColumn: number; // Column number in the .ts file
nameIndex?: number; // Optional name (index into names array) associated with this span
sourceIndex: number; // .ts file (index into sources array) associated with this span*/
/** Line number in the .js file. */
emittedLine: number;
/** Column number in the .js file. */
emittedColumn: number;
/** Line number in the .ts file. */
sourceLine: number;
/** Column number in the .ts file. */
sourceColumn: number;
/** Optional name (index into names array) associated with this span. */
nameIndex?: number;
/** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
export interface SourceMapData {
@@ -1069,7 +1103,7 @@ module ts {
sourceMapDecodedMappings: SourceMapSpan[]; // Raw source map spans that were encoded into the sourceMapMappings
}
// Return code used by getEmitOutput function to indicate status of the function
/** Return code used by getEmitOutput function to indicate status of the function */
export enum ExitStatus {
// Compiler ran successfully. Either this was a simple do-nothing compilation (for example,
// when -version or -help was provided, or this was a normal compilation, no diagnostics
@@ -1086,7 +1120,7 @@ module ts {
export interface EmitResult {
emitSkipped: boolean;
diagnostics: Diagnostic[];
sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
/* @internal */ sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
}
export interface TypeCheckerHost {
@@ -1105,8 +1139,6 @@ module ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getReturnTypeOfSignature(signature: Signature): Type;
// If 'predicate' is supplied, then only the first symbol in scope matching the predicate
// will be returned. Otherwise, all symbols in scope will be returned.
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getShorthandAssignmentValueSymbol(location: Node): Symbol;
@@ -1127,7 +1159,7 @@ module ts {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfExternalModule(node: ImportDeclaration): Symbol[];
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
@@ -1198,14 +1230,17 @@ module ts {
UseOnlyExternalAliasing = 0x00000002,
}
/* @internal */
export const enum SymbolAccessibility {
Accessible,
NotAccessible,
CannotBeNamed
}
/* @internal */
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
/* @internal */
export interface SymbolVisibilityResult {
accessibility: SymbolAccessibility;
aliasesToMakeVisible?: AnyImportSyntax[]; // aliases that need to have this symbol visible
@@ -1213,10 +1248,12 @@ module ts {
errorNode?: Node; // optional node that results in error
}
/* @internal */
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string // If the symbol is not visible from module, module's name
}
/* @internal */
export interface EmitResolver {
hasGlobalName(name: string): boolean;
getExpressionNameSubstitution(node: Identifier, getGeneratedNameForNode: (node: Node) => string): string;
@@ -1231,11 +1268,14 @@ module ts {
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
resolvesToSomeValue(location: Node, name: string): boolean;
getBlockScopedVariableId(node: Identifier): number;
serializeTypeOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): string | string[];
serializeParameterTypesOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): (string | string[])[];
serializeReturnTypeOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): string | string[];
}
export const enum SymbolFlags {
@@ -1318,19 +1358,20 @@ module ts {
}
export interface Symbol {
flags: SymbolFlags; // Symbol flags
name: string; // Name of symbol
id?: number; // Unique id (used to look up SymbolLinks)
mergeId?: number; // Merge id (used to look up merged symbol)
declarations?: Declaration[]; // Declarations associated with this symbol
parent?: Symbol; // Parent symbol
members?: SymbolTable; // Class, interface or literal instance members
exports?: SymbolTable; // Module exports
exportSymbol?: Symbol; // Exported symbol associated with this symbol
valueDeclaration?: Declaration // First value declaration of the symbol
constEnumOnlyModule?: boolean // True if module contains only const enums or other modules with only const enums
flags: SymbolFlags; // Symbol flags
name: string; // Name of symbol
/* @internal */ id?: number; // Unique id (used to look up SymbolLinks)
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
declarations?: Declaration[]; // Declarations associated with this symbol
/* @internal */ parent?: Symbol; // Parent symbol
members?: SymbolTable; // Class, interface or literal instance members
exports?: SymbolTable; // Module exports
/* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
valueDeclaration?: Declaration; // First value declaration of the symbol
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
}
/* @internal */
export interface SymbolLinks {
target?: Symbol; // Resolved (non-alias) target of an alias
type?: Type; // Type of value symbol
@@ -1342,12 +1383,14 @@ module ts {
exportsChecked?: boolean; // True if exports of external module have been checked
}
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks { }
export interface SymbolTable {
[index: string]: Symbol;
}
/* @internal */
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
@@ -1361,8 +1404,10 @@ module ts {
EnumValuesComputed = 0x00000080,
BlockScopedBindingInLoop = 0x00000100,
EmitDecorate = 0x00000200, // Emit __decorate
EmitParam = 0x00000400, // Emit __param helper for decorators
}
/* @internal */
export interface NodeLinks {
resolvedType?: Type; // Cached type of type node
resolvedSignature?: Signature; // Cached signature of signature node or call expression
@@ -1395,27 +1440,34 @@ module ts {
Tuple = 0x00002000, // Tuple
Union = 0x00004000, // Union
Anonymous = 0x00008000, // Anonymous
/* @internal */
FromSignature = 0x00010000, // Created for signature assignment check
ObjectLiteral = 0x00020000, // Originates in an object literal
/* @internal */
ContainsUndefinedOrNull = 0x00040000, // Type is or contains Undefined or Null type
ContainsObjectLiteral = 0x00080000, // Type is or contains object literal type
/* @internal */
ContainsObjectLiteral = 0x00080000, // Type is or contains object literal type
ESSymbol = 0x00100000, // Type of symbol primitive introduced in ES6
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
/* @internal */
Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum,
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
}
// Properties common to all types
export interface Type {
flags: TypeFlags; // Flags
id: number; // Unique ID
symbol?: Symbol; // Symbol associated with type (if any)
flags: TypeFlags; // Flags
/* @internal */ id: number; // Unique ID
symbol?: Symbol; // Symbol associated with type (if any)
}
/* @internal */
// Intrinsic types (TypeFlags.Intrinsic)
export interface IntrinsicType extends Type {
intrinsicName: string; // Name of intrinsic type
@@ -1448,6 +1500,7 @@ module ts {
// Generic class and interface types
export interface GenericType extends InterfaceType, TypeReference {
/* @internal */
instantiations: Map<TypeReference>; // Generic instantiation cache
}
@@ -1458,9 +1511,11 @@ module ts {
export interface UnionType extends Type {
types: Type[]; // Constituent types
/* @internal */
resolvedProperties: SymbolTable; // Cache of resolved properties
}
/* @internal */
// Resolved object or union type
export interface ResolvedType extends ObjectType, UnionType {
members: SymbolTable; // Properties by name
@@ -1474,7 +1529,9 @@ module ts {
// Type parameters (TypeFlags.TypeParameter)
export interface TypeParameter extends Type {
constraint: Type; // Constraint
/* @internal */
target?: TypeParameter; // Instantiation target
/* @internal */
mapper?: TypeMapper; // Instantiation mapper
}
@@ -1487,14 +1544,23 @@ module ts {
declaration: SignatureDeclaration; // Originating declaration
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: Symbol[]; // Parameters
/* @internal */
resolvedReturnType: Type; // Resolved return type
/* @internal */
minArgumentCount: number; // Number of non-optional parameters
/* @internal */
hasRestParameter: boolean; // True if last parameter is rest parameter
/* @internal */
hasStringLiterals: boolean; // True if specialized
/* @internal */
target?: Signature; // Instantiation target
/* @internal */
mapper?: TypeMapper; // Instantiation mapper
/* @internal */
unionSignatures?: Signature[]; // Underlying signatures of a union signature
/* @internal */
erasedSignatureCache?: Signature; // Erased version of signature (deferred)
/* @internal */
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
}
@@ -1503,11 +1569,12 @@ module ts {
Number,
}
/* @internal */
export interface TypeMapper {
(t: Type): Type;
}
// @internal
/* @internal */
export interface TypeInferences {
primary: Type[]; // Inferences made directly to a type parameter
secondary: Type[]; // Inferences made to a type parameter in a union type
@@ -1515,7 +1582,7 @@ module ts {
// If a type parameter is fixed, no more inferences can be made for the type parameter
}
// @internal
/* @internal */
export interface InferenceContext {
typeParameters: TypeParameter[]; // Type parameters for which inferences are made
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
@@ -1531,10 +1598,12 @@ module ts {
code: number;
}
// A linked list of formatted diagnostic messages to be used as part of a multiline message.
// It is built from the bottom up, leaving the head to be the "main" diagnostic.
// While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
// the difference is that messages are all preformatted in DMC.
/**
* A linked list of formatted diagnostic messages to be used as part of a multiline message.
* It is built from the bottom up, leaving the head to be the "main" diagnostic.
* While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
* the difference is that messages are all preformatted in DMC.
*/
export interface DiagnosticMessageChain {
messageText: string;
category: DiagnosticCategory;
@@ -1585,6 +1654,8 @@ module ts {
target?: ScriptTarget;
version?: boolean;
watch?: boolean;
separateCompilation?: boolean;
emitDecoratorMetadata?: boolean;
/* @internal */ stripInternal?: boolean;
[option: string]: string | number | boolean;
}
@@ -1616,6 +1687,7 @@ module ts {
errors: Diagnostic[];
}
/* @internal */
export interface CommandLineOption {
name: string;
type: string | Map<number>; // "string", "number", "boolean", or an object literal mapping named values to actual values
@@ -1627,6 +1699,7 @@ module ts {
experimental?: boolean;
}
/* @internal */
export const enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 0x7F,
@@ -1788,7 +1861,7 @@ module ts {
newLength: number;
}
// @internal
/* @internal */
export interface DiagnosticCollection {
// Adds a diagnostic to this diagnostic collection.
add(diagnostic: Diagnostic): void;
+96 -11
View File
@@ -1,5 +1,6 @@
/// <reference path="binder.ts" />
/* @internal */
module ts {
export interface ReferencePathMatchResult {
fileReference?: FileReference
@@ -145,7 +146,7 @@ module ts {
return node.pos === node.end && node.kind !== SyntaxKind.EndOfFileToken;
}
export function nodeIsPresent(node: Node) {
return !nodeIsMissing(node);
}
@@ -160,6 +161,14 @@ module ts {
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
}
export function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number {
if (nodeIsMissing(node) || !node.decorators) {
return getTokenPosOfNode(node, sourceFile);
}
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string {
if (nodeIsMissing(node)) {
return "";
@@ -274,11 +283,19 @@ module ts {
export function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan {
let errorNode = node;
switch (node.kind) {
case SyntaxKind.SourceFile:
let pos = skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
return createTextSpan(0, 0);
}
return getSpanOfTokenAtPosition(sourceFile, pos);
// This list is a work in progress. Add missing node kinds to improve their error
// spans.
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.EnumDeclaration:
@@ -288,7 +305,7 @@ module ts {
errorNode = (<Declaration>node).name;
break;
}
if (errorNode === undefined) {
// If we don't have a better node, then just set the error on the first token of
// construct.
@@ -441,6 +458,18 @@ module ts {
return false;
}
export function isAccessor(node: Node): boolean {
if (node) {
switch (node.kind) {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return true;
}
}
return false;
}
export function isFunctionLike(node: Node): boolean {
if (node) {
switch (node.kind) {
@@ -506,6 +535,19 @@ module ts {
// the *body* of the container.
node = node.parent;
break;
case SyntaxKind.Decorator:
// Decorators are always applied outside of the body of a class or method.
if (node.parent.kind === SyntaxKind.Parameter && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
node = node.parent.parent;
}
else if (isClassElement(node.parent)) {
// If the decorator's parent is a class element, we resolve the 'this' container
// from the parent class declaration.
node = node.parent;
}
break;
case SyntaxKind.ArrowFunction:
if (!includeArrowFunctions) {
continue;
@@ -548,6 +590,19 @@ module ts {
// the *body* of the container.
node = node.parent;
break;
case SyntaxKind.Decorator:
// Decorators are always applied outside of the body of a class or method.
if (node.parent.kind === SyntaxKind.Parameter && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
node = node.parent.parent;
}
else if (isClassElement(node.parent)) {
// If the decorator's parent is a class element, we resolve the 'this' container
// from the parent class declaration.
node = node.parent;
}
break;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
@@ -634,7 +689,7 @@ module ts {
return false;
}
export function childIsDecorated(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
@@ -670,6 +725,7 @@ module ts {
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ClassExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.VoidExpression:
case SyntaxKind.DeleteExpression:
@@ -733,6 +789,8 @@ module ts {
return node === (<TemplateSpan>parent).expression;
case SyntaxKind.ComputedPropertyName:
return node === (<ComputedPropertyName>parent).expression;
case SyntaxKind.Decorator:
return true;
default:
if (isExpression(parent)) {
return true;
@@ -745,7 +803,7 @@ module ts {
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
let moduleState = getModuleInstanceState(node)
return moduleState === ModuleInstanceState.Instantiated ||
(preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly);
(preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly);
}
export function isExternalModuleImportEqualsDeclaration(node: Node) {
@@ -898,6 +956,7 @@ module ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodSignature:
case SyntaxKind.IndexSignature:
return true;
default:
@@ -942,12 +1001,12 @@ module ts {
node.kind === SyntaxKind.ExportAssignment && (<ExportAssignment>node).expression.kind === SyntaxKind.Identifier;
}
export function getClassBaseTypeNode(node: ClassDeclaration) {
export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration) {
let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword);
return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
}
export function getClassImplementedTypeNodes(node: ClassDeclaration) {
export function getClassImplementsHeritageClauseElements(node: ClassDeclaration) {
let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword);
return heritageClause ? heritageClause.types : undefined;
}
@@ -1161,7 +1220,7 @@ module ts {
export function createTextSpanFromBounds(start: number, end: number) {
return createTextSpan(start, end - start);
}
export function textChangeRangeNewSpan(range: TextChangeRange) {
return createTextSpan(range.span.start, range.newLength);
}
@@ -1320,7 +1379,7 @@ module ts {
return node;
}
// @internal
/* @internal */
export function createDiagnosticCollection(): DiagnosticCollection {
let nonFileDiagnostics: Diagnostic[] = [];
let fileDiagnostics: Map<Diagnostic[]> = {};
@@ -1435,13 +1494,13 @@ module ts {
return escapedCharsMap[c] || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
}
}
function get16BitUnicodeEscapeSequence(charCode: number): string {
let hexCharCode = charCode.toString(16).toUpperCase();
let paddedHexCode = ("0000" + hexCharCode).slice(-4);
return "\\u" + paddedHexCode;
}
let nonAsciiCharacters = /[^\u0000-\u007F]/g;
export function escapeNonAsciiCharacters(s: string): string {
// Replace non-ASCII characters with '\uNNNN' escapes if any exist.
@@ -1573,7 +1632,7 @@ module ts {
return getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
export function getFirstConstructorWithBody(node: ClassDeclaration): ConstructorDeclaration {
export function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration {
return forEach(node.members, member => {
if (member.kind === SyntaxKind.Constructor && nodeIsPresent((<ConstructorDeclaration>member).body)) {
return <ConstructorDeclaration>member;
@@ -1768,4 +1827,30 @@ module ts {
}
}
// Returns false if this heritage clause element's expression contains something unsupported
// (i.e. not a name or dotted name).
export function isSupportedHeritageClauseElement(node: HeritageClauseElement): boolean {
return isSupportedHeritageClauseElementExpression(node.expression);
}
function isSupportedHeritageClauseElementExpression(node: Expression): boolean {
if (node.kind === SyntaxKind.Identifier) {
return true;
}
else if (node.kind === SyntaxKind.PropertyAccessExpression) {
return isSupportedHeritageClauseElementExpression((<PropertyAccessExpression>node).expression);
}
else {
return false;
}
}
export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
return (node.parent.kind === SyntaxKind.QualifiedName && (<QualifiedName>node.parent).right === node) ||
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node);
}
export function getLocalSymbolForExportDefault(symbol: Symbol) {
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & NodeFlags.Default) ? symbol.valueDeclaration.localSymbol : undefined;
}
}
+30 -18
View File
@@ -14,6 +14,7 @@
//
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='harnessLanguageService.ts' />
/// <reference path='harness.ts' />
/// <reference path='fourslashRunner.ts' />
@@ -115,7 +116,7 @@ module FourSlash {
// Name of testcase metadata including ts.CompilerOptions properties that will be used by globalOptions
// To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames
// Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data
var testOptMetadataNames = {
var metadataOptionNames = {
baselineFile: 'BaselineFile',
declaration: 'declaration',
emitThisFile: 'emitThisFile', // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project
@@ -126,14 +127,15 @@ module FourSlash {
outDir: 'outDir',
sourceMap: 'sourceMap',
sourceRoot: 'sourceRoot',
allowNonTsExtensions: 'allowNonTsExtensions',
resolveReference: 'ResolveReference', // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file
};
// List of allowed metadata names
var fileMetadataNames = [testOptMetadataNames.fileName, testOptMetadataNames.emitThisFile, testOptMetadataNames.resolveReference];
var globalMetadataNames = [testOptMetadataNames.baselineFile, testOptMetadataNames.declaration,
testOptMetadataNames.mapRoot, testOptMetadataNames.module, testOptMetadataNames.out,
testOptMetadataNames.outDir, testOptMetadataNames.sourceMap, testOptMetadataNames.sourceRoot]
var fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference];
var globalMetadataNames = [metadataOptionNames.allowNonTsExtensions, metadataOptionNames.baselineFile, metadataOptionNames.declaration,
metadataOptionNames.mapRoot, metadataOptionNames.module, metadataOptionNames.out,
metadataOptionNames.outDir, metadataOptionNames.sourceMap, metadataOptionNames.sourceRoot]
function convertGlobalOptionsToCompilerOptions(globalOptions: { [idx: string]: string }): ts.CompilerOptions {
var settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 };
@@ -141,13 +143,16 @@ module FourSlash {
for (var prop in globalOptions) {
if (globalOptions.hasOwnProperty(prop)) {
switch (prop) {
case testOptMetadataNames.declaration:
case metadataOptionNames.allowNonTsExtensions:
settings.allowNonTsExtensions = true;
break;
case metadataOptionNames.declaration:
settings.declaration = true;
break;
case testOptMetadataNames.mapRoot:
case metadataOptionNames.mapRoot:
settings.mapRoot = globalOptions[prop];
break;
case testOptMetadataNames.module:
case metadataOptionNames.module:
// create appropriate external module target for CompilationSettings
switch (globalOptions[prop]) {
case "AMD":
@@ -162,16 +167,16 @@ module FourSlash {
break;
}
break;
case testOptMetadataNames.out:
case metadataOptionNames.out:
settings.out = globalOptions[prop];
break;
case testOptMetadataNames.outDir:
case metadataOptionNames.outDir:
settings.outDir = globalOptions[prop];
break;
case testOptMetadataNames.sourceMap:
case metadataOptionNames.sourceMap:
settings.sourceMap = true;
break;
case testOptMetadataNames.sourceRoot:
case metadataOptionNames.sourceRoot:
settings.sourceRoot = globalOptions[prop];
break;
}
@@ -303,7 +308,7 @@ module FourSlash {
ts.forEach(testData.files, file => {
// Create map between fileName and its content for easily looking up when resolveReference flag is specified
this.inputFiles[file.fileName] = file.content;
if (!startResolveFileRef && file.fileOptions[testOptMetadataNames.resolveReference]) {
if (!startResolveFileRef && file.fileOptions[metadataOptionNames.resolveReference]) {
startResolveFileRef = file;
} else if (startResolveFileRef) {
// If entry point for resolving file references is already specified, report duplication error
@@ -793,6 +798,13 @@ module FourSlash {
return "\nActual " + name + ":\n\t" + actualValue + "\nExpected value:\n\t" + expectedValue;
}
public getSemanticDiagnostics(expected: string) {
var diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
var realized = ts.realizeDiagnostics(diagnostics, "\r\n");
var actual = JSON.stringify(realized, null, " ");
assert.equal(actual, expected);
}
public verifyQuickInfoString(negative: boolean, expectedText?: string, expectedDocumentation?: string) {
[expectedText, expectedDocumentation].forEach(str => {
if (str) {
@@ -1131,7 +1143,7 @@ module FourSlash {
Harness.Baseline.runBaseline(
"Breakpoint Locations for " + this.activeFile.fileName,
this.testData.globalOptions[testOptMetadataNames.baselineFile],
this.testData.globalOptions[metadataOptionNames.baselineFile],
() => {
return this.baselineCurrentFileLocations(pos => this.getBreakpointStatementLocation(pos));
},
@@ -1146,7 +1158,7 @@ module FourSlash {
var allFourSlashFiles = this.testData.files;
for (var idx = 0; idx < allFourSlashFiles.length; ++idx) {
var file = allFourSlashFiles[idx];
if (file.fileOptions[testOptMetadataNames.emitThisFile]) {
if (file.fileOptions[metadataOptionNames.emitThisFile]) {
// Find a file with the flag emitThisFile turned on
emitFiles.push(file);
}
@@ -1159,7 +1171,7 @@ module FourSlash {
Harness.Baseline.runBaseline(
"Generate getEmitOutput baseline : " + emitFiles.join(" "),
this.testData.globalOptions[testOptMetadataNames.baselineFile],
this.testData.globalOptions[metadataOptionNames.baselineFile],
() => {
var resultString = "";
// Loop through all the emittedFiles and emit them one by one
@@ -1704,7 +1716,7 @@ module FourSlash {
Harness.Baseline.runBaseline(
"Name OrDottedNameSpans for " + this.activeFile.fileName,
this.testData.globalOptions[testOptMetadataNames.baselineFile],
this.testData.globalOptions[metadataOptionNames.baselineFile],
() => {
return this.baselineCurrentFileLocations(pos =>
this.getNameOrDottedNameSpan(pos));
@@ -2280,7 +2292,7 @@ module FourSlash {
if (globalMetadataNamesIndex === -1) {
if (fileMetadataNamesIndex === -1) {
throw new Error('Unrecognized metadata name "' + match[1] + '". Available global metadata names are: ' + globalMetadataNames.join(', ') + '; file metadata names are: ' + fileMetadataNames.join(', '));
} else if (fileMetadataNamesIndex === fileMetadataNames.indexOf(testOptMetadataNames.fileName)) {
} else if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) {
// Found an @FileName directive, if this is not the first then create a new subfile
if (currentFileContent) {
var file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges);
+25 -7
View File
@@ -781,7 +781,7 @@ module Harness {
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[] {
public toArray(): { fileName: string; file: WriterAggregator; }[]{
var result: { fileName: string; file: WriterAggregator; }[] = [];
for (var p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
@@ -944,6 +944,10 @@ module Harness {
var newLine = '\r\n';
// 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 }[] = [];
var useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
this.settings.forEach(setting => {
switch (setting.flag.toLowerCase()) {
@@ -1052,23 +1056,28 @@ module Harness {
options.preserveConstEnums = setting.value === 'true';
break;
case 'separatecompilation':
options.separateCompilation = setting.value === 'true';
break;
case 'suppressimplicitanyindexerrors':
options.suppressImplicitAnyIndexErrors = setting.value === 'true';
break;
case 'includebuiltfile':
inputFiles.push({ unitName: setting.value, content: normalizeLineEndings(IO.readFile(libFolder + setting.value), newLine) });
let builtFileName = libFolder + setting.value;
includeBuiltFiles.push({ unitName: builtFileName, content: normalizeLineEndings(IO.readFile(builtFileName), newLine) });
break;
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
}
});
var fileOutputs: GeneratedFile[] = [];
var programFiles = inputFiles.map(file => file.unitName);
var program = ts.createProgram(programFiles, options, createCompilerHost(inputFiles.concat(otherFiles),
var programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
var program = ts.createProgram(programFiles, options, createCompilerHost(inputFiles.concat(includeBuiltFiles).concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target, useCaseSensitiveFileNames, currentDirectory));
@@ -1291,7 +1300,7 @@ module Harness {
});
var numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
return diagnostic.fileName && isLibraryFile(diagnostic.fileName);
return diagnostic.fileName && (isLibraryFile(diagnostic.fileName) || isBuiltFile(diagnostic.fileName));
});
var numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
@@ -1451,7 +1460,12 @@ module Harness {
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noemitonerror", "noimplicitany", "noresolve", "newline", "newlines", "emitbom", "errortruncation", "usecasesensitivefilenames", "preserveconstenums", "includebuiltfile", "suppressimplicitanyindexerrors", "stripinternal"];
var fileMetadataNames = ["filename", "comments", "declaration", "module",
"nolib", "sourcemap", "target", "out", "outdir", "noemitonerror",
"noimplicitany", "noresolve", "newline", "newlines", "emitbom",
"errortruncation", "usecasesensitivefilenames", "preserveconstenums",
"includebuiltfile", "suppressimplicitanyindexerrors", "stripinternal",
"separatecompilation"];
function extractCompilerSettings(content: string): CompilerSetting[] {
@@ -1689,6 +1703,10 @@ module Harness {
return (Path.getFileName(filePath) === 'lib.d.ts') || (Path.getFileName(filePath) === 'lib.core.d.ts');
}
export function isBuiltFile(filePath: string): boolean {
return filePath.indexOf(Harness.libFolder) === 0;
}
export function getDefaultLibraryFile(): { unitName: string, content: string } {
var libFile = Harness.userSpecifiedroot + Harness.libFolder + "/" + "lib.d.ts";
return {
+3
View File
@@ -336,6 +336,9 @@ module Harness.LanguageService {
getOccurrencesAtPosition(fileName: string, position: number): ts.ReferenceEntry[] {
return unwrapJSONCallResult(this.shim.getOccurrencesAtPosition(fileName, position));
}
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): ts.DocumentHighlights[] {
return unwrapJSONCallResult(this.shim.getDocumentHighlights(fileName, position, JSON.stringify(filesToSearch)));
}
getNavigateToItems(searchValue: string): ts.NavigateToItem[] {
return unwrapJSONCallResult(this.shim.getNavigateToItems(searchValue));
}
+9 -1
View File
@@ -38,7 +38,6 @@ class TypeWriterWalker {
case ts.SyntaxKind.SuperKeyword:
case ts.SyntaxKind.ArrayLiteralExpression:
case ts.SyntaxKind.ObjectLiteralExpression:
case ts.SyntaxKind.PropertyAccessExpression:
case ts.SyntaxKind.ElementAccessExpression:
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.NewExpression:
@@ -53,9 +52,18 @@ class TypeWriterWalker {
case ts.SyntaxKind.PostfixUnaryExpression:
case ts.SyntaxKind.BinaryExpression:
case ts.SyntaxKind.ConditionalExpression:
case ts.SyntaxKind.SpreadElementExpression:
this.log(node, this.getTypeOfNode(node));
break;
case ts.SyntaxKind.PropertyAccessExpression:
for (var current = node; current.kind === ts.SyntaxKind.PropertyAccessExpression; current = current.parent) {
}
if (current.kind !== ts.SyntaxKind.HeritageClauseElement) {
this.log(node, this.getTypeOfNode(node));
}
break;
// Should not change expression status (maybe expressions)
// TODO: Again, ideally should log number and string literals too,
// but to be consistent with the old typeWriter, just log identifiers
+2 -2
View File
@@ -823,7 +823,7 @@ interface RegExp {
*/
test(string: string): boolean;
/** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */
/** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */
source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
@@ -1168,4 +1168,4 @@ interface TypedPropertyDescriptor<T> {
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
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: Function, propertyKey: string | symbol, parameterIndex: number) => void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
+37 -30
View File
@@ -50,26 +50,21 @@ interface SymbolConstructor {
*/
isConcatSpreadable: symbol;
/**
* A Boolean value that if true indicates that an object may be used as a regular expression.
*/
isRegExp: symbol;
/**
* A method that returns the default iterator for an object.Called by the semantics of the
* for-of statement.
* for-of statement.
*/
iterator: symbol;
/**
* A method that converts an object to a corresponding primitive value.Called by the ToPrimitive
* abstract operation.
* abstract operation.
*/
toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built- in method Object.prototype.toString.
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
toStringTag: symbol;
@@ -111,7 +106,7 @@ interface ObjectConstructor {
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
@@ -598,8 +593,6 @@ interface Math {
}
interface RegExp {
[Symbol.isRegExp]: boolean;
/**
* Matches a string with a regular expression, and returns an array containing the results of
* that search.
@@ -631,6 +624,20 @@ interface RegExp {
*/
split(string: string, limit?: number): string[];
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
@@ -3513,27 +3520,27 @@ interface ProxyHandler<T> {
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handeler: ProxyHandler<T>): T
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
declare var Reflect: {
apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
construct(target: Function, argumentsList: ArrayLike<any>): any;
defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
deleteProperty(target: any, propertyKey: PropertyKey): boolean;
enumerate(target: any): IterableIterator<any>;
get(target: any, propertyKey: PropertyKey, receiver?: any): any;
getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
getPrototypeOf(target: any): any;
has(target: any, propertyKey: string): boolean;
has(target: any, propertyKey: symbol): boolean;
isExtensible(target: any): boolean;
ownKeys(target: any): Array<PropertyKey>;
preventExtensions(target: any): boolean;
set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
setPrototypeOf(target: any, proto: any): boolean;
};
declare module Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function enumerate(target: any): IterableIterator<any>;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
/**
* Represents the completion of an asynchronous operation
+28 -4
View File
@@ -68,12 +68,12 @@ module ts.server {
};
}
private processRequest<T extends protocol.Request>(command: string, arguments?: any): T {
private processRequest<T extends protocol.Request>(command: string, args?: any): T {
var request: protocol.Request = {
seq: this.sequence++,
type: "request",
command: command,
arguments: arguments
arguments: args,
command
};
this.writeMessage(JSON.stringify(request));
@@ -104,7 +104,7 @@ module ts.server {
var response: T = JSON.parse(responseBody);
}
catch (e) {
throw new Error("Malformed response: Failed to parse server response: " + lastMessage + ". \r\n Error detailes: " + e.message);
throw new Error("Malformed response: Failed to parse server response: " + lastMessage + ". \r\n Error details: " + e.message);
}
// verify the sequence numbers
@@ -446,6 +446,7 @@ module ts.server {
if (!response.body) {
return undefined;
}
var helpItems: protocol.SignatureHelpItems = response.body;
var span = helpItems.applicableSpan;
var start = this.lineOffsetToPosition(fileName, span.start);
@@ -465,6 +466,29 @@ module ts.server {
}
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.OccurrencesRequest>(CommandNames.Occurrences, args);
var response = this.processResponse<protocol.OccurrencesResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
return {
fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
isWriteAccess: entry.isWriteAccess,
};
});
}
getDocumentHighlights(fileName: string, position: number): DocumentHighlights[] {
throw new Error("Not Implemented Yet.");
}
+8 -2
View File
@@ -458,7 +458,7 @@ module ts.server {
var info = this.filenameToScriptInfo[args.file];
if (info) {
info.setFormatOptions(args.formatOptions);
this.log("Host configuration update for file " + args.file);
this.log("Host configuration update for file " + args.file, "Info");
}
}
else {
@@ -823,7 +823,6 @@ module ts.server {
*/
closeClientFile(filename: string) {
// TODO: tsconfig check
var info = ts.lookUp(this.filenameToScriptInfo, filename);
if (info) {
this.closeOpenFile(info);
@@ -856,6 +855,9 @@ module ts.server {
}
printProjects() {
if (!this.psLogger.isVerbose()) {
return;
}
this.psLogger.startGroup();
for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
var project = this.inferredProjects[i];
@@ -1466,6 +1468,10 @@ module ts.server {
return accum;
}
getLength(): number {
return this.root.charCount();
}
every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number) {
if (!rangeEnd) {
rangeEnd = this.root.charCount();
+44 -1
View File
@@ -165,6 +165,25 @@ declare module ts.server.protocol {
body?: FileSpan[];
}
/**
* Get occurrences request; value of command field is
* "occurrences". Return response giving spans that are relevant
* in the file at a given line and column.
*/
export interface OccurrencesRequest extends FileLocationRequest {
}
export interface OccurrencesResponseItem extends FileSpan {
/**
* True if the occurrence is a write location, false otherwise.
*/
isWriteAccess: boolean;
}
export interface OccurrencesResponse extends Response {
body?: OccurrencesResponseItem[];
}
/**
* Find references request; value of command field is
* "references". Return response giving the file locations that
@@ -405,6 +424,13 @@ declare module ts.server.protocol {
arguments: OpenRequestArgs;
}
/**
* Exit request; value of command field is "exit". Ask the server process
* to exit.
*/
export interface ExitRequest extends Request {
}
/**
* Close request; value of command field is "close". Notify the
* server that the client has closed a previously open file. If
@@ -617,12 +643,29 @@ declare module ts.server.protocol {
* Optional modifiers for the kind (such as 'public').
*/
kindModifiers: string;
/**
* A string that is used for comparing completion items so that they can be ordered. This
* is often the same as the name but may be different in certain circumstances.
*/
sortText: string;
}
/**
* Additional completion entry details, available on demand
*/
export interface CompletionEntryDetails extends CompletionEntry {
export interface CompletionEntryDetails {
/**
* The symbol's name.
*/
name: string;
/**
* The symbol's kind (such as 'className' or 'parameterName').
*/
kind: string;
/**
* Optional modifiers for the kind (such as 'public').
*/
kindModifiers: string;
/**
* Display parts of the symbol (similar to quick info).
*/
+7 -3
View File
@@ -177,6 +177,12 @@ module ts.server {
super(host, logger);
}
exit() {
this.projectService.log("Exiting...","Info");
this.projectService.closeLog();
process.exit(0);
}
listen() {
rl.on('line',(input: string) => {
var message = input.trim();
@@ -184,9 +190,7 @@ module ts.server {
});
rl.on('close',() => {
this.projectService.log("Exiting...");
this.projectService.closeLog();
process.exit(0);
this.exit();
});
}
}
+90 -69
View File
@@ -76,25 +76,27 @@ module ts.server {
}
export module CommandNames {
export var Brace = "brace";
export var Change = "change";
export var Close = "close";
export var Completions = "completions";
export var CompletionDetails = "completionEntryDetails";
export var SignatureHelp = "signatureHelp";
export var Configure = "configure";
export var Definition = "definition";
export var Exit = "exit";
export var Format = "format";
export var Formatonkey = "formatonkey";
export var Geterr = "geterr";
export var NavBar = "navbar";
export var Navto = "navto";
export var Occurrences = "occurrences";
export var Open = "open";
export var Quickinfo = "quickinfo";
export var References = "references";
export var Reload = "reload";
export var Rename = "rename";
export var Saveto = "saveto";
export var Brace = "brace";
export var SignatureHelp = "signatureHelp";
export var Unknown = "unknown";
}
@@ -116,7 +118,7 @@ module ts.server {
constructor(private host: ServerHost, private logger: Logger) {
this.projectService =
new ProjectService(host, logger, (eventName,project,fileName) => {
new ProjectService(host, logger, (eventName, project, fileName) => {
this.handleEvent(eventName, project, fileName);
});
}
@@ -261,7 +263,7 @@ module ts.server {
}
}
getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
getDefinition({ line, offset, file: fileName }: protocol.FileLocationRequestArgs): protocol.FileSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -283,7 +285,37 @@ module ts.server {
}));
}
getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody {
getOccurrences({ line, offset, file: fileName }: protocol.FileLocationRequestArgs): protocol.OccurrencesResponseItem[] {
fileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(fileName);
if (!project) {
throw Errors.NoProject;
}
let { compilerService } = project;
let position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
let occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position);
if (!occurrences) {
return undefined;
}
return occurrences.map(occurrence => {
let { fileName, isWriteAccess, textSpan } = occurrence;
let start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
let end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return {
start,
end,
file: fileName,
isWriteAccess
}
});
}
getRenameLocations({line, offset, file: fileName, findInComments, findInStrings }: protocol.RenameRequestArgs): protocol.RenameResponseBody {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -351,7 +383,7 @@ module ts.server {
return { info: renameInfo, locs: bakedRenameLocs };
}
getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody {
getReferences({ line, offset, file: fileName }: protocol.FileLocationRequestArgs): protocol.ReferencesResponseBody {
// TODO: get all projects for this file; report refs for all projects deleting duplicates
// can avoid duplicates by eliminating same ref file from subsequent projects
var file = ts.normalizePath(fileName);
@@ -377,7 +409,7 @@ module ts.server {
var nameSpan = nameInfo.textSpan;
var nameColStart = compilerService.host.positionToLineOffset(file, nameSpan.start).offset;
var nameText = compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan));
var bakedRefs: protocol.ReferencesResponseItem[] = references.map((ref) => {
var bakedRefs: protocol.ReferencesResponseItem[] = references.map(ref => {
var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start);
var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1);
var snap = compilerService.host.getScriptSnapshot(ref.fileName);
@@ -398,12 +430,12 @@ module ts.server {
};
}
openClientFile(fileName: string) {
openClientFile({ file: fileName }: protocol.OpenRequestArgs) {
var file = ts.normalizePath(fileName);
this.projectService.openClientFile(file);
}
getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
getQuickInfo({ line, offset, file: fileName }: protocol.FileLocationRequestArgs): protocol.QuickInfoResponseBody {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -429,7 +461,7 @@ module ts.server {
};
}
getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] {
getFormattingEditsForRange({line, offset, endLine, endOffset, file: fileName}: protocol.FormatRequestArgs): protocol.CodeEdit[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -456,7 +488,7 @@ module ts.server {
});
}
getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] {
getFormattingEditsAfterKeystroke({line, offset, key, file: fileName}: protocol.FormatOnKeyRequestArgs): protocol.CodeEdit[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -529,7 +561,7 @@ module ts.server {
});
}
getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] {
getCompletions({ line, offset, prefix, file: fileName}: protocol.CompletionsRequestArgs): protocol.CompletionEntry[] {
if (!prefix) {
prefix = "";
}
@@ -555,8 +587,7 @@ module ts.server {
}, []).sort((a, b) => a.name.localeCompare(b.name));
}
getCompletionEntryDetails(line: number, offset: number,
entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] {
getCompletionEntryDetails({ line, offset, entryNames, file: fileName}: protocol.CompletionDetailsRequestArgs): protocol.CompletionEntryDetails[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -575,20 +606,20 @@ module ts.server {
}, []);
}
getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems {
getSignatureHelpItems({ line, offset, file: fileName }: protocol.SignatureHelpRequestArgs): protocol.SignatureHelpItems {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
throw Errors.NoProject;
}
var compilerService = project.compilerService;
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var helpItems = compilerService.languageService.getSignatureHelpItems(file, position);
if (!helpItems) {
return undefined;
}
var span = helpItems.applicableSpan;
var result: protocol.SignatureHelpItems = {
items: helpItems.items,
@@ -600,11 +631,11 @@ module ts.server {
argumentIndex: helpItems.argumentIndex,
argumentCount: helpItems.argumentCount,
}
return result;
}
getDiagnostics(delay: number, fileNames: string[]) {
getDiagnostics({ delay, files: fileNames }: protocol.GeterrRequestArgs): void {
var checkList = fileNames.reduce((accum: PendingErrorCheck[], fileName: string) => {
fileName = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(fileName);
@@ -615,11 +646,11 @@ module ts.server {
}, []);
if (checkList.length > 0) {
this.updateErrorCheck(checkList, this.changeSeq,(n) => n == this.changeSeq, delay)
this.updateErrorCheck(checkList, this.changeSeq, (n) => n == this.changeSeq, delay)
}
}
change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) {
change({ line, offset, endLine, endOffset, insertString, file: fileName }: protocol.ChangeRequestArgs): void {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (project) {
@@ -634,7 +665,7 @@ module ts.server {
}
}
reload(fileName: string, tempFileName: string, reqSeq = 0) {
reload({ file: fileName, tmpfile: tempFileName }: protocol.ReloadRequestArgs, reqSeq = 0): void {
var file = ts.normalizePath(fileName);
var tmpfile = ts.normalizePath(tempFileName);
var project = this.projectService.getProjectForFile(file);
@@ -647,7 +678,7 @@ module ts.server {
}
}
saveToTmp(fileName: string, tempFileName: string) {
saveToTmp({ file: fileName, tmpfile: tempFileName }: protocol.SavetoRequestArgs): void {
var file = ts.normalizePath(fileName);
var tmpfile = ts.normalizePath(tempFileName);
@@ -657,7 +688,7 @@ module ts.server {
}
}
closeClientFile(fileName: string) {
closeClientFile({ file: fileName }: protocol.FileRequestArgs) {
var file = ts.normalizePath(fileName);
this.projectService.closeClientFile(file);
}
@@ -681,7 +712,7 @@ module ts.server {
}));
}
getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] {
getNavigationBarItems({ file: fileName }: protocol.FileRequestArgs): protocol.NavigationBarItem[]{
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -697,7 +728,7 @@ module ts.server {
return this.decorateNavigationBarItem(project, fileName, items);
}
getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] {
getNavigateToItems({ searchValue, file: fileName, maxResultCount }: protocol.NavtoRequestArgs): protocol.NavtoItem[]{
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -736,7 +767,7 @@ module ts.server {
});
}
getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] {
getBraceMatching({ line, offset, file: fileName }: protocol.FileLocationRequestArgs): protocol.TextSpan[]{
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -758,6 +789,9 @@ module ts.server {
}));
}
exit() {
}
onMessage(message: string) {
if (this.logger.isVerbose()) {
this.logger.info("request: " + message);
@@ -769,110 +803,97 @@ module ts.server {
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);
response = this.getDefinition(<protocol.FileLocationRequestArgs>request.arguments);
break;
}
case CommandNames.References: {
var refArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getReferences(refArgs.line, refArgs.offset, refArgs.file);
response = this.getReferences(<protocol.FileLocationRequestArgs>request.arguments);
break;
}
case CommandNames.Rename: {
var renameArgs = <protocol.RenameRequestArgs>request.arguments;
response = this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings);
response = this.getRenameLocations(<protocol.RenameRequestArgs>request.arguments);
break;
}
case CommandNames.Open: {
var openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file);
this.openClientFile(<protocol.OpenRequestArgs>request.arguments);
responseRequired = false;
break;
}
case CommandNames.Quickinfo: {
var quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file);
response = this.getQuickInfo(<protocol.FileLocationRequestArgs>request.arguments);
break;
}
case CommandNames.Format: {
var formatArgs = <protocol.FormatRequestArgs>request.arguments;
response = this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file);
response = this.getFormattingEditsForRange(<protocol.FormatRequestArgs>request.arguments);
break;
}
case CommandNames.Formatonkey: {
var formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments;
response = this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file);
response = this.getFormattingEditsAfterKeystroke(<protocol.FormatOnKeyRequestArgs>request.arguments);
break;
}
case CommandNames.Completions: {
var completionsArgs = <protocol.CompletionsRequestArgs>request.arguments;
response = this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file);
response = this.getCompletions(<protocol.CompletionsRequestArgs>request.arguments);
break;
}
case CommandNames.CompletionDetails: {
var completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments;
response =
this.getCompletionEntryDetails(completionDetailsArgs.line,completionDetailsArgs.offset,
completionDetailsArgs.entryNames,completionDetailsArgs.file);
response = this.getCompletionEntryDetails(<protocol.CompletionDetailsRequestArgs>request.arguments);
break;
}
case CommandNames.SignatureHelp: {
var signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments;
response = this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file);
response = this.getSignatureHelpItems(<protocol.SignatureHelpRequestArgs>request.arguments);
break;
}
case CommandNames.Geterr: {
var geterrArgs = <protocol.GeterrRequestArgs>request.arguments;
response = this.getDiagnostics(geterrArgs.delay, geterrArgs.files);
this.getDiagnostics(<protocol.GeterrRequestArgs>request.arguments);
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);
this.change(<protocol.ChangeRequestArgs>request.arguments);
responseRequired = false;
break;
}
case CommandNames.Configure: {
var configureArgs = <protocol.ConfigureRequestArguments>request.arguments;
this.projectService.setHostConfiguration(configureArgs);
this.projectService.setHostConfiguration(<protocol.ConfigureRequestArguments>request.arguments);
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);
this.reload(<protocol.ReloadRequestArgs>request.arguments);
responseRequired = false;
break;
}
case CommandNames.Saveto: {
var savetoArgs = <protocol.SavetoRequestArgs>request.arguments;
this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
this.saveToTmp(<protocol.SavetoRequestArgs>request.arguments);
responseRequired = false;
break;
}
case CommandNames.Close: {
var closeArgs = <protocol.FileRequestArgs>request.arguments;
this.closeClientFile(closeArgs.file);
this.closeClientFile(<protocol.FileRequestArgs>request.arguments);
responseRequired = false;
break;
}
case CommandNames.Navto: {
var navtoArgs = <protocol.NavtoRequestArgs>request.arguments;
response = this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount);
response = this.getNavigateToItems(<protocol.NavtoRequestArgs>request.arguments);
break;
}
case CommandNames.Brace: {
var braceArguments = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file);
response = this.getBraceMatching(<protocol.FileLocationRequestArgs>request.arguments);
break;
}
case CommandNames.NavBar: {
var navBarArgs = <protocol.FileRequestArgs>request.arguments;
response = this.getNavigationBarItems(navBarArgs.file);
response = this.getNavigationBarItems(<protocol.FileRequestArgs>request.arguments);
break;
}
case CommandNames.Occurrences: {
response = this.getOccurrences(<protocol.FileLocationRequestArgs>request.arguments);
break;
}
default: {
+1 -4
View File
@@ -3,6 +3,7 @@
/// <reference path='services.ts' />
/* @internal */
module ts.BreakpointResolver {
/**
* Get the breakpoint span in given sourceFile
@@ -173,10 +174,6 @@ module ts.BreakpointResolver {
return textSpan(node, (<ThrowStatement>node).expression);
case SyntaxKind.ExportAssignment:
if (!(<ExportAssignment>node).expression) {
return undefined;
}
// span on export = id
return textSpan(node, (<ExportAssignment>node).expression);
+20 -7
View File
@@ -3,6 +3,7 @@
///<reference path='rulesProvider.ts' />
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export interface TextRangeWithKind extends TextRange {
@@ -328,8 +329,13 @@ module ts.formatting {
if (formattingScanner.isOnToken()) {
let startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
let undecoratedStartLine = startLine;
if (enclosingNode.decorators) {
undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
}
let delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile);
processNode(enclosingNode, enclosingNode, startLine, initialIndentation, delta);
processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
}
formattingScanner.close();
@@ -500,7 +506,7 @@ module ts.formatting {
}
}
function processNode(node: Node, contextNode: Node, nodeStartLine: number, indentation: number, delta: number) {
function processNode(node: Node, contextNode: Node, nodeStartLine: number, undecoratedNodeStartLine: number, indentation: number, delta: number) {
if (!rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
return;
}
@@ -526,7 +532,7 @@ module ts.formatting {
forEachChild(
node,
child => {
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, /*isListElement*/ false)
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false)
},
(nodes: NodeArray<Node>) => {
processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
@@ -547,11 +553,17 @@ module ts.formatting {
parent: Node,
parentDynamicIndentation: DynamicIndentation,
parentStartLine: number,
undecoratedParentStartLine: number,
isListItem: boolean): number {
let childStartPos = child.getStart(sourceFile);
let childStart = sourceFile.getLineAndCharacterOfPosition(childStartPos);
let childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
let undecoratedChildStartLine = childStartLine;
if (child.decorators) {
undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
}
// if child is a list item - try to get its indentation
let childIndentationAmount = Constants.Unknown;
@@ -594,9 +606,10 @@ module ts.formatting {
return inheritedIndentation;
}
let childIndentation = computeIndentation(child, childStart.line, childIndentationAmount, node, parentDynamicIndentation, parentStartLine);
let effectiveParentStartLine = child.kind === SyntaxKind.Decorator ? childStartLine : undecoratedParentStartLine;
let childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
processNode(child, childContextNode, childStart.line, childIndentation.indentation, childIndentation.delta);
processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
childContextNode = node;
@@ -640,7 +653,7 @@ module ts.formatting {
let inheritedIndentation = Constants.Unknown;
for (let child of nodes) {
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, /*isListElement*/ true)
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true)
}
if (listEndToken !== SyntaxKind.Unknown) {
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// <reference path="references.ts"/>
/* @internal */
module ts.formatting {
export class FormattingContext {
public currentTokenSpan: TextRangeWithKind;
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// <reference path="references.ts"/>
/* @internal */
module ts.formatting {
export const enum FormattingRequestKind {
FormatDocument,
@@ -1,6 +1,7 @@
/// <reference path="formatting.ts"/>
/// <reference path="..\..\compiler\scanner.ts"/>
/* @internal */
module ts.formatting {
let scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false);
-15
View File
@@ -1,18 +1,3 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='..\services.ts' />
///<reference path='formattingContext.ts' />
///<reference path='formattingRequestKind.ts' />
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export class Rule {
constructor(
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export const enum RuleAction {
Ignore = 0x00000001,
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export class RuleDescriptor {
constructor(public LeftTokenRange: Shared.TokenRange, public RightTokenRange: Shared.TokenRange) {
+2 -15
View File
@@ -1,20 +1,7 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export const enum RuleFlags {
None,
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export class RuleOperation {
public Context: RuleOperationContext;
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export class RuleOperationContext {
+29 -16
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export class Rules {
public getRuleName(rule: Rule) {
@@ -208,6 +194,11 @@ module ts.formatting {
public SpaceAfterAnonymousFunctionKeyword: Rule;
public NoSpaceAfterAnonymousFunctionKeyword: Rule;
// Insert space after @ in decorator
public SpaceBeforeAt: Rule;
public NoSpaceAfterAt: Rule;
public SpaceAfterDecorator: Rule;
constructor() {
///
/// Common Rules
@@ -344,6 +335,11 @@ module ts.formatting {
// Remove spaces in empty interface literals. e.g.: x: {}
this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), RuleAction.Delete));
// decorators
this.SpaceBeforeAt = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.AtToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterAt = new Rule(RuleDescriptor.create3(SyntaxKind.AtToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterDecorator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.ExportKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.ClassKeyword, SyntaxKind.StaticKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.OpenBracketToken, SyntaxKind.AsteriskToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), RuleAction.Space));
// These rules are higher in priority than user-configurable rules.
this.HighPriorityCommonRules =
[
@@ -381,7 +377,10 @@ module ts.formatting {
this.NoSpaceBetweenCloseParenAndAngularBracket,
this.NoSpaceAfterOpenAngularBracket,
this.NoSpaceBeforeCloseAngularBracket,
this.NoSpaceAfterCloseAngularBracket
this.NoSpaceAfterCloseAngularBracket,
this.SpaceBeforeAt,
this.NoSpaceAfterAt,
this.SpaceAfterDecorator,
];
// These rules are lower in priority than user-configurable rules.
@@ -649,6 +648,20 @@ module ts.formatting {
return context.TokensAreOnSameLine();
}
static IsEndOfDecoratorContextOnSameLine(context: FormattingContext): boolean {
return context.TokensAreOnSameLine() &&
context.contextNode.decorators &&
Rules.NodeIsInDecoratorContext(context.currentTokenParent) &&
!Rules.NodeIsInDecoratorContext(context.nextTokenParent);
}
static NodeIsInDecoratorContext(node: Node): boolean {
while (isExpression(node)) {
node = node.parent;
}
return node.kind === SyntaxKind.Decorator;
}
static IsStartOfVariableDeclarationList(context: FormattingContext): boolean {
return context.currentTokenParent.kind === SyntaxKind.VariableDeclarationList &&
context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export class RulesMap {
public map: RulesBucket[];
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// <reference path="references.ts"/>
/* @internal */
module ts.formatting {
export class RulesProvider {
private globalRules: Rules;
+1
View File
@@ -1,5 +1,6 @@
///<reference path='..\services.ts' />
/* @internal */
module ts.formatting {
export module SmartIndenter {
+1 -15
View File
@@ -1,20 +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
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
/* @internal */
module ts.formatting {
export module Shared {
export interface ITokenAccess {
+2 -1
View File
@@ -1,3 +1,4 @@
/* @internal */
module ts.NavigateTo {
type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration };
@@ -22,7 +23,7 @@ module ts.NavigateTo {
continue;
}
// It was a match! If the pattern has dots in it, then also see if hte
// It was a match! If the pattern has dots in it, then also see if the
// declaration container matches as well.
if (patternMatcher.patternContainsDots) {
let containers = getContainers(declaration);
+4 -3
View File
@@ -1,5 +1,6 @@
/// <reference path='services.ts' />
/* @internal */
module ts.NavigationBar {
export function getNavigationBarItems(sourceFile: SourceFile): ts.NavigationBarItem[] {
// If the source file has any child items, then it included in the tree
@@ -418,10 +419,10 @@ module ts.NavigationBar {
}
function createFunctionItem(node: FunctionDeclaration) {
if ((node.name || node.flags & NodeFlags.Default) && node.body && node.body.kind === SyntaxKind.Block) {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
return getNavigationBarItem((!node.name && node.flags & NodeFlags.Default) ? "default": node.name.text ,
return getNavigationBarItem(!node.name ? "default": node.name.text ,
ts.ScriptElementKind.functionElement,
getNodeModifiers(node),
[getNodeSpan(node)],
@@ -470,7 +471,7 @@ module ts.NavigationBar {
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
var nodeName = !node.name && (node.flags & NodeFlags.Default) ? "default" : node.name.text;
var nodeName = !node.name ? "default" : node.name.text;
return getNavigationBarItem(
nodeName,
+179 -128
View File
@@ -1,129 +1,180 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
module ts {
export module OutliningElementsCollector {
export function collectElements(sourceFile: SourceFile): OutliningSpan[] {
let elements: OutliningSpan[] = [];
let collapseText = "...";
function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) {
if (hintSpanNode && startElement && endElement) {
let span: OutliningSpan = {
textSpan: createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function autoCollapse(node: Node) {
return isFunctionBlock(node) && node.parent.kind !== SyntaxKind.ArrowFunction;
}
let depth = 0;
let maxDepth = 20;
function walk(n: Node): void {
if (depth > maxDepth) {
return;
}
switch (n.kind) {
case SyntaxKind.Block:
if (!isFunctionBlock(n)) {
let parent = n.parent;
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collaps the block, but consider its hint span
// to be the entire span of the parent.
if (parent.kind === SyntaxKind.DoStatement ||
parent.kind === SyntaxKind.ForInStatement ||
parent.kind === SyntaxKind.ForOfStatement ||
parent.kind === SyntaxKind.ForStatement ||
parent.kind === SyntaxKind.IfStatement ||
parent.kind === SyntaxKind.WhileStatement ||
parent.kind === SyntaxKind.WithStatement ||
parent.kind === SyntaxKind.CatchClause) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
if (parent.kind === SyntaxKind.TryStatement) {
// Could be the try-block, or the finally-block.
let tryStatement = <TryStatement>parent;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
let finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
}
// fall through.
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
let span = createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
// Fallthrough.
case SyntaxKind.ModuleBlock: {
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
}
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.CaseBlock: {
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
case SyntaxKind.ArrayLiteralExpression:
let openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile);
let closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
}
depth++;
forEachChild(n, walk);
depth--;
}
walk(sourceFile);
return elements;
}
}
/* @internal */
module ts {
export module OutliningElementsCollector {
export function collectElements(sourceFile: SourceFile): OutliningSpan[] {
let elements: OutliningSpan[] = [];
let collapseText = "...";
function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) {
if (hintSpanNode && startElement && endElement) {
let span: OutliningSpan = {
textSpan: createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function addOutliningSpanComments(commentSpan: CommentRange, autoCollapse: boolean) {
if (commentSpan) {
let span: OutliningSpan = {
textSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function addOutliningForLeadingCommentsForNode(n: Node) {
let comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
if (comments) {
let firstSingleLineCommentStart = -1;
let lastSingleLineCommentEnd = -1;
let isFirstSingleLineComment = true;
let singleLineCommentCount = 0;
for (let currentComment of comments) {
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === SyntaxKind.SingleLineCommentTrivia) {
if (isFirstSingleLineComment) {
firstSingleLineCommentStart = currentComment.pos;
}
isFirstSingleLineComment = false;
lastSingleLineCommentEnd = currentComment.end;
singleLineCommentCount++;
}
else if (currentComment.kind === SyntaxKind.MultiLineCommentTrivia) {
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
addOutliningSpanComments(currentComment, /*autoCollapse*/ false);
singleLineCommentCount = 0;
lastSingleLineCommentEnd = -1;
isFirstSingleLineComment = true;
}
}
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
}
}
function combineAndAddMultipleSingleLineComments(count: number, start: number, end: number) {
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
let multipleSingleLineComments = {
pos: start,
end: end,
kind: SyntaxKind.SingleLineCommentTrivia
}
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
function autoCollapse(node: Node) {
return isFunctionBlock(node) && node.parent.kind !== SyntaxKind.ArrowFunction;
}
let depth = 0;
let maxDepth = 20;
function walk(n: Node): void {
if (depth > maxDepth) {
return;
}
if (isDeclaration(n)) {
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
case SyntaxKind.Block:
if (!isFunctionBlock(n)) {
let parent = n.parent;
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collaps the block, but consider its hint span
// to be the entire span of the parent.
if (parent.kind === SyntaxKind.DoStatement ||
parent.kind === SyntaxKind.ForInStatement ||
parent.kind === SyntaxKind.ForOfStatement ||
parent.kind === SyntaxKind.ForStatement ||
parent.kind === SyntaxKind.IfStatement ||
parent.kind === SyntaxKind.WhileStatement ||
parent.kind === SyntaxKind.WithStatement ||
parent.kind === SyntaxKind.CatchClause) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
if (parent.kind === SyntaxKind.TryStatement) {
// Could be the try-block, or the finally-block.
let tryStatement = <TryStatement>parent;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
let finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
}
// fall through.
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
let span = createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
// Fallthrough.
case SyntaxKind.ModuleBlock: {
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
}
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.CaseBlock: {
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
case SyntaxKind.ArrayLiteralExpression:
let openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile);
let closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
}
depth++;
forEachChild(n, walk);
depth--;
}
walk(sourceFile);
return elements;
}
}
}
+2 -1
View File
@@ -1,3 +1,4 @@
/* @internal */
module ts {
// Note(cyrusn): this enum is ordered from strongest match type to weakest match type.
export enum PatternMatchKind {
@@ -471,7 +472,7 @@ module ts {
// Helper function to compare two matches to determine which is better. Matches are first
// ordered by kind (so all prefix matches always beat all substring matches). Then, if the
// match is a camel case match, the relative weights of hte match are used to determine
// match is a camel case match, the relative weights of the match are used to determine
// which is better (with a greater weight being better). Then if the match is of the same
// type, then a case sensitive match is considered better than an insensitive one.
function patternMatchCompareTo(match1: PatternMatch, match2: PatternMatch): number {
+1182 -737
View File
File diff suppressed because it is too large Load Diff
+38 -12
View File
@@ -15,8 +15,10 @@
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = (<any>this);
/* @internal */
module ts {
export interface ScriptSnapshotShim {
/** Gets a portion of the script snapshot specified by [start, end). */
@@ -135,11 +137,21 @@ module ts {
findReferences(fileName: string, position: number): string;
/**
* @deprecated
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
*/
getOccurrencesAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; highlights: { start: number; length: number, isDefinition: boolean }[] }[]
*
* @param fileToSearch A JSON encoded string[] containing the file names that should be
* considered when searching.
*/
getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string;
/**
* Returns a JSON-encoded value of the type:
* { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; textSpan: { start: number; length: number}; } [] = [];
@@ -331,6 +343,21 @@ module ts {
}
}
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; } []{
return diagnostics.map(d => realizeDiagnostic(d, newLine));
}
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; } {
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
/// TODO: no need for the tolowerCase call
category: DiagnosticCategory[diagnostic.category].toLowerCase(),
code: diagnostic.code
};
}
class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim {
private logger: Logger;
@@ -391,18 +418,7 @@ module ts {
private realizeDiagnostics(diagnostics: Diagnostic[]): { message: string; start: number; length: number; category: string; }[]{
var newLine = this.getNewLine();
return diagnostics.map(d => this.realizeDiagnostic(d, newLine));
}
private realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; } {
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
/// TODO: no need for the tolowerCase call
category: DiagnosticCategory[diagnostic.category].toLowerCase(),
code: diagnostic.code
};
return ts.realizeDiagnostics(diagnostics, newLine);
}
public getSyntacticClassifications(fileName: string, start: number, length: number): string {
@@ -585,6 +601,14 @@ module ts {
});
}
public getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string {
return this.forwardJSONCall(
"getDocumentHighlights('" + fileName + "', " + position + ")",
() => {
return this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
});
}
/// COMPLETION LISTS
/**
@@ -839,8 +863,10 @@ module ts {
/// TODO: this is used by VS, clean this up on both sides of the interface
/* @internal */
module TypeScript.Services {
export var TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
}
/* @internal */
let toolsVersion = "1.4";
+1 -1
View File
@@ -1,5 +1,5 @@
///<reference path='services.ts' />
/* @internal */
module ts.SignatureHelp {
// A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression
+2
View File
@@ -1,4 +1,5 @@
// These utilities are common to multiple language service features.
/* @internal */
module ts {
export interface ListItemInfo {
listItemIndex: number;
@@ -500,6 +501,7 @@ module ts {
}
// Display-part writer helpers
/* @internal */
module ts {
export function isFirstDeclarationOfSymbolParameter(symbol: Symbol) {
return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === SyntaxKind.Parameter;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,12 +1,18 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,6): error TS2461: Type 'string | number' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,7): error TS2322: Type 'number' is not assignable to type 'string'.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,14): error TS2322: Type 'string' is not assignable to type 'number'.
==== tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts (1 errors) ====
==== tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts (3 errors) ====
var a: string, b: number;
var tuple: [number, string] = [2, "3"];
for ([a = 1, b = ""] of tuple) {
~~~~~~~~~~~~~~~
!!! error TS2461: Type 'string | number' is not an array type.
~
!!! error TS2322: Type 'number' is not assignable to type 'string'.
~
!!! error TS2322: Type 'string' is not assignable to type 'number'.
a;
b;
}
@@ -14,6 +14,7 @@ obj[Symbol.foo];
var Symbol;
var obj = (_a = {},
_a[Symbol.foo] = 0,
_a);
_a
);
obj[Symbol.foo];
var _a;
@@ -2,7 +2,5 @@
var v = { [yield]: foo }
//// [FunctionDeclaration8_es6.js]
var v = (_a = {},
_a[yield] = foo,
_a);
var v = (_a = {}, _a[yield] = foo, _a);
var _a;
@@ -5,8 +5,6 @@ function * foo() {
//// [FunctionDeclaration9_es6.js]
function foo() {
var v = (_a = {},
_a[] = foo,
_a);
var v = (_a = {}, _a[yield] = foo, _a);
var _a;
}
@@ -2,7 +2,5 @@
var v = { *[foo()]() { } }
//// [FunctionPropertyAssignments5_es6.js]
var v = (_a = {},
_a[foo()] = function () { },
_a);
var v = (_a = {}, _a[foo()] = function () { }, _a);
var _a;
@@ -7,6 +7,6 @@ var v = { * foo() {
//// [YieldExpression10_es6.js]
var v = { foo: function () {
;
yield (foo);
}
};
@@ -10,7 +10,7 @@ var C = (function () {
function C() {
}
C.prototype.foo = function () {
;
yield (foo);
};
return C;
})();
@@ -8,7 +8,7 @@ class C {
//// [YieldExpression12_es6.js]
var C = (function () {
function C() {
;
yield foo;
}
return C;
})();
@@ -2,4 +2,4 @@
function* foo() { yield }
//// [YieldExpression13_es6.js]
function foo() { ; }
function foo() { yield; }
@@ -10,7 +10,7 @@ var C = (function () {
function C() {
}
C.prototype.foo = function () {
;
yield foo;
};
return C;
})();
@@ -5,5 +5,5 @@ var v = () => {
//// [YieldExpression15_es6.js]
var v = function () {
;
yield foo;
};
@@ -8,6 +8,6 @@ function* foo() {
//// [YieldExpression16_es6.js]
function foo() {
function bar() {
;
yield foo;
}
}
@@ -2,4 +2,4 @@
var v = { get foo() { yield foo; } }
//// [YieldExpression17_es6.js]
var v = { get foo() { ; } };
var v = { get foo() { yield foo; } };
@@ -4,4 +4,4 @@ yield(foo);
//// [YieldExpression18_es6.js]
"use strict";
;
yield (foo);
@@ -11,7 +11,7 @@ function*foo() {
function foo() {
function bar() {
function quux() {
;
yield (foo);
}
}
}
@@ -2,4 +2,4 @@
yield foo;
//// [YieldExpression2_es6.js]
;
yield foo;
@@ -6,6 +6,6 @@ function* foo() {
//// [YieldExpression3_es6.js]
function foo() {
;
;
yield;
yield;
}
@@ -6,6 +6,6 @@ function* foo() {
//// [YieldExpression4_es6.js]
function foo() {
;
;
yield;
yield;
}
@@ -5,5 +5,5 @@ function* foo() {
//// [YieldExpression5_es6.js]
function foo() {
;
yield* ;
}
@@ -5,5 +5,5 @@ function* foo() {
//// [YieldExpression6_es6.js]
function foo() {
;
yield* foo;
}
@@ -5,5 +5,5 @@ function* foo() {
//// [YieldExpression7_es6.js]
function foo() {
;
yield foo;
}
@@ -7,5 +7,5 @@ function* foo() {
//// [YieldExpression8_es6.js]
yield(foo);
function foo() {
;
yield (foo);
}
@@ -5,5 +5,5 @@ var v = function*() {
//// [YieldExpression9_es6.js]
var v = function () {
;
yield (foo);
};
@@ -52,7 +52,7 @@ import Backbone = require("aliasUsage1_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone : unknown
>Backbone : typeof Backbone
>Model : Backbone.Model
// interesting stuff here
@@ -40,7 +40,7 @@ import Backbone = require("aliasUsageInArray_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone : unknown
>Backbone : typeof Backbone
>Model : Backbone.Model
// interesting stuff here
@@ -41,7 +41,7 @@ import Backbone = require("aliasUsageInFunctionExpression_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone : unknown
>Backbone : typeof Backbone
>Model : Backbone.Model
// interesting stuff here
@@ -55,7 +55,7 @@ import Backbone = require("aliasUsageInGenericFunction_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone : unknown
>Backbone : typeof Backbone
>Model : Backbone.Model
// interesting stuff here

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