Merge branch 'master' into moveTypeSerializationToEmitter

This commit is contained in:
Ron Buckton
2015-07-10 13:18:56 -07:00
642 changed files with 13638 additions and 3200 deletions
+33 -9
View File
@@ -361,7 +361,7 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
/*keepComments*/ true,
/*noResolve*/ false,
/*stripInternal*/ true,
/*callback*/ function () {
/*callback*/ function () {
jake.cpR(servicesFile, nodePackageFile, {silent: true});
prependFile(copyright, standaloneDefinitionsFile);
@@ -379,12 +379,12 @@ compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(se
var lsslFile = path.join(builtLocalDirectory, "tslssl.js");
compileFile(
lsslFile,
languageServiceLibrarySources,
lsslFile,
languageServiceLibrarySources,
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ true);
// Local target to build the language service server library
@@ -488,7 +488,7 @@ var refTest262Baseline = path.join(internalTests, "baselines/test262/reference")
desc("Builds the test infrastructure using the built compiler");
task("tests", ["local", run].concat(libraryTargets));
function exec(cmd, completeHandler) {
function exec(cmd, completeHandler, errorHandler) {
var ex = jake.createExec([cmd], {windowsVerbatimArguments: true});
// Add listeners for output and error
ex.addListener("stdout", function(output) {
@@ -504,8 +504,12 @@ function exec(cmd, completeHandler) {
complete();
});
ex.addListener("error", function(e, status) {
fail("Process exited with code " + status);
})
if(errorHandler) {
errorHandler(e, status);
} else {
fail("Process exited with code " + status);
}
});
ex.run();
}
@@ -715,3 +719,23 @@ task('tsc-instrumented', [loggedIOJsPath, instrumenterJsPath, tscFile], function
});
ex.run();
}, { async: true });
desc("Updates the sublime plugin's tsserver");
task("update-sublime", ["local", serverFile], function() {
jake.cpR(serverFile, "../TypeScript-Sublime-Plugin/tsserver/");
jake.cpR(serverFile + ".map", "../TypeScript-Sublime-Plugin/tsserver/");
});
// if the codebase were free of linter errors we could make jake runtests
// run this task automatically
desc("Runs tslint on the compiler sources");
task("lint", [], function() {
for(var i in compilerSources) {
var f = compilerSources[i];
var cmd = 'tslint -f ' + f;
exec(cmd,
function() { console.log('SUCCESS: No linter errors'); },
function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n');
});
}
}, { async: true });
+2 -1
View File
@@ -33,7 +33,8 @@
"mocha": "latest",
"chai": "latest",
"browserify": "latest",
"istanbul": "latest"
"istanbul": "latest",
"tslint": "latest"
},
"scripts": {
"test": "jake runtests"
+66 -67
View File
@@ -4,84 +4,83 @@ let async = require('async');
let glob = require('glob');
fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => {
if (err) {
throw err;
}
let messages = JSON.parse(data);
let keys = Object.keys(messages);
console.log('Loaded ' + keys.length + ' errors');
if (err) {
throw err;
}
for (let k of keys) {
messages[k]['seen'] = false;
}
let messages = JSON.parse(data);
let keys = Object.keys(messages);
console.log('Loaded ' + keys.length + ' errors');
let errRegex = /\(\d+,\d+\): error TS([^:]+):/g;
for (let k of keys) {
messages[k]['seen'] = false;
}
let baseDir = 'tests/baselines/reference/';
fs.readdir(baseDir, (err, files) => {
files = files.filter(f => f.indexOf('.errors.txt') > 0);
let tasks: Array<(callback: () => void) => void> = [];
files.forEach(f => tasks.push(done => {
fs.readFile(baseDir + f, 'utf-8', (err, baseline) => {
if (err) throw err;
let errRegex = /\(\d+,\d+\): error TS([^:]+):/g;
let g: string[];
while (g = errRegex.exec(baseline)) {
var errCode = +g[1];
let msg = keys.filter(k => messages[k].code === errCode)[0];
messages[msg]['seen'] = true;
}
let baseDir = 'tests/baselines/reference/';
fs.readdir(baseDir, (err, files) => {
files = files.filter(f => f.indexOf('.errors.txt') > 0);
let tasks: Array<(callback: () => void) => void> = [];
files.forEach(f => tasks.push(done => {
fs.readFile(baseDir + f, 'utf-8', (err, baseline) => {
if (err) throw err;
done();
});
}));
let g: string[];
while (g = errRegex.exec(baseline)) {
var errCode = +g[1];
let msg = keys.filter(k => messages[k].code === errCode)[0];
messages[msg]['seen'] = true;
}
async.parallelLimit(tasks, 25, done => {
console.log('== List of errors not present in baselines ==');
let count = 0;
for (let k of keys) {
if (messages[k]['seen'] !== true) {
console.log(k);
count++;
}
}
console.log(count + ' of ' + keys.length + ' errors are not in baselines');
});
});
done();
});
}));
async.parallelLimit(tasks, 25, done => {
console.log('== List of errors not present in baselines ==');
let count = 0;
for (let k of keys) {
if (messages[k]['seen'] !== true) {
console.log(k);
count++;
}
}
console.log(count + ' of ' + keys.length + ' errors are not in baselines');
});
});
});
fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, data) => {
let errorRegexp = /\s(\w+): \{ code/g;
let errorNames: string[] = [];
let errMatch: string[];
while (errMatch = errorRegexp.exec(data)) {
errorNames.push(errMatch[1]);
}
let errorRegexp = /\s(\w+): \{ code/g;
let errorNames: string[] = [];
let errMatch: string[];
while (errMatch = errorRegexp.exec(data)) {
errorNames.push(errMatch[1]);
}
let allSrc: string = '';
glob('./src/**/*.ts', {}, (err, files) => {
console.log('Reading ' + files.length + ' source files');
for(let file of files) {
if (file.indexOf('diagnosticInformationMap.generated.ts') > 0) {
continue;
}
let allSrc: string = '';
glob('./src/**/*.ts', {}, (err, files) => {
console.log('Reading ' + files.length + ' source files');
for (let file of files) {
if (file.indexOf('diagnosticInformationMap.generated.ts') > 0) {
continue;
}
let src = fs.readFileSync(file, 'utf-8');
allSrc = allSrc + src;
}
let src = fs.readFileSync(file, 'utf-8');
allSrc = allSrc + src;
}
console.log('Consumed ' + allSrc.length + ' characters of source');
console.log('Consumed ' + allSrc.length + ' characters of source');
let count = 0;
console.log('== List of errors not used in source ==')
for(let errName of errorNames) {
if (allSrc.indexOf(errName) < 0) {
console.log(errName);
count++;
}
}
console.log(count + ' of ' + errorNames.length + ' errors are not used in source');
});
let count = 0;
console.log('== List of errors not used in source ==');
for (let errName of errorNames) {
if (allSrc.indexOf(errName) < 0) {
console.log(errName);
count++;
}
}
console.log(count + ' of ' + errorNames.length + ' errors are not used in source');
});
});
+51 -39
View File
@@ -11,7 +11,7 @@ namespace ts {
}
export function getModuleInstanceState(node: Node): ModuleInstanceState {
// A module is uninstantiated if it contains only
// A module is uninstantiated if it contains only
// 1. interface declarations, type alias declarations
if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) {
return ModuleInstanceState.NonInstantiated;
@@ -53,7 +53,7 @@ namespace ts {
}
const enum ContainerFlags {
// The current node is not a container, and no container manipulation should happen before
// The current node is not a container, and no container manipulation should happen before
// recursing into it.
None = 0,
@@ -90,13 +90,13 @@ namespace ts {
let lastContainer: Node;
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
let inStrictMode = !!file.externalModuleIndicator;
let symbolCount = 0;
let Symbol = objectAllocator.getSymbolConstructor();
let classifiableNames: Map<string> = {};
let classifiableNames: Map<string> = {};
if (!file.locals) {
bind(file);
@@ -173,6 +173,14 @@ namespace ts {
return node.name ? declarationNameToString(node.name) : getDeclarationName(node);
}
/**
* Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
* @param symbolTable - The symbol table which node will be added to.
* @param parent - node's parent declaration.
* @param node - The declaration to be added to the symbol table
* @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
* @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
*/
function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol {
Debug.assert(!hasDynamicName(node));
@@ -181,15 +189,16 @@ namespace ts {
let symbol: Symbol;
if (name !== undefined) {
// Check and see if the symbol table already has a symbol with this name. If not,
// create a new symbol with this name and add it to the table. Note that we don't
// give the new symbol any flags *yet*. This ensures that it will not conflict
// witht he 'excludes' flags we pass in.
// give the new symbol any flags *yet*. This ensures that it will not conflict
// with the 'excludes' flags we pass in.
//
// If we do get an existing symbol, see if it conflicts with the new symbol we're
// creating. For example, a 'var' symbol and a 'class' symbol will conflict within
// the same symbol table. If we have a conflict, report the issue on each
// declaration we have for this symbol, and then create a new symbol for this
// the same symbol table. If we have a conflict, report the issue on each
// declaration we have for this symbol, and then create a new symbol for this
// declaration.
//
// If we created a new symbol, either because we didn't have a symbol with this name
@@ -202,10 +211,10 @@ namespace ts {
symbol = hasProperty(symbolTable, name)
? symbolTable[name]
: (symbolTable[name] = createSymbol(SymbolFlags.None, name));
if (name && (includes & SymbolFlags.Classifiable)) {
classifiableNames[name] = name;
}
classifiableNames[name] = name;
}
if (symbol.flags & excludes) {
if (node.name) {
@@ -250,7 +259,7 @@ namespace ts {
// ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
// on it. There are 2 main reasons:
//
// 1. We treat locals and exports of the same name as mutually exclusive within a container.
// 1. We treat locals and exports of the same name as mutually exclusive within a container.
// That means the binder will issue a Duplicate Identifier error if you mix locals and exports
// with the same name in the same container.
// TODO: Make this a more specific error and decouple it from the exclusion logic.
@@ -273,11 +282,11 @@ namespace ts {
}
}
// All container nodes are kept on a linked list in declaration order. This list is used by
// the getLocalNameOfContainer function in the type checker to validate that the local name
// All container nodes are kept on a linked list in declaration order. This list is used by
// the getLocalNameOfContainer function in the type checker to validate that the local name
// used for a container is unique.
function bindChildren(node: Node) {
// Before we recurse into a node's chilren, we first save the existing parent, container
// Before we recurse into a node's chilren, we first save the existing parent, container
// and block-container. Then after we pop out of processing the children, we restore
// these saved values.
let saveParent = parent;
@@ -286,16 +295,16 @@ namespace ts {
// This node will now be set as the parent of all of its children as we recurse into them.
parent = node;
// Depending on what kind of node this is, we may have to adjust the current container
// and block-container. If the current node is a container, then it is automatically
// considered the current block-container as well. Also, for containers that we know
// may contain locals, we proactively initialize the .locals field. We do this because
// it's highly likely that the .locals will be needed to place some child in (for example,
// a parameter, or variable declaration).
//
//
// However, we do not proactively create the .locals for block-containers because it's
// totally normal and common for block-containers to never actually have a block-scoped
// totally normal and common for block-containers to never actually have a block-scoped
// variable in them. We don't want to end up allocating an object for every 'block' we
// run into when most of them won't be necessary.
//
@@ -314,6 +323,7 @@ namespace ts {
addToContainerChain(container);
}
else if (containerFlags & ContainerFlags.IsBlockScopedContainer) {
blockScopeContainer = node;
blockScopeContainer.locals = undefined;
@@ -335,7 +345,7 @@ namespace ts {
case SyntaxKind.TypeLiteral:
case SyntaxKind.ObjectLiteralExpression:
return ContainerFlags.IsContainer;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
@@ -363,7 +373,7 @@ namespace ts {
case SyntaxKind.Block:
// do not treat blocks directly inside a function as a block-scoped-container.
// Locals that reside in this block should go to the function locals. Othewise 'x'
// Locals that reside in this block should go to the function locals. Othewise 'x'
// would not appear to be a redeclaration of a block scoped local in the following
// example:
//
@@ -376,7 +386,7 @@ namespace ts {
// the block, then there would be no collision.
//
// By not creating a new block-scoped-container here, we ensure that both 'var x'
// and 'let x' go into the Function-container's locals, and we do get a collision
// and 'let x' go into the Function-container's locals, and we do get a collision
// conflict.
return isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer;
}
@@ -474,7 +484,7 @@ namespace ts {
}
function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean {
var body = node.kind === SyntaxKind.SourceFile ? node : (<ModuleDeclaration>node).body;
let body = node.kind === SyntaxKind.SourceFile ? node : (<ModuleDeclaration>node).body;
if (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock) {
for (let stat of (<Block>body).statements) {
if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) {
@@ -526,8 +536,8 @@ namespace ts {
// For a given function symbol "<...>(...) => T" we want to generate a symbol identical
// to the one we would get for: { <...>(...): T }
//
// We do that by making an anonymous type literal symbol, and then setting the function
// symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
// We do that by making an anonymous type literal symbol, and then setting the function
// symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
// from an actual type literal symbol you would have gotten had you used the long form.
let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node));
addDeclarationToSymbol(symbol, node, SymbolFlags.Signature);
@@ -628,7 +638,7 @@ namespace ts {
}
function getStrictModeIdentifierMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getContainingClass(node)) {
return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
@@ -686,7 +696,7 @@ namespace ts {
}
function getStrictModeEvalOrArgumentsMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getContainingClass(node)) {
return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
@@ -750,24 +760,24 @@ namespace ts {
function bind(node: Node) {
node.parent = parent;
var savedInStrictMode = inStrictMode;
let savedInStrictMode = inStrictMode;
if (!savedInStrictMode) {
updateStrictMode(node);
}
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
// and then potentially add the symbol to an appropriate symbol table. Possible
// destination symbol tables are:
//
//
// 1) The 'exports' table of the current container's symbol.
// 2) The 'members' table of the current container's symbol.
// 3) The 'locals' table of the current container.
//
// However, not all symbols will end up in any of these tables. 'Anonymous' symbols
// However, not all symbols will end up in any of these tables. 'Anonymous' symbols
// (like TypeLiterals for example) will not be put in any table.
bindWorker(node);
// Then we recurse into the children of the node to bind them as well. For certain
// Then we recurse into the children of the node to bind them as well. For certain
// symbols we do specialized work when we recurse. For example, we'll keep track of
// the current 'container' node when it changes. This helps us know which symbol table
// a local should go into for example.
@@ -807,7 +817,7 @@ namespace ts {
}
}
}
/// Should be called only on prologue directives (isPrologueDirective(node) should be true)
function isUseStrictPrologueDirective(node: ExpressionStatement): boolean {
let nodeText = getTextOfNodeFromSourceText(file.text, node.expression);
@@ -882,7 +892,8 @@ namespace ts {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
checkStrictModeFunctionName(<FunctionExpression>node);
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, "__function");
let bindingName = (<FunctionExpression>node).name ? (<FunctionExpression>node).name.text : "__function";
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, bindingName);
case SyntaxKind.ClassExpression:
case SyntaxKind.ClassDeclaration:
return bindClassLikeDeclaration(<ClassLikeDeclaration>node);
@@ -954,15 +965,16 @@ namespace ts {
bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes);
}
else {
bindAnonymousDeclaration(node, SymbolFlags.Class, "__class");
let bindingName = node.name ? node.name.text : "__class";
bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName);
}
let symbol = node.symbol;
// TypeScript 1.0 spec (April 2014): 8.4
// Every class automatically contains a static property member named 'prototype', the
// 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. It is an error to explicitly declare a static
// argument for each type parameter. It is an error to explicitly declare a static
// property member with the name 'prototype'.
//
// Note: we check for this here because this class may be merging into a module. The
@@ -988,7 +1000,7 @@ namespace ts {
function bindVariableDeclarationOrBindingElement(node: VariableDeclaration | BindingElement) {
if (inStrictMode) {
checkStrictModeEvalOrArguments(node, node.name)
checkStrictModeEvalOrArguments(node, node.name);
}
if (!isBindingPattern(node.name)) {
@@ -1027,7 +1039,7 @@ namespace ts {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes);
}
// If this is a property-parameter, then also declare the property symbol into the
// If this is a property-parameter, then also declare the property symbol into the
// containing class.
if (node.flags & NodeFlags.AccessibilityModifier &&
node.parent.kind === SyntaxKind.Constructor &&
@@ -1044,4 +1056,4 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
}
}
}
+1334 -464
View File
File diff suppressed because it is too large Load Diff
+35 -29
View File
@@ -5,7 +5,7 @@
namespace ts {
/* @internal */
export var optionDeclarations: CommandLineOption[] = [
export let optionDeclarations: CommandLineOption[] = [
{
name: "charset",
type: "string",
@@ -203,6 +203,11 @@ namespace ts {
type: "boolean",
description: Diagnostics.Watch_input_files,
},
{
name: "experimentalAsyncFunctions",
type: "boolean",
description: Diagnostics.Enables_experimental_support_for_ES7_async_functions
},
{
name: "experimentalDecorators",
type: "boolean",
@@ -217,11 +222,11 @@ namespace ts {
];
export function parseCommandLine(commandLine: string[]): ParsedCommandLine {
var options: CompilerOptions = {};
var fileNames: string[] = [];
var errors: Diagnostic[] = [];
var shortOptionNames: Map<string> = {};
var optionNameMap: Map<CommandLineOption> = {};
let options: CompilerOptions = {};
let fileNames: string[] = [];
let errors: Diagnostic[] = [];
let shortOptionNames: Map<string> = {};
let optionNameMap: Map<CommandLineOption> = {};
forEach(optionDeclarations, option => {
optionNameMap[option.name.toLowerCase()] = option;
@@ -237,9 +242,9 @@ namespace ts {
};
function parseStrings(args: string[]) {
var i = 0;
let i = 0;
while (i < args.length) {
var s = args[i++];
let s = args[i++];
if (s.charCodeAt(0) === CharacterCodes.at) {
parseResponseFile(s.slice(1));
}
@@ -252,7 +257,7 @@ namespace ts {
}
if (hasProperty(optionNameMap, s)) {
var opt = optionNameMap[s];
let opt = optionNameMap[s];
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
@@ -271,8 +276,8 @@ namespace ts {
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
var map = <Map<number>>opt.type;
var key = (args[i++] || "").toLowerCase();
let map = <Map<number>>opt.type;
let key = (args[i++] || "").toLowerCase();
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
@@ -292,19 +297,19 @@ namespace ts {
}
function parseResponseFile(fileName: string) {
var text = sys.readFile(fileName);
let text = sys.readFile(fileName);
if (!text) {
errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName));
return;
}
var args: string[] = [];
var pos = 0;
let args: string[] = [];
let pos = 0;
while (true) {
while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++;
if (pos >= text.length) break;
var start = pos;
let start = pos;
if (text.charCodeAt(start) === CharacterCodes.doubleQuote) {
pos++;
while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++;
@@ -330,8 +335,9 @@ namespace ts {
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string): { config?: any; error?: Diagnostic } {
let text = '';
try {
var text = sys.readFile(fileName);
text = sys.readFile(fileName);
}
catch (e) {
return { error: createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) };
@@ -357,10 +363,10 @@ namespace 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
* file to. e.g. outDir
*/
export function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine {
var errors: Diagnostic[] = [];
let errors: Diagnostic[] = [];
return {
options: getCompilerOptions(),
@@ -369,22 +375,22 @@ namespace ts {
};
function getCompilerOptions(): CompilerOptions {
var options: CompilerOptions = {};
var optionNameMap: Map<CommandLineOption> = {};
let options: CompilerOptions = {};
let optionNameMap: Map<CommandLineOption> = {};
forEach(optionDeclarations, option => {
optionNameMap[option.name] = option;
});
var jsonOptions = json["compilerOptions"];
let jsonOptions = json["compilerOptions"];
if (jsonOptions) {
for (var id in jsonOptions) {
for (let id in jsonOptions) {
if (hasProperty(optionNameMap, id)) {
var opt = optionNameMap[id];
var optType = opt.type;
var value = jsonOptions[id];
var expectedType = typeof optType === "string" ? optType : "string";
let opt = optionNameMap[id];
let optType = opt.type;
let value = jsonOptions[id];
let expectedType = typeof optType === "string" ? optType : "string";
if (typeof value === expectedType) {
if (typeof optType !== "string") {
var key = value.toLowerCase();
let key = value.toLowerCase();
if (hasProperty(optType, key)) {
value = optType[key];
}
@@ -419,7 +425,7 @@ namespace ts {
}
else {
let exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
@@ -430,7 +436,7 @@ namespace ts {
}
else if (fileExtensionIs(name, ".ts")) {
if (!contains(sysFiles, name + "x")) {
fileNames.push(name)
fileNames.push(name);
}
}
else {
+29 -22
View File
@@ -2,17 +2,19 @@
/* @internal */
namespace 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.
// x & y is True if both x and y are True.
// x | y is False if both x and y are False.
// x | y is Maybe if either x or y is Maybe, but neither x or y is True.
// x | y is True if either x or y is True.
/**
* 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.
* x & y is True if both x and y are True.
* x | y is False if both x and y are False.
* x | y is Maybe if either x or y is Maybe, but neither x or y is True.
* x | y is True if either x or y is True.
*/
export const enum Ternary {
False = 0,
Maybe = 1,
True = -1
True = -1
}
export function createFileMap<T>(getCanonicalFileName: (fileName: string) => string): FileMap<T> {
@@ -23,7 +25,7 @@ namespace ts {
contains,
remove,
forEachValue: forEachValueInMap
}
};
function set(fileName: string, value: T) {
files[normalizeKey(fileName)] = value;
@@ -59,6 +61,11 @@ namespace ts {
export interface StringSet extends Map<any> { }
/**
* Iterates through 'array' by index and performs the callback on each element of array until the callback
* returns a truthy value, then returns that value.
* If no such value is found, the callback is applied to each element of array and undefined is returned.
*/
export function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U {
if (array) {
for (let i = 0, len = array.length; i < len; i++) {
@@ -163,7 +170,7 @@ namespace ts {
to.push(v);
}
}
}
}
export function rangeEquals<T>(array1: T[], array2: T[], pos: number, end: number) {
while (pos < end) {
@@ -365,7 +372,7 @@ namespace ts {
}
let text = getLocaleSpecificMessage(message.key);
if (arguments.length > 4) {
text = formatStringFromArgs(text, arguments, 4);
}
@@ -535,7 +542,7 @@ namespace ts {
else {
// A part may be an empty string (which is 'falsy') if the path had consecutive slashes,
// e.g. "path//file.ts". Drop these before re-joining the parts.
if(part) {
if (part) {
normalized.push(part);
}
}
@@ -593,20 +600,20 @@ namespace ts {
function getNormalizedPathComponentsOfUrl(url: string) {
// Get root length of http://www.website.com/folder1/foler2/
// In this example the root is: http://www.website.com/
// In this example the root is: http://www.website.com/
// normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
let urlLength = url.length;
// Initial root length is http:// part
let rootLength = url.indexOf("://") + "://".length;
while (rootLength < urlLength) {
// Consume all immediate slashes in the protocol
// Consume all immediate slashes in the protocol
// eg.initial rootlength is just file:// but it needs to consume another "/" in file:///
if (url.charCodeAt(rootLength) === CharacterCodes.slash) {
rootLength++;
}
else {
// non slash character means we continue proceeding to next component of root search
// non slash character means we continue proceeding to next component of root search
break;
}
}
@@ -619,15 +626,15 @@ namespace ts {
// Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://)
let indexOfNextSlash = url.indexOf(directorySeparator, rootLength);
if (indexOfNextSlash !== -1) {
// Found the "/" after the website.com so the root is length of http://www.website.com/
// Found the "/" after the website.com so the root is length of http://www.website.com/
// and get components afetr the root normally like any other folder components
rootLength = indexOfNextSlash + 1;
return normalizedPathComponents(url, rootLength);
}
else {
// Can't find the host assume the rest of the string as component
// Can't find the host assume the rest of the string as component
// but make sure we append "/" to it as root is not joined using "/"
// eg. if url passed in was http://website.com we want to use root as [http://website.com/]
// eg. if url passed in was http://website.com we want to use root as [http://website.com/]
// so that other path manipulations will be correct and it can be merged with relative paths correctly
return [url + directorySeparator];
}
@@ -757,8 +764,8 @@ namespace ts {
}
Node.prototype = {
kind: kind,
pos: 0,
end: 0,
pos: -1,
end: -1,
flags: 0,
parent: undefined,
};
@@ -767,7 +774,7 @@ namespace ts {
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,
getSignatureConstructor: () => <any>Signature
}
};
export const enum AssertionLevel {
None = 0,
@@ -798,4 +805,4 @@ namespace ts {
Debug.assert(false, message);
}
}
}
}
+45 -24
View File
@@ -130,7 +130,7 @@ namespace ts {
moduleElementDeclarationEmitInfo,
synchronousDeclarationOutput: writer.getText(),
referencePathsOutput,
}
};
function hasInternalAnnotation(range: CommentRange) {
let text = currentSourceFile.text;
@@ -188,7 +188,7 @@ namespace ts {
if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) {
moduleElementEmitInfo = forEach(asynchronousSubModuleDeclarationEmitInfo, declEmitInfo => declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined);
}
// If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration
// then we don't need to write it at this point. We will write it when we actually see its declaration
// Eg.
@@ -198,7 +198,7 @@ namespace ts {
// we would write alias foo declaration when we visit it since it would now be marked as visible
if (moduleElementEmitInfo) {
if (moduleElementEmitInfo.node.kind === SyntaxKind.ImportDeclaration) {
// we have to create asynchronous output only after we have collected complete information
// we have to create asynchronous output only after we have collected complete information
// because it is possible to enable multiple bindings as asynchronously visible
moduleElementEmitInfo.isVisible = true;
}
@@ -340,6 +340,8 @@ namespace ts {
return emitTupleType(<TupleTypeNode>type);
case SyntaxKind.UnionType:
return emitUnionType(<UnionTypeNode>type);
case SyntaxKind.IntersectionType:
return emitIntersectionType(<IntersectionTypeNode>type);
case SyntaxKind.ParenthesizedType:
return emitParenType(<ParenthesizedTypeNode>type);
case SyntaxKind.FunctionType:
@@ -351,6 +353,21 @@ namespace ts {
return emitEntityName(<Identifier>type);
case SyntaxKind.QualifiedName:
return emitEntityName(<QualifiedName>type);
case SyntaxKind.TypePredicate:
return emitTypePredicate(<TypePredicateNode>type);
}
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
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, right);
}
}
function emitEntityName(entityName: EntityName | PropertyAccessExpression) {
@@ -360,19 +377,6 @@ namespace ts {
handleSymbolAccessibilityError(visibilityResult);
writeEntityName(entityName);
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
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, right);
}
}
}
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
@@ -396,6 +400,12 @@ namespace ts {
}
}
function emitTypePredicate(type: TypePredicateNode) {
writeTextOfNode(currentSourceFile, type.parameterName);
write(" is ");
emitType(type.type);
}
function emitTypeQuery(type: TypeQueryNode) {
write("typeof ");
emitEntityName(type.exprName);
@@ -416,6 +426,10 @@ namespace ts {
emitSeparatedList(type.types, " | ", emitType);
}
function emitIntersectionType(type: IntersectionTypeNode) {
emitSeparatedList(type.types, " & ", emitType);
}
function emitParenType(type: ParenthesizedTypeNode) {
write("(");
emitType(type.type);
@@ -588,10 +602,13 @@ namespace ts {
if (node.flags & NodeFlags.Static) {
write("static ");
}
if (node.flags & NodeFlags.Abstract) {
write("abstract ");
}
}
function writeImportEqualsDeclaration(node: ImportEqualsDeclaration) {
// note usage of writer. methods instead of aliases created, just to make sure we are using
// note usage of writer. methods instead of aliases created, just to make sure we are using
// correct writer especially to handle asynchronous alias writing
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
@@ -633,7 +650,7 @@ namespace ts {
function writeImportDeclaration(node: ImportDeclaration) {
if (!node.importClause && !(node.flags & NodeFlags.Export)) {
// do not write non-exported import declarations that don't have import clauses
// do not write non-exported import declarations that don't have import clauses
return;
}
emitJsDocComments(node);
@@ -755,7 +772,7 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (isConst(node)) {
write("const ")
write("const ");
}
write("enum ");
writeTextOfNode(currentSourceFile, node.name);
@@ -912,6 +929,10 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (node.flags & NodeFlags.Abstract) {
write("abstract ");
}
write("class ");
writeTextOfNode(currentSourceFile, node.name);
let prevEnclosingDeclaration = enclosingDeclaration;
@@ -1330,7 +1351,7 @@ namespace ts {
return {
diagnosticMessage,
errorNode: <Node>node.name || node,
errorNode: <Node>node.name || node
};
}
}
@@ -1504,7 +1525,7 @@ namespace ts {
}
}
}
}
}
}
function emitNode(node: Node) {
@@ -1552,7 +1573,7 @@ namespace ts {
? referencedFile.fileName // Declaration file, use declaration file name
: shouldEmitToOwnFile(referencedFile, compilerOptions)
? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file
: removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file
: removeFileExtension(compilerOptions.out) + ".d.ts"; // Global out file
declFileName = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizeSlashes(jsFilePath)),
@@ -1564,7 +1585,7 @@ namespace ts {
referencePathsOutput += "/// <reference path=\"" + declFileName + "\" />" + newLine;
}
}
/* @internal */
export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) {
let emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile);
@@ -1591,4 +1612,4 @@ namespace ts {
return declarationOutput;
}
}
}
}
@@ -29,7 +29,12 @@ namespace ts {
Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." },
A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used in an already ambient context." },
Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: DiagnosticCategory.Error, key: "Initializers are not allowed in ambient contexts." },
_0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used in an ambient context." },
_0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used with a class declaration." },
_0_modifier_cannot_be_used_here: { code: 1042, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used here." },
_0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a data property." },
_0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a module element." },
A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: DiagnosticCategory.Error, key: "A '{0}' modifier cannot be used with an interface declaration." },
A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: DiagnosticCategory.Error, key: "A 'declare' modifier is required for a top level declaration in a .d.ts file." },
A_rest_parameter_cannot_be_optional: { code: 1047, category: DiagnosticCategory.Error, key: "A rest parameter cannot be optional." },
A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: DiagnosticCategory.Error, key: "A rest parameter cannot have an initializer." },
@@ -38,12 +43,18 @@ namespace ts {
A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: DiagnosticCategory.Error, key: "A 'set' accessor parameter cannot have an initializer." },
A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have rest parameter." },
A_get_accessor_cannot_have_parameters: { code: 1054, category: DiagnosticCategory.Error, key: "A 'get' accessor cannot have parameters." },
Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: DiagnosticCategory.Error, key: "Type '{0}' is not a valid async function return type." },
Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: DiagnosticCategory.Error, key: "Accessors are only available when targeting ECMAScript 5 and higher." },
An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: DiagnosticCategory.Error, key: "An async function or method must have a valid awaitable return type." },
Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: DiagnosticCategory.Error, key: "Operand for 'await' does not have a valid callable 'then' member." },
Return_expression_in_async_function_does_not_have_a_valid_callable_then_member: { code: 1059, category: DiagnosticCategory.Error, key: "Return expression in async function does not have a valid callable 'then' member." },
Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member: { code: 1060, category: DiagnosticCategory.Error, key: "Expression body for async arrow function does not have a valid callable 'then' member." },
Enum_member_must_have_initializer: { code: 1061, category: DiagnosticCategory.Error, key: "Enum member must have initializer." },
_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: DiagnosticCategory.Error, key: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." },
An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a namespace." },
Ambient_enum_elements_can_only_have_integer_literal_initializers: { code: 1066, category: DiagnosticCategory.Error, key: "Ambient enum elements can only have integer literal initializers." },
Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: DiagnosticCategory.Error, key: "Unexpected token. A constructor, method, accessor, or property was expected." },
A_declare_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an import declaration." },
A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: DiagnosticCategory.Error, key: "A '{0}' modifier cannot be used with an import declaration." },
Invalid_reference_directive_syntax: { code: 1084, category: DiagnosticCategory.Error, key: "Invalid 'reference' directive syntax." },
Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: DiagnosticCategory.Error, key: "Octal literals are not available when targeting ECMAScript 5 and higher." },
An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: DiagnosticCategory.Error, key: "An accessor cannot be declared in an ambient context." },
@@ -179,12 +190,20 @@ namespace ts {
An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: DiagnosticCategory.Error, key: "An export declaration can only be used in a module." },
An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." },
A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." },
Experimental_support_for_async_functions_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalAsyncFunctions_to_remove_this_warning: { code: 1236, category: DiagnosticCategory.Error, key: "Experimental support for async functions is a feature that is subject to change in a future release. Specify '--experimentalAsyncFunctions' to remove this warning." },
with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in an async function block." },
await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: DiagnosticCategory.Error, key: "'await' expression is only allowed within an async function." },
Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: DiagnosticCategory.Error, key: "Async functions are only available when targeting ECMAScript 6 and higher." },
The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." },
The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." },
Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." },
Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." },
Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." },
Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." },
abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: DiagnosticCategory.Error, key: "'abstract' modifier can only appear on a class or method declaration." },
_0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot be used with '{1}' modifier." },
Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: DiagnosticCategory.Error, key: "Abstract methods can only appear within an abstract class." },
Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: DiagnosticCategory.Error, key: "Method '{0}' cannot have an implementation because it is marked abstract." },
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." },
@@ -220,10 +239,10 @@ namespace ts {
this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a static property initializer." },
super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: DiagnosticCategory.Error, key: "'super' can only be referenced in a derived class." },
super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: DiagnosticCategory.Error, key: "'super' cannot be referenced in constructor arguments." },
Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: DiagnosticCategory.Error, key: "Super calls are not permitted outside constructors or in nested functions inside constructors" },
super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: DiagnosticCategory.Error, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class" },
Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: DiagnosticCategory.Error, key: "Super calls are not permitted outside constructors or in nested functions inside constructors." },
super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: DiagnosticCategory.Error, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." },
Property_0_does_not_exist_on_type_1: { code: 2339, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on type '{1}'." },
Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: DiagnosticCategory.Error, key: "Only public and protected methods of the base class are accessible via the 'super' keyword" },
Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: DiagnosticCategory.Error, key: "Only public and protected methods of the base class are accessible via the 'super' keyword." },
Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: DiagnosticCategory.Error, key: "Property '{0}' is private and only accessible within class '{1}'." },
An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: DiagnosticCategory.Error, key: "An index expression argument must be of type 'string', 'number', 'symbol, or 'any'." },
Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}'." },
@@ -382,6 +401,19 @@ namespace ts {
No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: DiagnosticCategory.Error, key: "No base constructor has the specified number of type arguments." },
Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: DiagnosticCategory.Error, key: "Base constructor return type '{0}' is not a class or interface type." },
Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: DiagnosticCategory.Error, key: "Base constructors must all have the same return type." },
Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: DiagnosticCategory.Error, key: "Cannot create an instance of the abstract class '{0}'." },
Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: DiagnosticCategory.Error, key: "Overload signatures must all be abstract or not abstract." },
Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: DiagnosticCategory.Error, key: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." },
Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." },
Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." },
All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." },
Constructor_objects_of_abstract_type_cannot_be_assigned_to_constructor_objects_of_non_abstract_type: { code: 2517, category: DiagnosticCategory.Error, key: "Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type" },
Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." },
Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." },
Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." },
The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." },
yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: DiagnosticCategory.Error, key: "'yield' expressions cannot be used in a parameter initializer." },
await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: DiagnosticCategory.Error, key: "'await' expressions cannot be used in a parameter initializer." },
JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: DiagnosticCategory.Error, key: "JSX element attributes type '{0}' must be an object type." },
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: DiagnosticCategory.Error, key: "The return type of a JSX element constructor must return an object type." },
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." },
@@ -538,6 +570,8 @@ namespace ts {
Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." },
Enables_experimental_support_for_ES7_decorators: { code: 6065, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 decorators." },
Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: DiagnosticCategory.Message, key: "Enables experimental support for emitting type metadata for decorators." },
Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower: { code: 6067, category: DiagnosticCategory.Message, key: "Option 'experimentalAsyncFunctions' cannot be specified when targeting ES5 or lower." },
Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 async functions." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." },
+140 -7
View File
@@ -103,10 +103,30 @@
"category": "Error",
"code": 1039
},
"'{0}' modifier cannot be used in an ambient context.": {
"category": "Error",
"code": 1040
},
"'{0}' modifier cannot be used with a class declaration.": {
"category": "Error",
"code": 1041
},
"'{0}' modifier cannot be used here.": {
"category": "Error",
"code": 1042
},
"'{0}' modifier cannot appear on a data property.": {
"category": "Error",
"code": 1043
},
"'{0}' modifier cannot appear on a module element.": {
"category": "Error",
"code": 1044
},
"A '{0}' modifier cannot be used with an interface declaration.": {
"category": "Error",
"code": 1045
},
"A 'declare' modifier is required for a top level declaration in a .d.ts file.": {
"category": "Error",
"code": 1046
@@ -139,14 +159,38 @@
"category": "Error",
"code": 1054
},
"Type '{0}' is not a valid async function return type.": {
"category": "Error",
"code": 1055
},
"Accessors are only available when targeting ECMAScript 5 and higher.": {
"category": "Error",
"code": 1056
},
"An async function or method must have a valid awaitable return type.": {
"category": "Error",
"code": 1057
},
"Operand for 'await' does not have a valid callable 'then' member.": {
"category": "Error",
"code": 1058
},
"Return expression in async function does not have a valid callable 'then' member.": {
"category": "Error",
"code": 1059
},
"Expression body for async arrow function does not have a valid callable 'then' member.": {
"category": "Error",
"code": 1060
},
"Enum member must have initializer.": {
"category": "Error",
"code": 1061
},
"{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method.": {
"category": "Error",
"code": 1062
},
"An export assignment cannot be used in a namespace.": {
"category": "Error",
"code": 1063
@@ -159,7 +203,7 @@
"category": "Error",
"code": 1068
},
"A 'declare' modifier cannot be used with an import declaration.": {
"A '{0}' modifier cannot be used with an import declaration.": {
"category": "Error",
"code": 1079
},
@@ -703,8 +747,24 @@
"category": "Error",
"code": 1235
},
"Experimental support for async functions is a feature that is subject to change in a future release. Specify '--experimentalAsyncFunctions' to remove this warning.": {
"category": "Error",
"code": 1236
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
},
"'await' expression is only allowed within an async function.": {
"category": "Error",
"code": 1308
},
"Async functions are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1311
},
"The return type of a property decorator function must be either 'void' or 'any'.": {
"category": "Error",
"code": 1236
@@ -729,7 +789,22 @@
"category": "Error",
"code": 1241
},
"'abstract' modifier can only appear on a class or method declaration.": {
"category": "Error",
"code": 1242
},
"'{0}' modifier cannot be used with '{1}' modifier.": {
"category": "Error",
"code": 1243
},
"Abstract methods can only appear within an abstract class.": {
"category": "Error",
"code": 1244
},
"Method '{0}' cannot have an implementation because it is marked abstract.": {
"category": "Error",
"code": 1245
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -870,11 +945,11 @@
"category": "Error",
"code": 2336
},
"Super calls are not permitted outside constructors or in nested functions inside constructors": {
"Super calls are not permitted outside constructors or in nested functions inside constructors.": {
"category": "Error",
"code": 2337
},
"'super' property access is permitted only in a constructor, member function, or member accessor of a derived class": {
"'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.": {
"category": "Error",
"code": 2338
},
@@ -882,7 +957,7 @@
"category": "Error",
"code": 2339
},
"Only public and protected methods of the base class are accessible via the 'super' keyword": {
"Only public and protected methods of the base class are accessible via the 'super' keyword.": {
"category": "Error",
"code": 2340
},
@@ -1518,7 +1593,58 @@
"category": "Error",
"code": 2510
},
"Cannot create an instance of the abstract class '{0}'.": {
"category": "Error",
"code": 2511
},
"Overload signatures must all be abstract or not abstract.": {
"category": "Error",
"code": 2512
},
"Abstract method '{0}' in class '{1}' cannot be accessed via super expression.": {
"category": "Error",
"code": 2513
},
"Classes containing abstract methods must be marked abstract.": {
"category": "Error",
"code": 2514
},
"Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'.": {
"category": "Error",
"code": 2515
},
"All declarations of an abstract method must be consecutive.": {
"category": "Error",
"code": 2516
},
"Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type": {
"category": "Error",
"code":2517
},
"Only an ambient class can be merged with an interface.": {
"category": "Error",
"code": 2518
},
"Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": {
"category": "Error",
"code": 2520
},
"Expression resolves to variable declaration '{0}' that compiler uses to support async functions.": {
"category": "Error",
"code": 2521
},
"The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression.": {
"category": "Error",
"code": 2522
},
"'yield' expressions cannot be used in a parameter initializer.": {
"category": "Error",
"code": 2523
},
"'await' expressions cannot be used in a parameter initializer.": {
"category": "Error",
"code": 2524
},
"JSX element attributes type '{0}' must be an object type.": {
"category": "Error",
"code": 2600
@@ -1559,7 +1685,6 @@
"category": "Error",
"code": 2650
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2145,6 +2270,14 @@
"category": "Message",
"code": 6066
},
"Option 'experimentalAsyncFunctions' cannot be specified when targeting ES5 or lower.": {
"category": "Message",
"code": 6067
},
"Enables experimental support for ES7 async functions.": {
"category": "Message",
"code": 6068
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
+280 -92
View File
@@ -47,6 +47,20 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};`;
const awaiterHelper = `
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
return new Promise(function (resolve, reject) {
generator = generator.call(thisArg, _arguments);
function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
function step(verb, value) {
var result = generator[verb](value);
result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
}
step("next", void 0);
});
};`;
let compilerOptions = host.getCompilerOptions();
let languageVersion = compilerOptions.target || ScriptTarget.ES3;
@@ -132,6 +146,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
let extendsEmitted = false;
let decorateEmitted = false;
let paramEmitted = false;
let awaiterEmitted = false;
let tempFlags = 0;
let tempVariables: Identifier[];
let tempParameters: Identifier[];
@@ -167,10 +182,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
/** Called to before starting the lexical scopes as in function/class in the emitted code because of node
* @param scopeDeclaration node that starts the lexical scope
* @param scopeName Optional name of this scope instead of deducing one from the declaration node */
let scopeEmitStart = function (scopeDeclaration: Node, scopeName?: string) { }
let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { };
/** Called after coming out of the scope */
let scopeEmitEnd = function () { }
let scopeEmitEnd = function() { };
/** Sourcemap data that will get encoded */
let sourceMapData: SourceMapData;
@@ -212,7 +227,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
function makeTempVariableName(flags: TempFlags): string {
if (flags && !(tempFlags & flags)) {
var name = flags === TempFlags._i ? "_i" : "_n"
let name = flags === TempFlags._i ? "_i" : "_n";
if (isUniqueName(name)) {
tempFlags |= flags;
return name;
@@ -882,13 +897,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
}
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (node.parent) {
return getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
switch (node.kind) {
@@ -918,14 +933,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// The raw strings contain the (escaped) strings of what the user wrote.
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
// thus we need to remove those characters.
// First template piece starts with "`", others with "}"
// Last template piece ends with "`", others with "${"
let isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail;
text = text.substring(1, text.length - (isLast ? 1 : 2));
// Newline normalization:
// ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
// <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
@@ -966,7 +981,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag));
write("(");
emit(tempVariable);
// Now we emit the expressions
if (node.template.kind === SyntaxKind.TemplateExpression) {
forEach((<TemplateExpression>node.template).templateSpans, templateSpan => {
@@ -1029,7 +1044,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// with the head will force the result up to this point to be a string.
// Emitting a '+ ""' has no semantic effect for middles and tails.
if (templateSpan.literal.text.length !== 0) {
write(" + ")
write(" + ");
emitLiteral(templateSpan.literal);
}
}
@@ -1343,7 +1358,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
else if (node.kind === SyntaxKind.ComputedPropertyName) {
// if this is a decorated computed property, we will need to capture the result
// of the property expression so that we can apply decorators later. This is to ensure
// of the property expression so that we can apply decorators later. This is to ensure
// we don't introduce unintended side effects:
//
// class C {
@@ -1449,6 +1464,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
function emitExpressionIdentifier(node: Identifier) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.LexicalArguments) {
write("_arguments");
return;
}
let container = resolver.getReferencedExportContainer(node);
if (container) {
if (container.kind === SyntaxKind.SourceFile) {
@@ -1532,7 +1552,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write("super");
}
else {
var flags = resolver.getNodeCheckFlags(node);
let flags = resolver.getNodeCheckFlags(node);
if (flags & NodeCheckFlags.SuperInstance) {
write("_super.prototype");
}
@@ -1589,6 +1609,30 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
}
function emitAwaitExpression(node: AwaitExpression) {
let needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node);
if (needsParenthesis) {
write("(");
}
write(tokenToString(SyntaxKind.YieldKeyword));
write(" ");
emit(node.expression);
if (needsParenthesis) {
write(")");
}
}
function needsParenthesisForAwaitExpressionAsYield(node: AwaitExpression) {
if (node.parent.kind === SyntaxKind.BinaryExpression && !isAssignmentOperator((<BinaryExpression>node.parent).operatorToken.kind)) {
return true;
}
else if (node.parent.kind === SyntaxKind.ConditionalExpression && (<ConditionalExpression>node.parent).condition === node) {
return true;
}
return false;
}
function needsParenthesisForPropertyAccessOrInvocation(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
@@ -1644,7 +1688,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
group++;
}
if (group > 1) {
if(useConcat) {
if (useConcat) {
write(")");
}
}
@@ -1679,7 +1723,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write("{");
if (numElements > 0) {
var properties = node.properties;
let properties = node.properties;
// If we are not doing a downlevel transformation for object literals,
// then try to preserve the original shape of the object literal.
@@ -1727,7 +1771,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// Write out the first non-computed properties
// (or all properties if none of them are computed),
// then emit the rest through indexing on the temp variable.
emit(tempVar)
emit(tempVar);
write(" = ");
emitObjectLiteralBody(node, firstComputedPropertyIndex);
@@ -1736,7 +1780,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
let property = properties[i];
emitStart(property)
emitStart(property);
if (property.kind === SyntaxKind.GetAccessor || property.kind === SyntaxKind.SetAccessor) {
// TODO (drosen): Reconcile with 'emitMemberFunctions'.
let accessors = getAllAccessorDeclarations(node.properties, <AccessorDeclaration>property);
@@ -1752,7 +1796,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write(", {");
increaseIndent();
if (accessors.getAccessor) {
writeLine()
writeLine();
emitLeadingComments(accessors.getAccessor);
write("get: ");
emitStart(accessors.getAccessor);
@@ -1977,8 +2021,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return false;
}
// Returns 'true' if the code was actually indented, false otherwise.
// If the code is not indented, an optional valueToWriteWhenNotIndenting will be
// Returns 'true' if the code was actually indented, false otherwise.
// If the code is not indented, an optional valueToWriteWhenNotIndenting will be
// emitted instead.
function indentIfOnDifferentLines(parent: Node, node1: Node, node2: Node, valueToWriteWhenNotIndenting?: string): boolean {
let realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2);
@@ -2006,8 +2050,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emit(node.expression);
let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
// 1 .toString is a valid property access, emit a space after the literal
// 1 .toString is a valid property access, emit a space after the literal
let shouldEmitSpace: boolean;
if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) {
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
@@ -2015,7 +2059,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
if (shouldEmitSpace) {
write(" .");
write(" .");
}
else {
write(".");
@@ -2379,14 +2423,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false);
}
/*
/*
* Checks if given node is a source file level declaration (not nested in module/function).
* If 'isExported' is true - then declaration must also be exported.
* This function is used in two cases:
* - check if node is a exported source file level value to determine
* - check if node is a exported source file level value to determine
* if we should also export the value after its it changed
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* we we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node: Node, isExported: boolean): boolean {
@@ -2397,7 +2441,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
let current: Node = node;
while (current) {
if (current.kind === SyntaxKind.SourceFile) {
return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0)
return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0);
}
else if (isFunctionLike(current) || current.kind === SyntaxKind.ModuleBlock) {
return false;
@@ -2455,7 +2499,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
decreaseIndentIf(indentedBeforeColon, indentedAfterColon);
}
// Helper function to decrease the indent if we previously indented. Allows multiple
// Helper function to decrease the indent if we previously indented. Allows multiple
// previous indent values to be considered at a time. This also allows caller to just
// call this once, passing in all their appropriate indent values, instead of needing
// to call this helper function multiple times.
@@ -2582,7 +2626,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
if (startPos !== undefined) {
emitToken(tokenKind, startPos);
write(" ")
write(" ");
}
else {
switch (tokenKind) {
@@ -2697,13 +2741,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// all destructuring.
// Note also that because an extra statement is needed to assign to the LHS,
// for-of bodies are always emitted as blocks.
let endPos = emitToken(SyntaxKind.ForKeyword, node.pos);
write(" ");
endPos = emitToken(SyntaxKind.OpenParenToken, endPos);
// Do not emit the LHS let declaration yet, because it might contain destructuring.
// Do not call recordTempDeclaration because we are declaring the temps
// right here. Recording means they will be declared later.
// In the case where the user wrote an identifier as the RHS, like this:
@@ -2719,7 +2763,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// the LHS will be emitted inside the body.
emitStart(node.expression);
write("var ");
// _i = 0
emitNodeWithoutSourceMap(counter);
write(" = 0");
@@ -2736,7 +2780,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
write("; ");
// _i < _a.length;
emitStart(node.initializer);
emitNodeWithoutSourceMap(counter);
@@ -2747,19 +2791,19 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitEnd(node.initializer);
write("; ");
// _i++)
emitStart(node.initializer);
emitNodeWithoutSourceMap(counter);
write("++");
emitEnd(node.initializer);
emitToken(SyntaxKind.CloseParenToken, node.expression.end);
// Body
write(" {");
writeLine();
increaseIndent();
// Initialize LHS
// let v = _a[_i];
let rhsIterationValue = createElementAccessExpression(rhsReference, counter);
@@ -2845,7 +2889,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emit(node.expression);
endPos = emitToken(SyntaxKind.CloseParenToken, node.expression.end);
write(" ");
emitCaseBlock(node.caseBlock, endPos)
emitCaseBlock(node.caseBlock, endPos);
}
function emitCaseBlock(node: CaseBlock, startPos: number): void {
@@ -2947,7 +2991,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
function emitModuleMemberName(node: Declaration) {
emitStart(node.name);
if (getCombinedNodeFlags(node) & NodeFlags.Export) {
var container = getContainingModule(node);
let container = getContainingModule(node);
if (container) {
write(getGeneratedNameForNode(container));
write(".");
@@ -2986,7 +3030,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
write(`", `);
emitDeclarationName(node);
write(")")
write(")");
}
else {
if (node.flags & NodeFlags.Default) {
@@ -3017,7 +3061,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitNodeWithoutSourceMap(specifier.name);
write(`", `);
emitExpressionIdentifier(name);
write(")")
write(")");
emitEnd(specifier.name);
}
else {
@@ -3307,7 +3351,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitOptional(" = ", initializer);
if (exportChanged) {
write(")")
write(")");
}
}
}
@@ -3607,9 +3651,150 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emit(node.parameters[0]);
return;
}
emitSignatureParameters(node);
}
function emitAsyncFunctionBodyForES6(node: FunctionLikeDeclaration) {
let promiseConstructor = getEntityNameFromTypeNode(node.type);
let isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
let hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
let args: string;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
//
// The emit for an async arrow without a lexical `arguments` binding might be:
//
// // input
// let a = async (b) => { await b; }
//
// // output
// let a = (b) => __awaiter(this, void 0, void 0, function* () {
// yield b;
// });
//
// The emit for an async arrow with a lexical `arguments` binding might be:
//
// // input
// let a = async (b) => { await arguments[0]; }
//
// // output
// let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) {
// yield arguments[0];
// });
//
// The emit for an async function expression without a lexical `arguments` binding
// might be:
//
// // input
// let a = async function (b) {
// await b;
// }
//
// // output
// let a = function (b) {
// return __awaiter(this, void 0, void 0, function* () {
// yield b;
// });
// }
//
// The emit for an async function expression with a lexical `arguments` binding
// might be:
//
// // input
// let a = async function (b) {
// await arguments[0];
// }
//
// // output
// let a = function (b) {
// return __awaiter(this, arguments, void 0, function* (_arguments) {
// yield _arguments[0];
// });
// }
//
// The emit for an async function expression with a lexical `arguments` binding
// and a return type annotation might be:
//
// // input
// let a = async function (b): MyPromise<any> {
// await arguments[0];
// }
//
// // output
// let a = function (b) {
// return __awaiter(this, arguments, MyPromise, function* (_arguments) {
// yield _arguments[0];
// });
// }
//
// If this is not an async arrow, emit the opening brace of the function body
// and the start of the return statement.
if (!isArrowFunction) {
write(" {");
increaseIndent();
writeLine();
write("return");
}
write(" __awaiter(this");
if (hasLexicalArguments) {
write(", arguments");
}
else {
write(", void 0");
}
if (promiseConstructor) {
write(", ");
emitNodeWithoutSourceMap(promiseConstructor);
}
else {
write(", Promise");
}
// Emit the call to __awaiter.
if (hasLexicalArguments) {
write(", function* (_arguments)");
}
else {
write(", function* ()");
}
// Emit the signature and body for the inner generator function.
emitFunctionBody(node);
write(")");
// If this is not an async arrow, emit the closing brace of the outer function body.
if (!isArrowFunction) {
write(";");
decreaseIndent();
writeLine();
write("}");
}
}
function emitFunctionBody(node: FunctionLikeDeclaration) {
if (!node.body) {
// There can be no body when there are parse errors. Just emit an empty block
// in that case.
write(" { }");
}
else {
if (node.body.kind === SyntaxKind.Block) {
emitBlockFunctionBody(node, <Block>node.body);
}
else {
emitExpressionFunctionBody(node, <Expression>node.body);
}
}
}
function emitSignatureAndBody(node: FunctionLikeDeclaration) {
let saveTempFlags = tempFlags;
let saveTempVariables = tempVariables;
@@ -3627,16 +3812,12 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitSignatureParameters(node);
}
if (!node.body) {
// There can be no body when there are parse errors. Just emit an empty block
// in that case.
write(" { }");
}
else if (node.body.kind === SyntaxKind.Block) {
emitBlockFunctionBody(node, <Block>node.body);
let isAsync = isAsyncFunctionLike(node);
if (isAsync && languageVersion === ScriptTarget.ES6) {
emitAsyncFunctionBodyForES6(node);
}
else {
emitExpressionFunctionBody(node, <Expression>node.body);
emitFunctionBody(node);
}
if (!isES6ExportedDeclaration(node)) {
@@ -3656,12 +3837,12 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
function emitExpressionFunctionBody(node: FunctionLikeDeclaration, body: Expression) {
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES6 || node.flags & NodeFlags.Async) {
emitDownLevelExpressionFunctionBody(node, body);
return;
}
// For es6 and higher we can emit the expression as is. However, in the case
// For es6 and higher we can emit the expression as is. However, in the case
// where the expression might end up looking like a block when emitted, we'll
// also wrap it in parentheses first. For example if you have: a => <foo>{}
// then we need to generate: a => ({})
@@ -3933,8 +4114,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitOnlyPinnedOrTripleSlashComments(member);
}
else if (member.kind === SyntaxKind.MethodDeclaration ||
member.kind === SyntaxKind.GetAccessor ||
member.kind === SyntaxKind.SetAccessor) {
member.kind === SyntaxKind.GetAccessor ||
member.kind === SyntaxKind.SetAccessor) {
writeLine();
emitLeadingComments(member);
emitStart(member);
@@ -4068,7 +4249,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false));
if (ctor) {
var statements: Node[] = (<Block>ctor.body).statements;
let statements: Node[] = (<Block>ctor.body).statements;
if (superCall) {
statements = statements.slice(1);
}
@@ -4178,9 +4359,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
// If the class has static properties, and it's a class expression, then we'll need
// to specialize the emit a bit. for a class expression of the form:
// to specialize the emit a bit. for a class expression of the form:
//
// class C { static a = 1; static b = 2; ... }
// class C { static a = 1; static b = 2; ... }
//
// We'll emit:
//
@@ -4197,7 +4378,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write("(");
increaseIndent();
emit(tempVariable);
write(" = ")
write(" = ");
}
write("class");
@@ -4208,7 +4389,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitDeclarationName(node);
}
var baseTypeNode = getClassExtendsHeritageClauseElement(node);
let baseTypeNode = getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
write(" extends ");
emit(baseTypeNode.expression);
@@ -4226,7 +4407,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
scopeEmitEnd();
// TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now.
// For a decorated class, we need to assign its name (if it has one). This is because we emit
// the class as a class expression to avoid the double-binding of the identifier:
//
@@ -4471,7 +4652,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
//
// The emit for a method is:
//
// Object.defineProperty(C.prototype, "method",
// Object.defineProperty(C.prototype, "method",
// __decorate([
// dec,
// __param(0, dec2),
@@ -4479,10 +4660,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// __metadata("design:paramtypes", [Object]),
// __metadata("design:returntype", void 0)
// ], C.prototype, "method", Object.getOwnPropertyDescriptor(C.prototype, "method")));
//
//
// The emit for an accessor is:
//
// Object.defineProperty(C.prototype, "accessor",
// Object.defineProperty(C.prototype, "accessor",
// __decorate([
// dec
// ], C.prototype, "accessor", Object.getOwnPropertyDescriptor(C.prototype, "accessor")));
@@ -4572,7 +4753,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
function shouldEmitTypeMetadata(node: Declaration): boolean {
// This method determines whether to emit the "design:type" metadata based on the node's kind.
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// compiler option is set.
switch (node.kind) {
case SyntaxKind.MethodDeclaration:
@@ -4587,7 +4768,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
function shouldEmitReturnTypeMetadata(node: Declaration): boolean {
// This method determines whether to emit the "design:returntype" metadata based on the node's kind.
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// compiler option is set.
switch (node.kind) {
case SyntaxKind.MethodDeclaration:
@@ -4598,7 +4779,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
function shouldEmitParamTypesMetadata(node: Declaration): boolean {
// This method determines whether to emit the "design:paramtypes" metadata based on the node's kind.
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// compiler option is set.
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
@@ -5330,7 +5511,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
writeLine();
emitStart(node);
write("export default ");
var expression = node.expression;
let expression = node.expression;
emit(expression);
if (expression.kind !== SyntaxKind.FunctionDeclaration &&
expression.kind !== SyntaxKind.ClassDeclaration) {
@@ -5460,7 +5641,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// do not create variable declaration for exports and imports that lack import clause
let skipNode =
importNode.kind === SyntaxKind.ExportDeclaration ||
(importNode.kind === SyntaxKind.ImportDeclaration && !(<ImportDeclaration>importNode).importClause)
(importNode.kind === SyntaxKind.ImportDeclaration && !(<ImportDeclaration>importNode).importClause);
if (skipNode) {
continue;
@@ -5578,14 +5759,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write("}");
decreaseIndent();
writeLine();
write("}")
write("}");
return exportStarFunction;
}
function writeExportedName(node: Identifier | Declaration): void {
// do not record default exports
// they are local to module and never overwritten (explicitly skipped) by star export
// they are local to module and never overwritten (explicitly skipped) by star export
if (node.kind !== SyntaxKind.Identifier && node.flags & NodeFlags.Default) {
return;
}
@@ -5611,7 +5792,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
function processTopLevelVariableAndFunctionDeclarations(node: SourceFile): (Identifier | Declaration)[] {
// per ES6 spec:
// per ES6 spec:
// 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method
// - var declarations are initialized to undefined - 14.a.ii
// - function/generator declarations are instantiated - 16.a.iv
@@ -5666,7 +5847,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
exportedDeclarations.push(local);
}
}
write(";")
write(";");
}
if (hoistedFunctionDeclarations) {
@@ -5766,7 +5947,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// hoist variable if
// - it is not block scoped
// - it is top level block scoped
// if block scoped variables are nested in some another block then
// if block scoped variables are nested in some another block then
// no other functions can use them except ones that are defined at least in the same block
return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0 ||
getEnclosingBlockScopeContainer(node).kind === SyntaxKind.SourceFile;
@@ -5815,8 +5996,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// }
emitVariableDeclarationsForImports();
writeLine();
var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);
let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations)
let exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);
let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations);
writeLine();
write("return {");
increaseIndent();
@@ -5893,7 +6074,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// export {a, b as c}
for (let element of (<NamedImports>namedBindings).elements) {
emitExportMemberAssignments(element.name || element.propertyName);
writeLine()
writeLine();
}
}
}
@@ -5932,7 +6113,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
break;
}
write("}")
write("}");
decreaseIndent();
}
write("],");
@@ -5958,7 +6139,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
decreaseIndent();
writeLine();
write("}") // execute
write("}"); // execute
}
function emitSystemModule(node: SourceFile, startIndex: number): void {
@@ -5966,10 +6147,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// System modules has the following shape
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
// 'exports' here is a function 'exports<T>(name: string, value: T): T' that is used to publish exported values.
// 'exports' returns its 'value' argument so in most cases expressions
// 'exports' returns its 'value' argument so in most cases expressions
// that mutate exported values can be rewritten as:
// expr -> exports('name', expr).
// The only exception in this rule is postfix unary operators,
// expr -> exports('name', expr).
// The only exception in this rule is postfix unary operators,
// see comment to 'emitPostfixUnaryExpression' for more details
Debug.assert(!exportFunctionForFile);
// make sure that name of 'exports' function does not conflict with existing identifiers
@@ -5979,7 +6160,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
if (node.moduleName) {
write(`"${node.moduleName}", `);
}
write("[")
write("[");
for (let i = 0; i < externalImports.length; ++i) {
let text = getExternalModuleNameText(externalImports[i]);
if (i !== 0) {
@@ -6010,13 +6191,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// `import "module"` or `<amd-dependency path= "a.css" />`
// we need to add modules without alias names to the end of the dependencies list
let aliasedModuleNames: string[] = []; // names of modules with corresponding parameter in the
// factory function.
let unaliasedModuleNames: string[] = []; // names of modules with no corresponding parameters in
// factory function.
let importAliasNames: string[] = []; // names of the parameters in the factory function; these
// parameters need to match the indexes of the corresponding
// module names in aliasedModuleNames.
// names of modules with corresponding parameter in the factory function
let aliasedModuleNames: string[] = [];
// names of modules with no corresponding parameters in factory function
let unaliasedModuleNames: string[] = [];
let importAliasNames: string[] = []; // names of the parameters in the factory function; these
// parameters need to match the indexes of the corresponding
// module names in aliasedModuleNames.
// Fill in amd-dependency tags
for (let amdDependency of node.amdDependencies) {
@@ -6123,7 +6304,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
emitTempDeclarations(/*newLine*/ true);
// Emit exportDefault if it exists will happen as part
// Emit exportDefault if it exists will happen as part
// or normal statement emit.
}
@@ -6264,7 +6445,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitDetachedComments(node);
// emit prologue directives prior to __extends
var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
// Only emit helpers if the user did not say otherwise.
if (!compilerOptions.noEmitHelpers) {
@@ -6287,6 +6468,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
writeLines(paramHelper);
paramEmitted = true;
}
if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitAwaiter) {
writeLines(awaiterHelper);
awaiterEmitted = true;
}
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
@@ -6366,7 +6552,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return shouldEmitEnumDeclaration(<EnumDeclaration>node);
}
// If this is the expression body of an arrow function that we're down-leveling,
// If this is the expression body of an arrow function that we're down-leveling,
// then we don't want to emit comments when we emit the body. It will have already
// been taken care of when we emitted the 'return' statement for the function
// expression body.
@@ -6469,6 +6655,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return emitTypeOfExpression(<TypeOfExpression>node);
case SyntaxKind.VoidExpression:
return emitVoidExpression(<VoidExpression>node);
case SyntaxKind.AwaitExpression:
return emitAwaitExpression(<AwaitExpression>node);
case SyntaxKind.PrefixUnaryExpression:
return emitPrefixUnaryExpression(<PrefixUnaryExpression>node);
case SyntaxKind.PostfixUnaryExpression:
@@ -6629,7 +6817,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
function emitTrailingComments(node: Node) {
// Emit the trailing comments only if the parent's end doesn't match
var trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
let trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
+312 -207
View File
File diff suppressed because it is too large Load Diff
+89 -46
View File
@@ -11,12 +11,12 @@ namespace ts {
export const version = "1.5.3";
export function findConfigFile(searchPath: string): string {
var fileName = "tsconfig.json";
let fileName = "tsconfig.json";
while (true) {
if (sys.fileExists(fileName)) {
return fileName;
}
var parentPath = getDirectoryPath(searchPath);
let parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
@@ -35,7 +35,7 @@ namespace ts {
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
let unsupportedFileEncodingErrorCode = -2147024809;
@@ -79,7 +79,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
var start = new Date().getTime();
let start = new Date().getTime();
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
ioWriteTime += new Date().getTime() - start;
@@ -104,14 +104,14 @@ namespace ts {
};
}
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[] {
let diagnostics = program.getOptionsDiagnostics().concat(
program.getSyntacticDiagnostics(sourceFile),
program.getGlobalDiagnostics(),
program.getSemanticDiagnostics(sourceFile));
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] {
let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
diagnostics.concat(program.getDeclarationDiagnostics(sourceFile));
diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return sortAndDeduplicateDiagnostics(diagnostics);
@@ -233,10 +233,15 @@ namespace ts {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback): EmitResult {
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult {
return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken));
}
function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult {
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out.
if (options.noEmitOnError && getPreEmitDiagnostics(this).length > 0) {
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) {
return { diagnostics: [], sourceMaps: undefined, emitSkipped: true };
}
@@ -265,55 +270,88 @@ namespace ts {
return filesByName.get(fileName);
}
function getDiagnosticsHelper(sourceFile: SourceFile, getDiagnostics: (sourceFile: SourceFile) => Diagnostic[]): Diagnostic[] {
function getDiagnosticsHelper(
sourceFile: SourceFile,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[],
cancellationToken: CancellationToken): Diagnostic[] {
if (sourceFile) {
return getDiagnostics(sourceFile);
return getDiagnostics(sourceFile, cancellationToken);
}
let allDiagnostics: Diagnostic[] = [];
forEach(program.getSourceFiles(), sourceFile => {
addRange(allDiagnostics, getDiagnostics(sourceFile));
if (cancellationToken) {
cancellationToken.throwIfCancellationRequested();
}
addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken));
});
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile);
function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
}
function getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile);
function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
}
function getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile);
function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
}
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return sourceFile.parseDiagnostics;
}
function getSemanticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
let typeChecker = getDiagnosticsProducingTypeChecker();
function runWithCancellationToken<T>(func: () => T): T {
try {
return func();
}
catch (e) {
if (e instanceof OperationCanceledException) {
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly agressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
}
Debug.assert(!!sourceFile.bindDiagnostics);
let bindDiagnostics = sourceFile.bindDiagnostics;
let checkDiagnostics = typeChecker.getDiagnostics(sourceFile);
let programDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(programDiagnostics);
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
if (!isDeclarationFile(sourceFile)) {
let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile);
// Don't actually write any files since we're just getting diagnostics.
var writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
throw e;
}
}
function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
let typeChecker = getDiagnosticsProducingTypeChecker();
Debug.assert(!!sourceFile.bindDiagnostics);
let bindDiagnostics = sourceFile.bindDiagnostics;
let checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken);
let programDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(programDiagnostics);
});
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
if (!isDeclarationFile(sourceFile)) {
let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
let writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
});
}
function getOptionsDiagnostics(): Diagnostic[] {
let allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, diagnostics.getGlobalDiagnostics());
@@ -358,7 +396,7 @@ namespace ts {
}
}
else {
var nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd);
let nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = Diagnostics.File_0_not_found;
@@ -458,7 +496,7 @@ namespace ts {
let moduleNameText = (<LiteralExpression>moduleNameExpr).text;
if (moduleNameText) {
let searchPath = basePath;
let searchName: string;
let searchName: string;
while (true) {
searchName = normalizePath(combinePaths(searchPath, moduleNameText));
if (forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, moduleNameExpr))) {
@@ -475,7 +513,7 @@ namespace ts {
}
else if (node.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
@@ -487,7 +525,7 @@ namespace ts {
let moduleName = nameLiteral.text;
if (moduleName) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
let searchName = normalizePath(combinePaths(basePath, moduleName));
forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, nameLiteral));
@@ -626,7 +664,7 @@ namespace ts {
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
// 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_modules_unless_the_module_flag_is_provided));
}
@@ -653,7 +691,7 @@ namespace ts {
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
@@ -669,11 +707,16 @@ namespace ts {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration));
}
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified));
}
if (options.experimentalAsyncFunctions &&
options.target !== ScriptTarget.ES6) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower));
}
}
}
}
+156 -153
View File
@@ -32,19 +32,20 @@ namespace ts {
setScriptTarget(scriptTarget: ScriptTarget): void;
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
// Invokes the provided callback then unconditionally restores the scanner to the state it
// Invokes the provided callback then unconditionally restores the scanner to the state it
// was in immediately prior to invoking the callback. The result of invoking the callback
// is returned from this function.
lookAhead<T>(callback: () => T): T;
// Invokes the provided callback. If the callback returns something falsy, then it restores
// the scanner to the state it was in immediately prior to invoking the callback. If the
// the scanner to the state it was in immediately prior to invoking the callback. If the
// callback returns something truthy, then the scanner state is not rolled back. The result
// of invoking the callback is returned from this function.
tryScan<T>(callback: () => T): T;
}
let textToToken: Map<SyntaxKind> = {
"abstract": SyntaxKind.AbstractKeyword,
"any": SyntaxKind.AnyKeyword,
"as": SyntaxKind.AsKeyword,
"boolean": SyntaxKind.BooleanKeyword,
@@ -106,6 +107,8 @@ namespace ts {
"while": SyntaxKind.WhileKeyword,
"with": SyntaxKind.WithKeyword,
"yield": SyntaxKind.YieldKeyword,
"async": SyntaxKind.AsyncKeyword,
"await": SyntaxKind.AwaitKeyword,
"of": SyntaxKind.OfKeyword,
"{": SyntaxKind.OpenBraceToken,
"}": SyntaxKind.CloseBraceToken,
@@ -272,7 +275,7 @@ namespace ts {
return textToToken[s];
}
/* @internal */
/* @internal */
export function computeLineStarts(text: string): number[] {
let result: number[] = new Array();
let pos = 0;
@@ -304,22 +307,22 @@ namespace ts {
return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character);
}
/* @internal */
/* @internal */
export function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number): number {
Debug.assert(line >= 0 && line < lineStarts.length);
return lineStarts[line] + character;
}
/* @internal */
/* @internal */
export function getLineStarts(sourceFile: SourceFile): number[] {
return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
}
/* @internal */
/* @internal */
export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) {
let lineNumber = binarySearch(lineStarts, position);
if (lineNumber < 0) {
// If the actual position was not found,
// If the actual position was not found,
// the binary search returns the negative value of the next line start
// e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
// then the search will return -2
@@ -352,125 +355,125 @@ namespace ts {
ch === CharacterCodes.mathematicalSpace ||
ch === CharacterCodes.ideographicSpace ||
ch === CharacterCodes.byteOrderMark;
}
}
export function isLineBreak(ch: number): boolean {
// ES5 7.3:
// The ECMAScript line terminator characters are listed in Table 3.
// Table 3: Line Terminator Characters
// Code Unit Value Name Formal Name
// \u000A Line Feed <LF>
// \u000D Carriage Return <CR>
// \u2028 Line separator <LS>
// \u2029 Paragraph separator <PS>
// Only the characters in Table 3 are treated as line terminators. Other new line or line
// breaking characters are treated as white space but not as line terminators.
export function isLineBreak(ch: number): boolean {
// ES5 7.3:
// The ECMAScript line terminator characters are listed in Table 3.
// Table 3: Line Terminator Characters
// Code Unit Value Name Formal Name
// \u000A Line Feed <LF>
// \u000D Carriage Return <CR>
// \u2028 Line separator <LS>
// \u2029 Paragraph separator <PS>
// Only the characters in Table 3 are treated as line terminators. Other new line or line
// breaking characters are treated as white space but not as line terminators.
return ch === CharacterCodes.lineFeed ||
ch === CharacterCodes.carriageReturn ||
ch === CharacterCodes.lineSeparator ||
ch === CharacterCodes.paragraphSeparator;
}
return ch === CharacterCodes.lineFeed ||
ch === CharacterCodes.carriageReturn ||
ch === CharacterCodes.lineSeparator ||
ch === CharacterCodes.paragraphSeparator;
}
function isDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
}
function isDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
}
/* @internal */
export function isOctalDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
}
/* @internal */
export function isOctalDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
}
export function couldStartTrivia(text: string, pos: number): boolean {
// Keep in sync with skipTrivia
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
case CharacterCodes.slash:
// starts of normal trivia
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
}
export function couldStartTrivia(text: string, pos: number): boolean {
// Keep in sync with skipTrivia
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
case CharacterCodes.slash:
// starts of normal trivia
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
}
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
// Keep in sync with couldStartTrivia
while (true) {
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
case CharacterCodes.lineFeed:
pos++;
if (stopAfterLineBreak) {
return pos;
}
continue;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
pos++;
continue;
case CharacterCodes.slash:
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
continue;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) {
pos += 2;
while (pos < text.length) {
if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
break;
}
pos++;
}
continue;
}
break;
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
// Keep in sync with couldStartTrivia
while (true) {
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
case CharacterCodes.lineFeed:
pos++;
if (stopAfterLineBreak) {
return pos;
}
continue;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
pos++;
continue;
case CharacterCodes.slash:
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
continue;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) {
pos += 2;
while (pos < text.length) {
if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
break;
}
pos++;
}
continue;
}
break;
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos);
continue;
}
break;
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos);
continue;
}
break;
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
continue;
}
break;
}
return pos;
}
}
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
continue;
}
break;
}
return pos;
}
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
let mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text: string, pos: number) {
@@ -525,12 +528,12 @@ namespace ts {
return pos;
}
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
// position and the next line break are returned.The return value is an array containing a
// TextRange for each comment. Single-line comment ranges include the beginning '//' characters
// but not the ending line break. Multi - line comment ranges include the beginning '/* and
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
// position and the next line break are returned.The return value is an array containing a
// TextRange for each comment. Single-line comment ranges include the beginning '//' characters
// but not the ending line break. Multi - line comment ranges include the beginning '/* and
// ending '*/' characters.The return value is undefined if no comments were found.
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
@@ -626,9 +629,9 @@ namespace ts {
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
@@ -637,16 +640,16 @@ namespace ts {
start?: number,
length?: number): Scanner {
// Current position (end position of text of current token)
let pos: number;
let pos: number;
// end of text
let end: number;
let end: number;
// Start position of whitespace before current token
let startPos: number;
let startPos: number;
// Start position of text of current token
let tokenPos: number;
let tokenPos: number;
let token: SyntaxKind;
let tokenValue: string;
@@ -732,7 +735,7 @@ namespace ts {
}
return +(text.substring(start, pos));
}
/**
* Scans the given number of hexadecimal digits in the text,
* returning -1 if the given number is unavailable.
@@ -740,7 +743,7 @@ namespace ts {
function scanExactNumberOfHexDigits(count: number): number {
return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false);
}
/**
* Scans as many hexadecimal digits as are available in the text,
* returning -1 if the given number of digits was unavailable.
@@ -818,7 +821,7 @@ namespace ts {
pos++;
let start = pos;
let contents = ""
let contents = "";
let resultingToken: SyntaxKind;
while (true) {
@@ -913,13 +916,13 @@ namespace ts {
pos++;
return scanExtendedUnicodeEscape();
}
// '\uDDDD'
return scanHexadecimalEscape(/*numDigits*/ 4)
return scanHexadecimalEscape(/*numDigits*/ 4);
case CharacterCodes.x:
// '\xDD'
return scanHexadecimalEscape(/*numDigits*/ 2)
return scanHexadecimalEscape(/*numDigits*/ 2);
// when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
// the line terminator is interpreted to be "the empty code unit sequence".
@@ -931,31 +934,31 @@ namespace ts {
case CharacterCodes.lineFeed:
case CharacterCodes.lineSeparator:
case CharacterCodes.paragraphSeparator:
return ""
return "";
default:
return String.fromCharCode(ch);
}
}
function scanHexadecimalEscape(numDigits: number): string {
let escapedValue = scanExactNumberOfHexDigits(numDigits);
if (escapedValue >= 0) {
return String.fromCharCode(escapedValue);
}
else {
error(Diagnostics.Hexadecimal_digit_expected);
return ""
return "";
}
}
function scanExtendedUnicodeEscape(): string {
let escapedValue = scanMinimumNumberOfHexDigits(1);
let isInvalidExtendedEscape = false;
// Validate the value of the digit
if (escapedValue < 0) {
error(Diagnostics.Hexadecimal_digit_expected)
error(Diagnostics.Hexadecimal_digit_expected);
isInvalidExtendedEscape = true;
}
else if (escapedValue > 0x10FFFF) {
@@ -982,18 +985,18 @@ namespace ts {
return utf16EncodeAsString(escapedValue);
}
// Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
function utf16EncodeAsString(codePoint: number): string {
Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
if (codePoint <= 65535) {
return String.fromCharCode(codePoint);
}
let codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
let codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
return String.fromCharCode(codeUnit1, codeUnit2);
}
@@ -1055,7 +1058,7 @@ namespace ts {
let value = 0;
// For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
// Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
let numberOfDigits = 0;
let numberOfDigits = 0;
while (true) {
let ch = text.charCodeAt(pos);
let valueOfCh = ch - CharacterCodes._0;
@@ -1129,7 +1132,7 @@ namespace ts {
tokenValue = scanString();
return token = SyntaxKind.StringLiteral;
case CharacterCodes.backtick:
return token = scanTemplateAndSetTokenValue()
return token = scanTemplateAndSetTokenValue();
case CharacterCodes.percent:
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.PercentEqualsToken;
@@ -1441,14 +1444,14 @@ namespace ts {
// regex. Report error and return what we have so far.
if (p >= end) {
tokenIsUnterminated = true;
error(Diagnostics.Unterminated_regular_expression_literal)
error(Diagnostics.Unterminated_regular_expression_literal);
break;
}
let ch = text.charCodeAt(p);
if (isLineBreak(ch)) {
tokenIsUnterminated = true;
error(Diagnostics.Unterminated_regular_expression_literal)
error(Diagnostics.Unterminated_regular_expression_literal);
break;
}
@@ -1540,7 +1543,7 @@ namespace ts {
let ch = text.charCodeAt(pos);
if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch) : isIdentifierPart(ch))) {
pos++;
}
}
else {
break;
}
@@ -1549,7 +1552,7 @@ namespace ts {
}
return token;
}
function speculationHelper<T>(callback: () => T, isLookahead: boolean): T {
let savePos = pos;
let saveStartPos = startPos;
+22 -22
View File
@@ -41,16 +41,16 @@ namespace ts {
function getWScriptSystem(): System {
var fso = new ActiveXObject("Scripting.FileSystemObject");
let fso = new ActiveXObject("Scripting.FileSystemObject");
var fileStream = new ActiveXObject("ADODB.Stream");
let fileStream = new ActiveXObject("ADODB.Stream");
fileStream.Type = 2 /*text*/;
var binaryStream = new ActiveXObject("ADODB.Stream");
let binaryStream = new ActiveXObject("ADODB.Stream");
binaryStream.Type = 1 /*binary*/;
var args: string[] = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
let args: string[] = [];
for (let i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
@@ -68,7 +68,7 @@ namespace ts {
// Load file and read the first two bytes into a string with no interpretation
fileStream.Charset = "x-ansi";
fileStream.LoadFromFile(fileName);
var bom = fileStream.ReadText(2) || "";
let bom = fileStream.ReadText(2) || "";
// Position must be at 0 before encoding can be changed
fileStream.Position = 0;
// [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8
@@ -114,28 +114,28 @@ namespace ts {
}
function getNames(collection: any): string[]{
var result: string[] = [];
for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
let result: string[] = [];
for (let e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
result.push(e.item().Name);
}
return result.sort();
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
var result: string[] = [];
let result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path);
return result;
function visitDirectory(path: string) {
var folder = fso.GetFolder(path || ".");
var files = getNames(folder.files);
let folder = fso.GetFolder(path || ".");
let files = getNames(folder.files);
for (let current of files) {
let name = combinePaths(path, current);
if ((!extension || fileExtensionIs(name, extension)) && !contains(exclude, getCanonicalPath(name))) {
result.push(name);
}
}
var subfolders = getNames(folder.subfolders);
let subfolders = getNames(folder.subfolders);
for (let current of subfolders) {
let name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
@@ -197,14 +197,14 @@ namespace ts {
if (!_fs.existsSync(fileName)) {
return undefined;
}
var buffer = _fs.readFileSync(fileName);
var len = buffer.length;
let buffer = _fs.readFileSync(fileName);
let len = buffer.length;
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
// Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
// flip all byte pairs and treat as little endian.
len &= ~1;
for (var i = 0; i < len; i += 2) {
var temp = buffer[i];
for (let i = 0; i < len; i += 2) {
let temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
}
@@ -236,17 +236,17 @@ namespace ts {
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
var result: string[] = [];
let result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path);
return result;
function visitDirectory(path: string) {
var files = _fs.readdirSync(path || ".").sort();
var directories: string[] = [];
let files = _fs.readdirSync(path || ".").sort();
let directories: string[] = [];
for (let current of files) {
var name = combinePaths(path, current);
let name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
var stat = _fs.statSync(name);
let stat = _fs.statSync(name);
if (stat.isFile()) {
if (!extension || fileExtensionIs(name, extension)) {
result.push(name);
@@ -331,4 +331,4 @@ namespace ts {
return undefined; // Unsupported host
}
})();
}
}
+54 -53
View File
@@ -11,15 +11,15 @@ namespace ts {
* and if it is, attempts to set the appropriate language.
*/
function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp'));
return false;
}
var language = matchResult[1];
var territory = matchResult[3];
let language = matchResult[1];
let territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
if (!trySetLanguageAndTerritory(language, territory, errors) &&
@@ -33,10 +33,10 @@ namespace ts {
}
function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean {
var compilerFilePath = normalizePath(sys.getExecutingFilePath());
var containingDirectoryPath = getDirectoryPath(compilerFilePath);
let compilerFilePath = normalizePath(sys.getExecutingFilePath());
let containingDirectoryPath = getDirectoryPath(compilerFilePath);
var filePath = combinePaths(containingDirectoryPath, language);
let filePath = combinePaths(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
@@ -49,8 +49,9 @@ namespace ts {
}
// TODO: Add codePage support for readFile?
let fileContents = '';
try {
var fileContents = sys.readFile(filePath);
fileContents = sys.readFile(filePath);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath));
@@ -68,7 +69,7 @@ namespace ts {
}
function countLines(program: Program): number {
var count = 0;
let count = 0;
forEach(program.getSourceFiles(), file => {
count += getLineStarts(file).length;
});
@@ -76,27 +77,27 @@ namespace ts {
}
function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string {
var diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
let diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
return <string>diagnostic.messageText;
}
function reportDiagnostic(diagnostic: Diagnostic) {
var output = "";
let output = "";
if (diagnostic.file) {
var loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `;
}
var category = DiagnosticCategory[diagnostic.category].toLowerCase();
let category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`;
sys.write(output);
}
function reportDiagnostics(diagnostics: Diagnostic[]) {
for (var i = 0; i < diagnostics.length; i++) {
for (let i = 0; i < diagnostics.length; i++) {
reportDiagnostic(diagnostics[i]);
}
}
@@ -133,15 +134,15 @@ namespace ts {
}
export function executeCommandLine(args: string[]): void {
var commandLine = parseCommandLine(args);
var configFileName: string; // Configuration file name (if any)
var configFileWatcher: FileWatcher; // Configuration file watcher
var cachedProgram: Program; // Program cached from last compilation
var rootFileNames: string[]; // Root fileNames for compilation
var compilerOptions: CompilerOptions; // Compiler options for compilation
var compilerHost: CompilerHost; // Compiler host
var hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host
var timerHandle: number; // Handle for 0.25s wait timer
let commandLine = parseCommandLine(args);
let configFileName: string; // Configuration file name (if any)
let configFileWatcher: FileWatcher; // Configuration file watcher
let cachedProgram: Program; // Program cached from last compilation
let rootFileNames: string[]; // Root fileNames for compilation
let compilerOptions: CompilerOptions; // Compiler options for compilation
let compilerHost: CompilerHost; // Compiler host
let hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host
let timerHandle: number; // Handle for 0.25s wait timer
if (commandLine.options.locale) {
if (!isJSONSupported()) {
@@ -181,7 +182,7 @@ namespace ts {
}
}
else if (commandLine.fileNames.length === 0 && isJSONSupported()) {
var searchPath = normalizePath(sys.getCurrentDirectory());
let searchPath = normalizePath(sys.getCurrentDirectory());
configFileName = findConfigFile(searchPath);
}
@@ -247,14 +248,14 @@ namespace ts {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) {
// Return existing SourceFile object if one is available
if (cachedProgram) {
var sourceFile = cachedProgram.getSourceFile(fileName);
let sourceFile = cachedProgram.getSourceFile(fileName);
// A modified source file has no watcher and should not be reused
if (sourceFile && sourceFile.fileWatcher) {
return sourceFile;
}
}
// Use default host function
var sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
let sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
if (sourceFile && compilerOptions.watch) {
// Attach a file watcher
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, () => sourceFileChanged(sourceFile));
@@ -265,7 +266,7 @@ namespace ts {
// Change cached program to the given program
function setCachedProgram(program: Program) {
if (cachedProgram) {
var newSourceFiles = program ? program.getSourceFiles() : undefined;
let newSourceFiles = program ? program.getSourceFiles() : undefined;
forEach(cachedProgram.getSourceFiles(), sourceFile => {
if (!(newSourceFiles && contains(newSourceFiles, sourceFile))) {
if (sourceFile.fileWatcher) {
@@ -316,8 +317,8 @@ namespace ts {
checkTime = 0;
emitTime = 0;
var program = createProgram(fileNames, compilerOptions, compilerHost);
var exitStatus = compileProgram();
let program = createProgram(fileNames, compilerOptions, compilerHost);
let exitStatus = compileProgram();
if (compilerOptions.listFiles) {
forEach(program.getSourceFiles(), file => {
@@ -326,7 +327,7 @@ namespace ts {
}
if (compilerOptions.diagnostics) {
var memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
let memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
reportCountStatistic("Files", program.getSourceFiles().length);
reportCountStatistic("Lines", countLines(program));
reportCountStatistic("Nodes", program.getNodeCount());
@@ -354,18 +355,18 @@ namespace ts {
return { program, exitStatus };
function compileProgram(): ExitStatus {
// First get any syntactic errors.
var diagnostics = program.getSyntacticDiagnostics();
// First get any syntactic errors.
let diagnostics = program.getSyntacticDiagnostics();
reportDiagnostics(diagnostics);
// If we didn't have any syntactic errors, then also try getting the global and
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === 0) {
var diagnostics = program.getGlobalDiagnostics();
let diagnostics = program.getGlobalDiagnostics();
reportDiagnostics(diagnostics);
if (diagnostics.length === 0) {
var diagnostics = program.getSemanticDiagnostics();
let diagnostics = program.getSemanticDiagnostics();
reportDiagnostics(diagnostics);
}
}
@@ -378,7 +379,7 @@ namespace ts {
}
// Otherwise, emit and report any errors we ran into.
var emitOutput = program.emit();
let emitOutput = program.emit();
reportDiagnostics(emitOutput.diagnostics);
// If the emitter didn't emit anything, then pass that value along.
@@ -401,22 +402,22 @@ namespace ts {
}
function printHelp() {
var output = "";
let output = "";
// We want to align our "syntax" and "examples" commands to a certain margin.
var syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length;
var examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length;
var marginLength = Math.max(syntaxLength, examplesLength);
let syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length;
let examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length;
let marginLength = Math.max(syntaxLength, examplesLength);
// Build up the syntactic skeleton.
var syntax = makePadding(marginLength - syntaxLength);
let syntax = makePadding(marginLength - syntaxLength);
syntax += "tsc [" + getDiagnosticText(Diagnostics.options) + "] [" + getDiagnosticText(Diagnostics.file) + " ...]";
output += getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax);
output += sys.newLine + sys.newLine;
// Build up the list of examples.
var padding = makePadding(marginLength);
let padding = makePadding(marginLength);
output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine;
output += padding + "tsc --out file.js file.ts" + sys.newLine;
output += padding + "tsc @args.txt" + sys.newLine;
@@ -425,17 +426,17 @@ namespace ts {
output += getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine;
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
var optsList = filter(optionDeclarations.slice(), v => !v.experimental);
let optsList = filter(optionDeclarations.slice(), v => !v.experimental);
optsList.sort((a, b) => compareValues<string>(a.name.toLowerCase(), b.name.toLowerCase()));
// We want our descriptions to align at the same column in our output,
// so we keep track of the longest option usage string.
var marginLength = 0;
var usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
var descriptionColumn: string[] = [];
marginLength = 0;
let usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
let descriptionColumn: string[] = [];
for (var i = 0; i < optsList.length; i++) {
var option = optsList[i];
for (let i = 0; i < optsList.length; i++) {
let option = optsList[i];
// If an option lacks a description,
// it is not officially supported.
@@ -443,7 +444,7 @@ namespace ts {
continue;
}
var usageText = " ";
let usageText = " ";
if (option.shortName) {
usageText += "-" + option.shortName;
usageText += getParamType(option);
@@ -461,15 +462,15 @@ namespace ts {
}
// Special case that can't fit in the loop.
var usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">";
let usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">";
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file));
marginLength = Math.max(usageText.length, marginLength);
// Print out each row, aligning all the descriptions on the same column.
for (var i = 0; i < usageColumn.length; i++) {
var usage = usageColumn[i];
var description = descriptionColumn[i];
for (let i = 0; i < usageColumn.length; i++) {
let usage = usageColumn[i];
let description = descriptionColumn[i];
output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine;
}
+116 -81
View File
@@ -140,8 +140,11 @@ namespace ts {
StaticKeyword,
YieldKeyword,
// Contextual keywords
AbstractKeyword,
AsKeyword,
AnyKeyword,
AsyncKeyword,
AwaitKeyword,
BooleanKeyword,
ConstructorKeyword,
DeclareKeyword,
@@ -188,6 +191,7 @@ namespace ts {
ArrayType,
TupleType,
UnionType,
IntersectionType,
ParenthesizedType,
// Binding patterns
ObjectBindingPattern,
@@ -208,6 +212,7 @@ namespace ts {
DeleteExpression,
TypeOfExpression,
VoidExpression,
AwaitExpression,
PrefixUnaryExpression,
PostfixUnaryExpression,
BinaryExpression,
@@ -268,7 +273,7 @@ namespace ts {
// Module references
ExternalModuleReference,
//JSX
// JSX
JsxElement,
JsxSelfClosingElement,
JsxOpeningElement,
@@ -356,17 +361,19 @@ namespace ts {
Private = 0x00000020, // Property/Method
Protected = 0x00000040, // Property/Method
Static = 0x00000080, // Property/Method
Default = 0x00000100, // Function/Class (export default declaration)
MultiLine = 0x00000200, // Multi-line array or object literal
Synthetic = 0x00000400, // Synthetic node (for full fidelity)
DeclarationFile = 0x00000800, // Node is a .d.ts file
Let = 0x00001000, // Variable declaration
Const = 0x00002000, // Variable declaration
OctalLiteral = 0x00004000, // Octal numeric literal
Namespace = 0x00008000, // Namespace declaration
ExportContext = 0x00010000, // Export context (initialized by binding)
Abstract = 0x00000100, // Class/Method/ConstructSignature
Async = 0x00000200, // Property/Method/Function
Default = 0x00000400, // Function/Class (export default declaration)
MultiLine = 0x00000800, // Multi-line array or object literal
Synthetic = 0x00001000, // Synthetic node (for full fidelity)
DeclarationFile = 0x00002000, // Node is a .d.ts file
Let = 0x00004000, // Variable declaration
Const = 0x00008000, // Variable declaration
OctalLiteral = 0x00010000, // Octal numeric literal
Namespace = 0x00020000, // Namespace declaration
ExportContext = 0x00040000, // Export context (initialized by binding)
Modifier = Export | Ambient | Public | Private | Protected | Static | Default,
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async,
AccessibilityModifier = Public | Private | Protected,
BlockScoped = Let | Const
}
@@ -376,37 +383,40 @@ namespace ts {
None = 0,
// If this node was parsed in a context where 'in-expressions' are not allowed.
DisallowIn = 1 << 1,
DisallowIn = 1 << 0,
// If this node was parsed in the 'yield' context created when parsing a generator.
Yield = 1 << 2,
// If this node was parsed in the parameters of a generator.
GeneratorParameter = 1 << 3,
Yield = 1 << 1,
// If this node was parsed as part of a decorator
Decorator = 1 << 4,
Decorator = 1 << 2,
// If this node was parsed in the 'await' context created when parsing an async function.
Await = 1 << 3,
// If the parser encountered an error when parsing the code that created this node. Note
// the parser only sets this directly on the node it creates right after encountering the
// error.
ThisNodeHasError = 1 << 5,
ThisNodeHasError = 1 << 4,
// This node was parsed in a JavaScript file and can be processed differently. For example
// its type can be specified usign a JSDoc comment.
JavaScriptFile = 1 << 6,
JavaScriptFile = 1 << 5,
// Context flags set directly by the parser.
ParserGeneratedFlags = DisallowIn | Yield | GeneratorParameter | Decorator | ThisNodeHasError,
ParserGeneratedFlags = DisallowIn | Yield | Decorator | ThisNodeHasError | Await,
// Exclude these flags when parsing a Type
TypeExcludesFlags = Yield | Await,
// Context flags computed by aggregating child flags upwards.
// Used during incremental parsing to determine if this node or any of its children had an
// error. Computed only once and then cached.
ThisNodeOrAnySubNodesHasError = 1 << 7,
ThisNodeOrAnySubNodesHasError = 1 << 6,
// Used to know if we've computed data from children and cached it in this node.
HasAggregatedChildData = 1 << 8
HasAggregatedChildData = 1 << 7
}
export const enum JsxFlags {
@@ -658,10 +668,14 @@ namespace ts {
elementTypes: NodeArray<TypeNode>;
}
export interface UnionTypeNode extends TypeNode {
export interface UnionOrIntersectionTypeNode extends TypeNode {
types: NodeArray<TypeNode>;
}
export interface UnionTypeNode extends UnionOrIntersectionTypeNode { }
export interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { }
export interface ParenthesizedTypeNode extends TypeNode {
type: TypeNode;
}
@@ -726,6 +740,10 @@ namespace ts {
expression: UnaryExpression;
}
export interface AwaitExpression extends UnaryExpression {
expression: UnaryExpression;
}
export interface YieldExpression extends Expression {
asteriskToken?: Node;
expression?: Expression;
@@ -1037,7 +1055,7 @@ namespace ts {
}
export interface ModuleBlock extends Node, Statement {
statements: NodeArray<Statement>
statements: NodeArray<Statement>;
}
export interface ImportEqualsDeclaration extends Declaration, Statement {
@@ -1153,7 +1171,7 @@ namespace ts {
export interface JSDocTypeReference extends JSDocType {
name: EntityName;
typeArguments: NodeArray<JSDocType>
typeArguments: NodeArray<JSDocType>;
}
export interface JSDocOptionalType extends JSDocType {
@@ -1178,8 +1196,8 @@ namespace ts {
}
export interface JSDocRecordMember extends PropertyDeclaration {
name: Identifier | LiteralExpression,
type?: JSDocType
name: Identifier | LiteralExpression;
type?: JSDocType;
}
export interface JSDocComment extends Node {
@@ -1272,6 +1290,15 @@ namespace ts {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
export class OperationCanceledException { }
export interface CancellationToken {
isCancellationRequested(): boolean;
/** @throws OperationCanceledException if isCancellationRequested is true */
throwIfCancellationRequested(): void;
}
export interface Program extends ScriptReferenceHost {
/**
* Get a list of files in the program
@@ -1288,15 +1315,15 @@ namespace ts {
* used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
* will be invoked when writing the JavaScript and declaration files.
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
getOptionsDiagnostics(): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/**
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
getTypeChecker(): TypeChecker;
@@ -1317,15 +1344,15 @@ namespace ts {
export interface SourceMapSpan {
/** Line number in the .js file. */
emittedLine: number;
emittedLine: number;
/** Column number in the .js file. */
emittedColumn: number;
emittedColumn: number;
/** Line number in the .ts file. */
sourceLine: number;
sourceLine: number;
/** Column number in the .ts file. */
sourceColumn: number;
sourceColumn: number;
/** Optional name (index into names array) associated with this span. */
nameIndex?: number;
nameIndex?: number;
/** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
@@ -1405,9 +1432,9 @@ namespace ts {
getJsxIntrinsicTagNames(): Symbol[];
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/* @internal */ getGlobalDiagnostics(): Diagnostic[];
/* @internal */ getEmitResolver(sourceFile?: SourceFile): EmitResolver;
/* @internal */ getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver;
/* @internal */ getNodeCount(): number;
/* @internal */ getIdentifierCount(): number;
@@ -1479,7 +1506,7 @@ namespace ts {
NotAccessible,
CannotBeNamed
}
export interface TypePredicate {
parameterName: string;
parameterIndex: number;
@@ -1499,7 +1526,7 @@ namespace ts {
/* @internal */
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string // If the symbol is not visible from module, module's name
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator
@@ -1579,7 +1606,7 @@ namespace ts {
Merged = 0x02000000, // Merged symbol (created during program binding)
Transient = 0x04000000, // Transient symbol (created during type check)
Prototype = 0x08000000, // Prototype property (no source representation)
UnionProperty = 0x10000000, // Property in union type
SyntheticProperty = 0x10000000, // Property in union or intersection type
Optional = 0x20000000, // Optional property
ExportStar = 0x40000000, // Export * declaration
@@ -1603,8 +1630,8 @@ namespace ts {
PropertyExcludes = Value,
EnumMemberExcludes = Value,
FunctionExcludes = Value & ~(Function | ValueModule),
ClassExcludes = (Value | Type) & ~ValueModule,
InterfaceExcludes = Type & ~Interface,
ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts
InterfaceExcludes = Type & ~(Interface | Class),
RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules
ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule),
@@ -1629,7 +1656,7 @@ namespace ts {
Export = ExportNamespace | ExportType | ExportValue,
/* @internal */
// The set of things we consider semantically classifiable. Used to speed up the LS during
// The set of things we consider semantically classifiable. Used to speed up the LS during
// classification.
Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module,
}
@@ -1649,7 +1676,7 @@ namespace ts {
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
}
/* @internal */
/* @internal */
export interface SymbolLinks {
target?: Symbol; // Resolved (non-alias) target of an alias
type?: Type; // Type of value symbol
@@ -1658,40 +1685,45 @@ namespace ts {
instantiations?: Map<Type>; // Instantiations of generic type alias (undefined if non-generic)
mapper?: TypeMapper; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value
unionType?: UnionType; // Containing union type for union property
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
isNestedRedeclaration?: boolean; // True if symbol is block scoped redeclaration
}
/* @internal */
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks { }
export interface SymbolTable {
[index: string]: Symbol;
}
/* @internal */
/* @internal */
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
EmitExtends = 0x00000008, // Emit __extends
SuperInstance = 0x00000010, // Instance 'super' reference
SuperStatic = 0x00000020, // Static 'super' reference
ContextChecked = 0x00000040, // Contextual types have been assigned
EmitDecorate = 0x00000010, // Emit __decorate
EmitParam = 0x00000020, // Emit __param helper for decorators
EmitAwaiter = 0x00000040, // Emit __awaiter
EmitGenerator = 0x00000080, // Emit __generator
SuperInstance = 0x00000100, // Instance 'super' reference
SuperStatic = 0x00000200, // Static 'super' reference
ContextChecked = 0x00000400, // Contextual types have been assigned
LexicalArguments = 0x00000800,
CaptureArguments = 0x00001000, // Lexical 'arguments' used in body (for async functions)
// Values for enum members have been computed, and any errors have been reported for them.
EnumValuesComputed = 0x00000080,
BlockScopedBindingInLoop = 0x00000100,
EmitDecorate = 0x00000200, // Emit __decorate
EmitParam = 0x00000400, // Emit __param helper for decorators
LexicalModuleMergesWithClass = 0x00000800, // Instantiated lexical module declaration is merged with a previous class declaration.
EnumValuesComputed = 0x00002000,
BlockScopedBindingInLoop = 0x00004000,
LexicalModuleMergesWithClass= 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
}
/* @internal */
/* @internal */
export interface NodeLinks {
resolvedType?: Type; // Cached type of type node
resolvedAwaitedType?: Type; // Cached awaited type of type node
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
flags?: NodeCheckFlags; // Set of flags specific to Node
@@ -1722,27 +1754,30 @@ namespace ts {
Interface = 0x00000800, // Interface
Reference = 0x00001000, // Generic type reference
Tuple = 0x00002000, // Tuple
Union = 0x00004000, // Union
Anonymous = 0x00008000, // Anonymous
Instantiated = 0x00010000, // Instantiated anonymous type
Union = 0x00004000, // Union (T | U)
Intersection = 0x00008000, // Intersection (T & U)
Anonymous = 0x00010000, // Anonymous
Instantiated = 0x00020000, // Instantiated anonymous type
/* @internal */
FromSignature = 0x00020000, // Created for signature assignment check
ObjectLiteral = 0x00040000, // Originates in an object literal
FromSignature = 0x00040000, // Created for signature assignment check
ObjectLiteral = 0x00080000, // Originates in an object literal
/* @internal */
ContainsUndefinedOrNull = 0x00080000, // Type is or contains Undefined or Null type
ContainsUndefinedOrNull = 0x00100000, // Type is or contains Undefined or Null type
/* @internal */
ContainsObjectLiteral = 0x00100000, // Type is or contains object literal type
ESSymbol = 0x00200000, // Type of symbol primitive introduced in ES6
ContainsObjectLiteral = 0x00200000, // Type is or contains object literal type
ESSymbol = 0x00400000, // Type of symbol primitive introduced in ES6
/* @internal */
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
/* @internal */
/* @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
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
}
// Properties common to all types
@@ -1752,7 +1787,7 @@ namespace ts {
symbol?: Symbol; // Symbol associated with type (if any)
}
/* @internal */
/* @internal */
// Intrinsic types (TypeFlags.Intrinsic)
export interface IntrinsicType extends Type {
intrinsicName: string; // Name of intrinsic type
@@ -1800,7 +1835,7 @@ namespace ts {
baseArrayType: TypeReference; // Array<T> where T is best common type of element types
}
export interface UnionType extends Type {
export interface UnionOrIntersectionType extends Type {
types: Type[]; // Constituent types
/* @internal */
reducedType: Type; // Reduced union type (all subtypes removed)
@@ -1808,9 +1843,13 @@ namespace ts {
resolvedProperties: SymbolTable; // Cache of resolved properties
}
export interface UnionType extends UnionOrIntersectionType { }
export interface IntersectionType extends UnionOrIntersectionType { }
/* @internal */
// Resolved object or union type
export interface ResolvedType extends ObjectType, UnionType {
// Resolved object, union, or intersection type
export interface ResolvedType extends ObjectType, UnionOrIntersectionType {
members: SymbolTable; // Properties by name
properties: Symbol[]; // Properties
callSignatures: Signature[]; // Call signatures of type
@@ -1963,6 +2002,7 @@ namespace ts {
watch?: boolean;
isolatedModules?: boolean;
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
/* @internal */ stripInternal?: boolean;
@@ -2166,14 +2206,9 @@ namespace ts {
verticalTab = 0x0B, // \v
}
export interface CancellationToken {
isCancellationRequested(): boolean;
}
export interface CompilerHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getDefaultLibFileName(options: CompilerOptions): string;
getCancellationToken? (): CancellationToken;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
+98 -74
View File
@@ -3,9 +3,9 @@
/* @internal */
namespace ts {
export interface ReferencePathMatchResult {
fileReference?: FileReference
diagnosticMessage?: DiagnosticMessage
isNoDefaultLib?: boolean
fileReference?: FileReference;
diagnosticMessage?: DiagnosticMessage;
isNoDefaultLib?: boolean;
}
export interface SynthesizedNode extends Node {
@@ -16,9 +16,11 @@ namespace ts {
export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration {
let declarations = symbol.declarations;
for (let declaration of declarations) {
if (declaration.kind === kind) {
return declaration;
if (declarations) {
for (let declaration of declarations) {
if (declaration.kind === kind) {
return declaration;
}
}
}
@@ -70,7 +72,7 @@ namespace ts {
}
export function releaseStringWriter(writer: StringSymbolWriter) {
writer.clear()
writer.clear();
stringWriters.push(writer);
}
@@ -81,7 +83,7 @@ namespace ts {
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0
return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0;
}
function aggregateChildData(node: Node): void {
@@ -92,7 +94,7 @@ namespace ts {
let thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) ||
forEachChild(node, containsParseError);
// If so, mark ourselves accordingly.
// If so, mark ourselves accordingly.
if (thisNodeOrAnySubNodesHasError) {
node.parserContextFlags |= ParserContextFlags.ThisNodeOrAnySubNodesHasError;
}
@@ -129,13 +131,13 @@ namespace ts {
// Returns true if this node is missing from the actual source code. 'missing' is different
// from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
// in the tree), it is definitel missing. HOwever, a node may be defined, but still be
// in the tree), it is definitel missing. HOwever, a node may be defined, but still be
// missing. This happens whenever the parser knows it needs to parse something, but can't
// get anything in the source code that it expects at that location. For example:
//
// let a: ;
//
// Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
// Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
// code). So the parser will attempt to parse out a type, and will create an actual node.
// However, this node will be 'missing' in the sense that no actual source-code/tokens are
// contained within it.
@@ -144,7 +146,7 @@ namespace ts {
return true;
}
return node.pos === node.end && node.kind !== SyntaxKind.EndOfFileToken;
return node.pos === node.end && node.pos >= 0 && node.kind !== SyntaxKind.EndOfFileToken;
}
export function nodeIsPresent(node: Node) {
@@ -166,7 +168,7 @@ namespace ts {
return getTokenPosOfNode(node, sourceFile);
}
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia = false): string {
@@ -211,7 +213,7 @@ namespace ts {
isCatchClauseVariableDeclaration(declaration);
}
// Gets the nearest enclosing block scope container that has the provided node
// Gets the nearest enclosing block scope container that has the provided node
// as a descendant, that is not the provided node.
export function getEnclosingBlockScopeContainer(node: Node): Node {
let current = node.parent;
@@ -307,7 +309,7 @@ namespace ts {
}
if (errorNode === undefined) {
// If we don't have a better node, then just set the error on the first token of
// If we don't have a better node, then just set the error on the first token of
// construct.
return getSpanOfTokenAtPosition(sourceFile, node.pos);
}
@@ -339,10 +341,10 @@ namespace ts {
return node;
}
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// nodes like variable declarations and binding elements can returned a view of their flags
// that includes the modifiers from their container. i.e. flags like export/declare aren't
// stored on the variable declaration directly, but on the containing variable statement
// stored on the variable declaration directly, but on the containing variable statement
// (if it has one). Similarly, flags for let/const are store on the variable declaration
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
@@ -406,7 +408,7 @@ namespace ts {
}
}
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export function isTypeNode(node: Node): boolean {
if (SyntaxKind.FirstTypeNode <= node.kind && node.kind <= SyntaxKind.LastTypeNode) {
@@ -662,7 +664,7 @@ namespace ts {
node = node.parent;
break;
case SyntaxKind.Decorator:
// Decorators are always applied outside of the body of a class or method.
// 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.
@@ -717,7 +719,7 @@ namespace ts {
node = node.parent;
break;
case SyntaxKind.Decorator:
// Decorators are always applied outside of the body of a class or method.
// 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.
@@ -747,11 +749,27 @@ namespace ts {
}
}
export function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression {
if (node) {
switch (node.kind) {
case SyntaxKind.TypeReference:
return (<TypeReferenceNode>node).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>node).expression;
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
return (<EntityName><Node>node);
}
}
return undefined;
}
export function getInvokedExpression(node: CallLikeExpression): Expression {
if (node.kind === SyntaxKind.TaggedTemplateExpression) {
return (<TaggedTemplateExpression>node).tag;
}
// Will either be a CallExpression, NewExpression, or Decorator.
return (<CallExpression | Decorator>node).expression;
}
@@ -933,7 +951,7 @@ namespace ts {
}
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
let moduleState = getModuleInstanceState(node)
let moduleState = getModuleInstanceState(node);
return moduleState === ModuleInstanceState.Instantiated ||
(preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly);
}
@@ -1015,7 +1033,7 @@ namespace ts {
export function getCorrespondingJSDocParameterTag(parameter: ParameterDeclaration): JSDocParameterTag {
if (parameter.name && parameter.name.kind === SyntaxKind.Identifier) {
// If it's a parameter, see if the parent has a jsdoc comment with an @param
// If it's a parameter, see if the parent has a jsdoc comment with an @param
// annotation.
let parameterName = (<Identifier>parameter.name).text;
@@ -1285,7 +1303,7 @@ namespace ts {
if (isNoDefaultLibRegEx.exec(comment)) {
return {
isNoDefaultLib: true
}
};
}
else {
let matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
@@ -1321,6 +1339,10 @@ namespace ts {
return SyntaxKind.FirstTriviaToken <= token && token <= SyntaxKind.LastTriviaToken;
}
export function isAsyncFunctionLike(node: Node): boolean {
return isFunctionLike(node) && (node.flags & NodeFlags.Async) !== 0 && !isAccessor(node);
}
/**
* A declaration has a dynamic name if both of the following are true:
* 1. The declaration has a computed property name
@@ -1371,14 +1393,16 @@ namespace ts {
export function isModifier(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DefaultKeyword:
return true;
}
return false;
@@ -1395,7 +1419,7 @@ namespace ts {
}
return node;
}
export function nodeStartsNewLexicalEnvironment(n: Node): boolean {
return isFunctionLike(n) || n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.SourceFile;
}
@@ -1406,14 +1430,12 @@ namespace ts {
export function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node {
let node = <SynthesizedNode>createNode(kind);
node.pos = -1;
node.end = -1;
node.startsOnNewLine = startsOnNewLine;
return node;
}
export function createSynthesizedNodeArray(): NodeArray<any> {
var array = <NodeArray<any>>[];
let array = <NodeArray<any>>[];
array.pos = -1;
array.end = -1;
return array;
@@ -1497,7 +1519,7 @@ namespace ts {
}
}
}
// This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
// paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
// the language service. These characters should be escaped when printing, and if any characters are added,
@@ -1883,10 +1905,12 @@ namespace ts {
case SyntaxKind.PublicKeyword: return NodeFlags.Public;
case SyntaxKind.ProtectedKeyword: return NodeFlags.Protected;
case SyntaxKind.PrivateKeyword: return NodeFlags.Private;
case SyntaxKind.AbstractKeyword: return NodeFlags.Abstract;
case SyntaxKind.ExportKeyword: return NodeFlags.Export;
case SyntaxKind.DeclareKeyword: return NodeFlags.Ambient;
case SyntaxKind.ConstKeyword: return NodeFlags.Const;
case SyntaxKind.DefaultKeyword: return NodeFlags.Default;
case SyntaxKind.AsyncKeyword: return NodeFlags.Async;
}
return 0;
}
@@ -1970,7 +1994,7 @@ namespace ts {
}
/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* representing the UTF-8 encoding of the character, and return the expanded char code list.
*/
function getExpandedCharCodes(input: string): number[] {
@@ -2013,7 +2037,7 @@ namespace ts {
* Converts a string to a base-64 encoded ASCII string.
*/
export function convertToBase64(input: string): string {
var result = "";
let result = "";
let charCodes = getExpandedCharCodes(input);
let i = 0;
let length = charCodes.length;
@@ -2055,7 +2079,7 @@ namespace ts {
return lineFeed;
}
else if (sys) {
return sys.newLine
return sys.newLine;
}
return carriageReturnLineFeed;
}
@@ -2067,11 +2091,11 @@ namespace ts {
}
export function textSpanEnd(span: TextSpan) {
return span.start + span.length
return span.start + span.length;
}
export function textSpanIsEmpty(span: TextSpan) {
return span.length === 0
return span.length === 0;
}
export function textSpanContainsPosition(span: TextSpan, position: number) {
@@ -2099,7 +2123,7 @@ namespace ts {
}
export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) {
return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start
return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start;
}
export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) {
@@ -2160,10 +2184,10 @@ namespace ts {
export let unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0);
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* 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.
*
* 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.
*/
@@ -2194,17 +2218,17 @@ namespace ts {
//
// 0 10 20 30 40 50 60 70 80 90 100
// -------------------------------------------------------------------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// | /
// | /----
// T1 | /----
// | /----
// | /----
// -------------------------------------------------------------------------------------------------------
// | \
// | \
// T2 | \
// | \
// | \
// | \
// | \
// T2 | \
// | \
// | \
// -------------------------------------------------------------------------------------------------------
//
// Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
@@ -2212,17 +2236,17 @@ namespace ts {
//
// 0 10 20 30 40 50 60 70 80 90 100
// ------------------------------------------------------------*------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ----------------------------------------$-------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// (Note the dots represent the newly inferrred start.
@@ -2233,22 +2257,22 @@ namespace ts {
//
// 0 10 20 30 40 50 60 70 80 90 100
// --------------------------------------------------------------------------------*----------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ------------------------------------------------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// In other words (in this case), we're recognizing that the second edit happened after where the first edit
// ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
// that's the same as if we started at char 80 instead of 60.
// that's the same as if we started at char 80 instead of 60.
//
// As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter
// than pusing the first edit forward to match the second, we'll push the second edit forward to match the
@@ -2258,7 +2282,7 @@ namespace ts {
// semantics: { { start: 10, length: 70 }, newLength: 60 }
//
// The math then works out as follows.
// If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
// If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
// final result like so:
//
// {
+57 -9
View File
@@ -190,14 +190,14 @@ module FourSlash {
return "\nMarker: " + currentTestState.lastKnownMarker + "\nChecking: " + msg + "\n\n";
}
export class TestCancellationToken implements ts.CancellationToken {
export class TestCancellationToken implements ts.HostCancellationToken {
// 0 - cancelled
// >0 - not cancelled
// <0 - not cancelled and value denotes number of isCancellationRequested after which token become cancelled
private static NotCancelled: number = -1;
private numberOfCallsBeforeCancellation: number = TestCancellationToken.NotCancelled;
public isCancellationRequested(): boolean {
private static NotCanceled: number = -1;
private numberOfCallsBeforeCancellation: number = TestCancellationToken.NotCanceled;
public isCancellationRequested(): boolean {
if (this.numberOfCallsBeforeCancellation < 0) {
return false;
}
@@ -216,7 +216,7 @@ module FourSlash {
}
public resetCancelled(): void {
this.numberOfCallsBeforeCancellation = TestCancellationToken.NotCancelled;
this.numberOfCallsBeforeCancellation = TestCancellationToken.NotCanceled;
}
}
@@ -704,13 +704,61 @@ module FourSlash {
}
}
public verifyCompletionListDoesNotContain(symbol: string) {
/**
* Verify that the completion list does NOT contain the given symbol.
* The symbol is considered matched with the symbol in the list if and only if all given parameters must matched.
* When any parameter is omitted, the parameter is ignored during comparison and assumed that the parameter with
* that property of the symbol in the list.
* @param symbol the name of symbol
* @param expectedText the text associated with the symbol
* @param expectedDocumentation the documentation text associated with the symbol
* @param expectedKind the kind of symbol (see ScriptElementKind)
*/
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) {
let that = this;
function filterByTextOrDocumentation(entry: ts.CompletionEntry) {
let details = that.getCompletionEntryDetails(entry.name);
let documentation = ts.displayPartsToString(details.documentation);
let text = ts.displayPartsToString(details.displayParts);
if (expectedText && expectedDocumentation) {
return (documentation === expectedDocumentation && text === expectedText) ? true : false;
}
else if (expectedText && !expectedDocumentation) {
return text === expectedText ? true : false;
}
else if (expectedDocumentation && !expectedText) {
return documentation === expectedDocumentation ? true : false;
}
// Because expectedText and expectedDocumentation are undefined, we assume that
// users don't care to compare them so we will treat that entry as if the entry has matching text and documentation
// and keep it in the list of filtered entry.
return true;
}
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
var completions = this.getCompletionListAtCaret();
if (completions && completions.entries.filter(e => e.name === symbol).length !== 0) {
this.raiseError('Completion list did contain ' + symbol);
if (completions) {
let filterCompletions = completions.entries.filter(e => e.name === symbol);
filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions;
filterCompletions = filterCompletions.filter(filterByTextOrDocumentation);
if (filterCompletions.length !== 0) {
// After filtered using all present criterion, if there are still symbol left in the list
// then these symbols must meet the criterion for Not supposed to be in the list. So we
// raise an error
let error = "Completion list did contain \'" + symbol + "\'.";
let details = this.getCompletionEntryDetails(filterCompletions[0].name);
if (expectedText) {
error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + ".";
}
if (expectedDocumentation) {
error += "Expected documentation: " + expectedDocumentation + " to equal: " + ts.displayPartsToString(details.documentation) + ".";
}
if (expectedKind) {
error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + "."
}
this.raiseError(error);
}
}
}
@@ -2167,7 +2215,7 @@ module FourSlash {
var itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n");
this.raiseError('Expected "' + JSON.stringify({ name: name, text: text, documentation: documentation, kind: kind }) + '" to be in list [' + itemsString + ']');
this.raiseError('Expected "' + JSON.stringify({ name, text, documentation, kind }) + '" to be in list [' + itemsString + ']');
}
private findFile(indexOrName: any) {
+4 -4
View File
@@ -35,9 +35,9 @@ class FourSlashRunner extends RunnerBase {
this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false });
}
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
var justName = fn.replace(/^.*[\\\/]/, '');
// Convert to relative path
@@ -45,7 +45,7 @@ class FourSlashRunner extends RunnerBase {
if (testIndex >= 0) fn = fn.substr(testIndex);
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
it(this.testSuiteName + ' test ' + justName + ' runs correctly',() => {
it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}
+4
View File
@@ -1055,6 +1055,10 @@ module Harness {
case 'emitdecoratormetadata':
options.emitDecoratorMetadata = setting.value === 'true';
break;
case 'experimentalasyncfunctions':
options.experimentalAsyncFunctions = setting.value === 'true';
break;
case 'noemithelpers':
options.noEmitHelpers = setting.value === 'true';
+13 -16
View File
@@ -103,14 +103,11 @@ module Harness.LanguageService {
}
}
class CancellationToken {
public static None: CancellationToken = new CancellationToken(null);
constructor(private cancellationToken: ts.CancellationToken) {
}
class DefaultHostCancellationToken implements ts.HostCancellationToken {
public static Instance = new DefaultHostCancellationToken();
public isCancellationRequested() {
return this.cancellationToken && this.cancellationToken.isCancellationRequested();
return false;
}
}
@@ -124,8 +121,8 @@ module Harness.LanguageService {
export class LanguageServiceAdapterHost {
protected fileNameToScript: ts.Map<ScriptInfo> = {};
constructor(protected cancellationToken: ts.CancellationToken = CancellationToken.None,
protected settings = ts.getDefaultCompilerOptions()) {
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
protected settings = ts.getDefaultCompilerOptions()) {
}
public getNewLine(): string {
@@ -173,8 +170,8 @@ module Harness.LanguageService {
/// Native adapter
class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost {
getCompilationSettings(): ts.CompilerOptions { return this.settings; }
getCancellationToken(): ts.CancellationToken { return this.cancellationToken; }
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getCurrentDirectory(): string { return ""; }
getDefaultLibFileName(): string { return ""; }
getScriptFileNames(): string[] { return this.getFilenames(); }
@@ -194,7 +191,7 @@ module Harness.LanguageService {
export class NativeLanugageServiceAdapter implements LanguageServiceAdapter {
private host: NativeLanguageServiceHost;
constructor(cancellationToken?: ts.CancellationToken, options?: ts.CompilerOptions) {
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new NativeLanguageServiceHost(cancellationToken, options);
}
getHost() { return this.host; }
@@ -206,7 +203,7 @@ module Harness.LanguageService {
/// Shim adapter
class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceShimHost, ts.CoreServicesShimHost {
private nativeHost: NativeLanguageServiceHost;
constructor(cancellationToken?: ts.CancellationToken, options?: ts.CompilerOptions) {
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
this.nativeHost = new NativeLanguageServiceHost(cancellationToken, options);
}
@@ -218,7 +215,7 @@ module Harness.LanguageService {
positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter { return this.nativeHost.positionToLineAndCharacter(fileName, position); }
getCompilationSettings(): string { return JSON.stringify(this.nativeHost.getCompilationSettings()); }
getCancellationToken(): ts.CancellationToken { return this.nativeHost.getCancellationToken(); }
getCancellationToken(): ts.HostCancellationToken { return this.nativeHost.getCancellationToken(); }
getCurrentDirectory(): string { return this.nativeHost.getCurrentDirectory(); }
getDefaultLibFileName(): string { return this.nativeHost.getDefaultLibFileName(); }
getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); }
@@ -399,7 +396,7 @@ module Harness.LanguageService {
export class ShimLanugageServiceAdapter implements LanguageServiceAdapter {
private host: ShimLanguageServiceHost;
private factory: ts.TypeScriptServicesFactory;
constructor(cancellationToken?: ts.CancellationToken, options?: ts.CompilerOptions) {
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new ShimLanguageServiceHost(cancellationToken, options);
this.factory = new TypeScript.Services.TypeScriptServicesFactory();
}
@@ -446,7 +443,7 @@ module Harness.LanguageService {
class SessionClientHost extends NativeLanguageServiceHost implements ts.server.SessionClientHost {
private client: ts.server.SessionClient;
constructor(cancellationToken: ts.CancellationToken, settings: ts.CompilerOptions) {
constructor(cancellationToken: ts.HostCancellationToken, settings: ts.CompilerOptions) {
super(cancellationToken, settings);
}
@@ -575,7 +572,7 @@ module Harness.LanguageService {
export class ServerLanugageServiceAdapter implements LanguageServiceAdapter {
private host: SessionClientHost;
private client: ts.server.SessionClient;
constructor(cancellationToken?: ts.CancellationToken, options?: ts.CompilerOptions) {
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
// This is the main host that tests use to direct tests
var clientHost = new SessionClientHost(cancellationToken, options);
var client = new ts.server.SessionClient(clientHost);
+1
View File
@@ -49,6 +49,7 @@ if (testConfigFile !== '') {
if (!option) {
continue;
}
switch (option) {
case 'compiler':
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
+13
View File
@@ -1169,3 +1169,16 @@ declare type ClassDecorator = <TFunction extends Function>(target: TFunction) =>
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
+38 -64
View File
@@ -1092,16 +1092,11 @@ interface CanvasRenderingContext2D {
clearRect(x: number, y: number, w: number, h: number): void;
clip(fillRule?: string): void;
closePath(): void;
createImageData(imageDataOrSw: number, sh?: number): ImageData;
createImageData(imageDataOrSw: ImageData, sh?: number): ImageData;
createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createPattern(image: HTMLImageElement, repetition: string): CanvasPattern;
createPattern(image: HTMLCanvasElement, repetition: string): CanvasPattern;
createPattern(image: HTMLVideoElement, repetition: string): CanvasPattern;
createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
drawImage(image: HTMLImageElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLCanvasElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void;
fill(fillRule?: string): void;
fillRect(x: number, y: number, w: number, h: number): void;
fillText(text: string, x: number, y: number, maxWidth?: number): void;
@@ -2259,12 +2254,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
/**
* Gets a collection of objects based on the value of the NAME or ID attribute.
* @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.
*/
getElementsByName(elementName: string): NodeList;
getElementsByName(elementName: string): NodeListOf<Element>;
/**
* Retrieves a collection of objects based on the specified element name.
* @param name Specifies the name of an element.
@@ -2442,8 +2437,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
getElementsByTagName(tagname: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(tagname: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(tagname: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(tagname: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(tagname: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
/**
* Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
*/
@@ -2716,6 +2711,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
scrollTop: number;
scrollWidth: number;
tagName: string;
id: string;
className: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@@ -2895,8 +2892,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(name: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(name: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(name: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string, localName: string): boolean;
msGetRegionContent(): MSRangeCollection;
@@ -3077,7 +3074,7 @@ interface FormData {
declare var FormData: {
prototype: FormData;
new(): FormData;
new (form?: HTMLFormElement): FormData;
}
interface GainNode extends AudioNode {
@@ -3370,8 +3367,7 @@ interface HTMLAreasCollection extends HTMLCollection {
/**
* Adds an element to the areas, controlRange, or options collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Removes an element from the collection.
*/
@@ -3815,14 +3811,12 @@ declare var HTMLDocument: {
interface HTMLElement extends Element {
accessKey: string;
children: HTMLCollection;
className: string;
contentEditable: string;
dataset: DOMStringMap;
dir: string;
draggable: boolean;
hidden: boolean;
hideFocus: boolean;
id: string;
innerHTML: string;
innerText: string;
isContentEditable: boolean;
@@ -3909,7 +3903,7 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@@ -6119,8 +6113,7 @@ interface HTMLSelectElement extends HTMLElement {
* @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.
* @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.
*/
add(element: HTMLElement, before?: HTMLElement): void;
add(element: HTMLElement, before?: number): void;
add(element: HTMLElement, before?: HTMLElement | number): void;
/**
* Returns whether a form will validate when it is submitted, without having to submit it.
*/
@@ -8722,6 +8715,7 @@ declare var SVGDescElement: {
interface SVGElement extends Element {
id: string;
className: any;
onclick: (ev: MouseEvent) => any;
ondblclick: (ev: MouseEvent) => any;
onfocusin: (ev: FocusEvent) => any;
@@ -10281,8 +10275,7 @@ interface Screen extends EventTarget {
systemXDPI: number;
systemYDPI: number;
width: number;
msLockOrientation(orientations: string): boolean;
msLockOrientation(orientations: string[]): boolean;
msLockOrientation(orientations: string | string[]): boolean;
msUnlockOrientation(): void;
addEventListener(type: "MSOrientationChange", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -10354,8 +10347,7 @@ interface SourceBuffer extends EventTarget {
updating: boolean;
videoTracks: VideoTrackList;
abort(): void;
appendBuffer(data: ArrayBuffer): void;
appendBuffer(data: ArrayBufferView): void;
appendBuffer(data: ArrayBuffer | ArrayBufferView): void;
appendStream(stream: MSStream, maxSize?: number): void;
remove(start: number, end: number): void;
}
@@ -10463,33 +10455,18 @@ declare var StyleSheetPageList: {
}
interface SubtleCrypto {
decrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string, baseKey: CryptoKey, length: number): any;
deriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: string, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: string, extractable: boolean, keyUsages: string[]): any;
deriveKey(algorithm: Algorithm, baseKey: CryptoKey, derivedKeyType: Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string, data: ArrayBufferView): any;
digest(algorithm: Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
encrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any;
deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
digest(algorithm: string | Algorithm, data: ArrayBufferView): any;
encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
exportKey(format: string, key: CryptoKey): any;
generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): any;
generateKey(algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string, key: CryptoKey, data: ArrayBufferView): any;
sign(algorithm: Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: string, extractable: boolean, keyUsages: string[]): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: Algorithm, unwrappedKeyAlgorithm: Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
verify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: Algorithm): any;
generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any;
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any;
verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any;
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any;
}
declare var SubtleCrypto: {
@@ -10998,11 +10975,8 @@ interface WebGLRenderingContext {
blendEquationSeparate(modeRGB: number, modeAlpha: number): void;
blendFunc(sfactor: number, dfactor: number): void;
blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;
bufferData(target: number, size: number, usage: number): void;
bufferData(target: number, size: ArrayBufferView, usage: number): void;
bufferData(target: number, size: any, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView): void;
bufferSubData(target: number, offset: number, data: any): void;
bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void;
bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void;
checkFramebufferStatus(target: number): number;
clear(mask: number): void;
clearColor(red: number, green: number, blue: number, alpha: number): void;
@@ -11845,8 +11819,7 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string): WebSocket;
new(url: string, protocols?: any): WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
@@ -12012,6 +11985,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
toolbar: BarProp;
top: Window;
window: Window;
URL: URL;
alert(message?: any): void;
blur(): void;
cancelAnimationFrame(handle: number): void;
@@ -12515,7 +12489,7 @@ interface NavigatorStorageUtils {
interface NodeSelector {
querySelector(selectors: string): Element;
querySelectorAll(selectors: string): NodeList;
querySelectorAll(selectors: string): NodeListOf<Element>;
}
interface RandomSource {
@@ -12563,7 +12537,7 @@ interface SVGLocatable {
}
interface SVGStylable {
className: SVGAnimatedString;
className: any;
style: CSSStyleDeclaration;
}
@@ -12650,8 +12624,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event, source?: string, fileno?: number, columnNumber?: number): void;
(event: string, source?: string, fileno?: number, columnNumber?: number): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
@@ -12827,6 +12800,7 @@ declare var styleMedia: StyleMedia;
declare var toolbar: BarProp;
declare var top: Window;
declare var window: Window;
declare var URL: URL;
declare function alert(message?: any): void;
declare function blur(): void;
declare function cancelAnimationFrame(handle: number): void;
@@ -12978,4 +12952,4 @@ declare function addEventListener(type: "unload", listener: (ev: Event) => any,
declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
+1 -11
View File
@@ -3573,17 +3573,6 @@ declare module Reflect {
function setPrototypeOf(target: any, proto: any): boolean;
}
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
/**
* Represents the completion of an asynchronous operation
*/
@@ -3603,6 +3592,7 @@ interface Promise<T> {
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
[Symbol.toStringTag]: string;
}
+2 -4
View File
@@ -571,8 +571,7 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string): WebSocket;
new(url: string, protocols?: any): WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
@@ -807,8 +806,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event, source?: string, fileno?: number, columnNumber?: number): void;
(event: string, source?: string, fileno?: number, columnNumber?: number): void;
(event: Event | string, source?: string, fileno?: number, columnNumber?: number): void;
}
interface PositionCallback {
(position: Position): void;
+2 -2
View File
@@ -318,7 +318,7 @@ namespace ts.formatting {
this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Add a space around certain TypeScript keywords
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
// Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
@@ -344,7 +344,7 @@ namespace ts.formatting {
// 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));
this.SpaceAfterDecorator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, 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));
this.NoSpaceBetweenFunctionKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.FunctionKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), RuleAction.Delete));
this.SpaceAfterStarInGeneratorDeclaration = new Rule(RuleDescriptor.create3(SyntaxKind.AsteriskToken, Shared.TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), RuleAction.Space));
+1 -1
View File
@@ -2,7 +2,7 @@
namespace ts.NavigateTo {
type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration };
export function getNavigateToItems(program: Program, cancellationToken: CancellationTokenObject, searchValue: string, maxResultCount: number): NavigateToItem[] {
export function getNavigateToItems(program: Program, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[] {
let patternMatcher = createPatternMatcher(searchValue);
let rawItems: RawNavigateToItem[] = [];
+2 -2
View File
@@ -228,7 +228,7 @@ namespace ts.NavigationBar {
function merge(target: ts.NavigationBarItem, source: ts.NavigationBarItem) {
// First, add any spans in the source to the target.
target.spans.push.apply(target.spans, source.spans);
addRange(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
@@ -465,7 +465,7 @@ namespace ts.NavigationBar {
// are not properties will be filtered out later by createChildItem.
let nodes: Node[] = removeDynamicallyNamedProperties(node);
if (constructor) {
nodes.push.apply(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name)));
addRange(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name)));
}
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
+388 -259
View File
@@ -345,7 +345,7 @@ namespace ts {
ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), jsDocCommentTextRange => {
let cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedParamJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment);
addRange(jsDocCommentParts, cleanedParamJsDocComment);
}
});
}
@@ -365,7 +365,7 @@ namespace ts {
declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => {
let cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment);
addRange(jsDocCommentParts, cleanedJsDocComment);
}
});
}
@@ -944,6 +944,10 @@ namespace ts {
}
}
export interface HostCancellationToken {
isCancellationRequested(): boolean;
}
//
// Public interface of the host of a language service instance.
//
@@ -955,7 +959,7 @@ namespace ts {
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): CancellationToken;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
getDefaultLibFileName(options: CompilerOptions): string;
log? (s: string): void;
@@ -1424,6 +1428,9 @@ namespace ts {
// class X {}
export const classElement = "class";
// var x = class X {}
export const localClassElement = "local class";
// interface Y {}
export const interfaceElement = "interface";
@@ -1494,6 +1501,7 @@ namespace ts {
export const exportedModifier = "export";
export const ambientModifier = "declare";
export const staticModifier = "static";
export const abstractModifier = "abstract";
}
export class ClassificationTypeNames {
@@ -1614,26 +1622,6 @@ namespace ts {
};
}
export class OperationCanceledException { }
export class CancellationTokenObject {
public static None: CancellationTokenObject = new CancellationTokenObject(null)
constructor(private cancellationToken: CancellationToken) {
}
public isCancellationRequested() {
return this.cancellationToken && this.cancellationToken.isCancellationRequested();
}
public throwIfCancellationRequested(): void {
if (this.isCancellationRequested()) {
throw new OperationCanceledException();
}
}
}
// Cache host information about scrip Should be refreshed
// at each language service public entry point, since we don't know when
// set of scripts handled by the host changes.
@@ -2400,6 +2388,21 @@ namespace ts {
return ScriptElementKind.unknown;
}
class CancellationTokenObject implements CancellationToken {
constructor(private cancellationToken: HostCancellationToken) {
}
public isCancellationRequested() {
return this.cancellationToken && this.cancellationToken.isCancellationRequested();
}
public throwIfCancellationRequested(): void {
if (this.isCancellationRequested()) {
throw new OperationCanceledException();
}
}
}
export function createLanguageService(host: LanguageServiceHost, documentRegistry: DocumentRegistry = createDocumentRegistry()): LanguageService {
let syntaxTreeCache: SyntaxTreeCache = new SyntaxTreeCache(host);
let ruleProvider: formatting.RulesProvider;
@@ -2604,7 +2607,7 @@ namespace ts {
function getSyntacticDiagnostics(fileName: string) {
synchronizeHostData();
return program.getSyntacticDiagnostics(getValidSourceFile(fileName));
return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken);
}
/**
@@ -2626,13 +2629,13 @@ namespace ts {
// Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
// Therefore only get diagnostics for given file.
let semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile);
let semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
if (!program.getCompilerOptions().declaration) {
return semanticDiagnostics;
}
// If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
let declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile);
let declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
return concatenate(semanticDiagnostics, declarationDiagnostics);
}
@@ -2784,6 +2787,7 @@ namespace ts {
case SyntaxKind.ExportKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.AbstractKeyword:
}
}
}
@@ -2794,21 +2798,19 @@ namespace ts {
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
return program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics());
return program.getOptionsDiagnostics(cancellationToken).concat(
program.getGlobalDiagnostics(cancellationToken));
}
/// Completion
function getCompletionEntryDisplayNameForSymbol(symbol: Symbol, target: ScriptTarget, performCharacterChecks: boolean): string {
let displayName = symbol.getName();
if (displayName) {
// If this is the default export, get the name of the declaration if it exists
if (displayName === "default") {
let localSymbol = getLocalSymbolForExportDefault(symbol);
if (localSymbol && localSymbol.name) {
displayName = symbol.valueDeclaration.localSymbol.name;
}
}
/**
* Get the name to be display in completion from a given symbol.
*
* @return undefined if the name is of external module otherwise a name with striped of any quote
*/
function getCompletionEntryDisplayNameForSymbol(symbol: Symbol, target: ScriptTarget, performCharacterChecks: boolean, location: Node): string {
let displayName: string = getDeclaredName(program.getTypeChecker(), symbol, location);
if (displayName) {
let firstCharCode = displayName.charCodeAt(0);
// First check of the displayName is not external module; if it is an external module, it is not valid entry
if ((symbol.flags & SymbolFlags.Namespace) && (firstCharCode === CharacterCodes.singleQuote || firstCharCode === CharacterCodes.doubleQuote)) {
@@ -2821,37 +2823,38 @@ namespace ts {
return getCompletionEntryDisplayName(displayName, target, performCharacterChecks);
}
function getCompletionEntryDisplayName(displayName: string, target: ScriptTarget, performCharacterChecks: boolean): string {
if (!displayName) {
/**
* Get a displayName from a given for completion list, performing any necessary quotes stripping
* and checking whether the name is valid identifier name.
*/
function getCompletionEntryDisplayName(name: string, target: ScriptTarget, performCharacterChecks: boolean): string {
if (!name) {
return undefined;
}
let firstCharCode = displayName.charCodeAt(0);
if (displayName.length >= 2 &&
firstCharCode === displayName.charCodeAt(displayName.length - 1) &&
(firstCharCode === CharacterCodes.singleQuote || firstCharCode === CharacterCodes.doubleQuote)) {
// If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an
// invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name.
displayName = displayName.substring(1, displayName.length - 1);
}
name = stripQuotes(name);
if (!displayName) {
if (!name) {
return undefined;
}
// If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an
// invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name.
// e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid.
// We, thus, need to check if whatever was inside the quotes is actually a valid identifier name.
if (performCharacterChecks) {
if (!isIdentifierStart(displayName.charCodeAt(0), target)) {
if (!isIdentifierStart(name.charCodeAt(0), target)) {
return undefined;
}
for (let i = 1, n = displayName.length; i < n; i++) {
if (!isIdentifierPart(displayName.charCodeAt(i), target)) {
for (let i = 1, n = name.length; i < n; i++) {
if (!isIdentifierPart(name.charCodeAt(i), target)) {
return undefined;
}
}
}
return unescapeIdentifier(displayName);
return name;
}
function getCompletionData(fileName: string, position: number) {
@@ -2890,33 +2893,36 @@ namespace ts {
log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start));
}
// Check if this is a valid completion location
if (contextToken && isCompletionListBlocker(contextToken)) {
log("Returning an empty list because completion was requested in an invalid position.");
return undefined;
}
let options = program.getCompilerOptions();
let jsx = options.jsx !== JsxEmit.None;
let target = options.target;
// Find the node where completion is requested on, in the case of a completion after
// a dot, it is the member access expression other wise, it is a request for all
// visible symbols in the scope, and the node is the current location.
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
// or attributes of a JSX tag.
let node = currentToken;
let isRightOfDot = false;
let isRightOfOpenTag = false;
let location = getTouchingPropertyName(sourceFile, position);
if(contextToken) {
let kind = contextToken.kind;
if (kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.PropertyAccessExpression) {
node = (<PropertyAccessExpression>contextToken.parent).expression;
isRightOfDot = true;
if (contextToken) {
// Bail out if this is a known invalid completion location
if (isCompletionListBlocker(contextToken)) {
log("Returning an empty list because completion was requested in an invalid position.");
return undefined;
}
else if (kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.QualifiedName) {
node = (<QualifiedName>contextToken.parent).left;
isRightOfDot = true;
let { parent, kind } = contextToken;
if (kind === SyntaxKind.DotToken) {
if (parent.kind === SyntaxKind.PropertyAccessExpression) {
node = (<PropertyAccessExpression>contextToken.parent).expression;
isRightOfDot = true;
}
else if (parent.kind === SyntaxKind.QualifiedName) {
node = (<QualifiedName>contextToken.parent).left;
isRightOfDot = true;
}
else {
// There is nothing that precedes the dot, so this likely just a stray character
// or leading into a '...' token. Just bail out instead.
return undefined;
}
}
else if (kind === SyntaxKind.LessThanToken && sourceFile.languageVariant === LanguageVariant.JSX) {
isRightOfOpenTag = true;
@@ -3008,81 +3014,33 @@ namespace ts {
}
function tryGetGlobalSymbols(): boolean {
let objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
if (objectLikeContainer) {
// Object literal expression, look up possible property names from contextual type
isMemberCompletion = true;
isNewIdentifierLocation = true;
let objectLikeContainer: ObjectLiteralExpression | BindingPattern;
let importClause: ImportClause;
let jsxContainer: JsxOpeningLikeElement;
let typeForObject: Type;
let existingMembers: Declaration[];
if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
typeForObject = typeChecker.getContextualType(<ObjectLiteralExpression>objectLikeContainer);
existingMembers = (<ObjectLiteralExpression>objectLikeContainer).properties;
}
else {
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
if (!typeForObject) {
return false;
}
let typeMembers = typeChecker.getPropertiesOfType(typeForObject);
if (typeMembers && typeMembers.length > 0) {
// Add filtered items to the completion list
symbols = filterObjectMembersList(typeMembers, existingMembers);
}
return true;
if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) {
return tryGetObjectLikeCompletionSymbols(objectLikeContainer);
}
else if (getAncestor(contextToken, SyntaxKind.ImportClause)) {
// cursor is in import clause
if (importClause = <ImportClause>getAncestor(contextToken, SyntaxKind.ImportClause)) {
// cursor is in an import clause
// try to show exported member for imported module
isMemberCompletion = true;
isNewIdentifierLocation = true;
if (showCompletionsInImportsClause(contextToken)) {
let importDeclaration = <ImportDeclaration>getAncestor(contextToken, SyntaxKind.ImportDeclaration);
Debug.assert(importDeclaration !== undefined);
let exports: Symbol[];
if (importDeclaration.moduleSpecifier) {
let moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
}
//let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration);
symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray;
}
return true;
return tryGetImportClauseCompletionSymbols(importClause);
}
else if (getAncestor(contextToken, SyntaxKind.JsxElement) || getAncestor(contextToken, SyntaxKind.JsxSelfClosingElement)) {
// Go up until we hit either the element or expression
let jsxNode = contextToken;
while (jsxNode) {
if (jsxNode.kind === SyntaxKind.JsxExpression) {
// Defer to global completion if we're inside an {expression}
break;
} else if (jsxNode.kind === SyntaxKind.JsxSelfClosingElement || jsxNode.kind === SyntaxKind.JsxElement) {
let attrsType: Type;
if (jsxNode.kind === SyntaxKind.JsxSelfClosingElement) {
// Cursor is inside a JSX self-closing element
attrsType = typeChecker.getJsxElementAttributesType(<JsxSelfClosingElement>jsxNode);
}
else {
Debug.assert(jsxNode.kind === SyntaxKind.JsxElement);
// Cursor is inside a JSX element
attrsType = typeChecker.getJsxElementAttributesType((<JsxElement>jsxNode).openingElement);
}
symbols = typeChecker.getPropertiesOfType(attrsType);
if (jsxContainer = tryGetContainingJsxElement(contextToken)) {
let attrsType: Type;
if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) {
// Cursor is inside a JSX self-closing element or opening element
attrsType = typeChecker.getJsxElementAttributesType(<JsxOpeningLikeElement>jsxContainer);
if (attrsType) {
symbols = filterJsxAttributes((<JsxOpeningLikeElement>jsxContainer).attributes, typeChecker.getPropertiesOfType(attrsType));
isMemberCompletion = true;
isNewIdentifierLocation = false;
return true;
}
jsxNode = jsxNode.parent;
}
}
@@ -3143,16 +3101,16 @@ namespace ts {
return scope;
}
function isCompletionListBlocker(previousToken: Node): boolean {
function isCompletionListBlocker(contextToken: Node): boolean {
let start = new Date().getTime();
let result = isInStringOrRegularExpressionOrTemplateLiteral(previousToken) ||
isIdentifierDefinitionLocation(previousToken) ||
isRightOfIllegalDot(previousToken);
let result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
isIdentifierDefinitionLocation(contextToken) ||
isDotOfNumericLiteral(contextToken);
log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start));
return result;
}
function showCompletionsInImportsClause(node: Node): boolean {
function shouldShowCompletionsInImportsClause(node: Node): boolean {
if (node) {
// import {|
// import {a,|
@@ -3170,7 +3128,7 @@ namespace ts {
switch (previousToken.kind) {
case SyntaxKind.CommaToken:
return containingNodeKind === SyntaxKind.CallExpression // func( a, |
|| containingNodeKind === SyntaxKind.Constructor // constructor( a, | public, protected, private keywords are allowed here, so show completion
|| containingNodeKind === SyntaxKind.Constructor // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
|| containingNodeKind === SyntaxKind.NewExpression // new C(a, |
|| containingNodeKind === SyntaxKind.ArrayLiteralExpression // [a, |
|| containingNodeKind === SyntaxKind.BinaryExpression // let x = (a, |
@@ -3181,10 +3139,12 @@ namespace ts {
|| containingNodeKind === SyntaxKind.Constructor // constructor( |
|| containingNodeKind === SyntaxKind.NewExpression // new C(a|
|| containingNodeKind === SyntaxKind.ParenthesizedExpression // let x = (a|
|| containingNodeKind === SyntaxKind.ParenthesizedType; // function F(pred: (a| this can become an arrow function, where 'a' is the argument
|| containingNodeKind === SyntaxKind.ParenthesizedType; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
case SyntaxKind.OpenBracketToken:
return containingNodeKind === SyntaxKind.ArrayLiteralExpression; // [ |
return containingNodeKind === SyntaxKind.ArrayLiteralExpression // [ |
|| containingNodeKind === SyntaxKind.IndexSignature // [ | : string ]
|| containingNodeKind === SyntaxKind.ComputedPropertyName // [ | /* this can become an index signature */
case SyntaxKind.ModuleKeyword: // module |
case SyntaxKind.NamespaceKeyword: // namespace |
@@ -3224,12 +3184,12 @@ namespace ts {
return false;
}
function isInStringOrRegularExpressionOrTemplateLiteral(previousToken: Node): boolean {
if (previousToken.kind === SyntaxKind.StringLiteral
|| previousToken.kind === SyntaxKind.RegularExpressionLiteral
|| isTemplateLiteralKind(previousToken.kind)) {
let start = previousToken.getStart();
let end = previousToken.getEnd();
function isInStringOrRegularExpressionOrTemplateLiteral(contextToken: Node): boolean {
if (contextToken.kind === SyntaxKind.StringLiteral
|| contextToken.kind === SyntaxKind.RegularExpressionLiteral
|| isTemplateLiteralKind(contextToken.kind)) {
let start = contextToken.getStart();
let end = contextToken.getEnd();
// To be "in" one of these literals, the position has to be:
// 1. entirely within the token text.
@@ -3240,14 +3200,94 @@ namespace ts {
}
if (position === end) {
return !!(<LiteralExpression>previousToken).isUnterminated ||
previousToken.kind === SyntaxKind.RegularExpressionLiteral;
return !!(<LiteralExpression>contextToken).isUnterminated
|| contextToken.kind === SyntaxKind.RegularExpressionLiteral;
}
}
return false;
}
/**
* Aggregates relevant symbols for completion in object literals and object binding patterns.
* Relevant symbols are stored in the captured 'symbols' variable.
*
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetObjectLikeCompletionSymbols(objectLikeContainer: ObjectLiteralExpression | BindingPattern): boolean {
// We're looking up possible property names from contextual/inferred/declared type.
isMemberCompletion = true;
let typeForObject: Type;
let existingMembers: Declaration[];
if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
// We are completing on contextual types, but may also include properties
// other than those within the declared type.
isNewIdentifierLocation = true;
typeForObject = typeChecker.getContextualType(<ObjectLiteralExpression>objectLikeContainer);
existingMembers = (<ObjectLiteralExpression>objectLikeContainer).properties;
}
else if (objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern) {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
else {
Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind);
}
if (!typeForObject) {
return false;
}
let typeMembers = typeChecker.getPropertiesOfType(typeForObject);
if (typeMembers && typeMembers.length > 0) {
// Add filtered items to the completion list
symbols = filterObjectMembersList(typeMembers, existingMembers);
}
return true;
}
/**
* Aggregates relevant symbols for completion in import clauses; for instance,
*
* import { $ } from "moduleName";
*
* Relevant symbols are stored in the captured 'symbols' variable.
*
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetImportClauseCompletionSymbols(importClause: ImportClause): boolean {
// cursor is in import clause
// try to show exported member for imported module
if (shouldShowCompletionsInImportsClause(contextToken)) {
isMemberCompletion = true;
isNewIdentifierLocation = false;
let importDeclaration = <ImportDeclaration>importClause.parent;
Debug.assert(importDeclaration !== undefined && importDeclaration.kind === SyntaxKind.ImportDeclaration);
let exports: Symbol[];
let moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
//let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration);
symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray;
}
else {
isMemberCompletion = false;
isNewIdentifierLocation = true;
}
return true;
}
/**
* Returns the immediate owning object literal or binding pattern of a context token,
* on the condition that one exists and that the context implies completion should be given.
@@ -3268,6 +3308,36 @@ namespace ts {
return undefined;
}
function tryGetContainingJsxElement(contextToken: Node): JsxOpeningLikeElement {
if (contextToken) {
let parent = contextToken.parent;
switch(contextToken.kind) {
case SyntaxKind.LessThanSlashToken:
case SyntaxKind.SlashToken:
case SyntaxKind.Identifier:
if(parent && (parent.kind === SyntaxKind.JsxSelfClosingElement || parent.kind === SyntaxKind.JsxOpeningElement)) {
return <JsxOpeningLikeElement>parent;
}
break;
case SyntaxKind.CloseBraceToken:
// The context token is the closing } of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
if(parent &&
parent.kind === SyntaxKind.JsxExpression &&
parent.parent &&
parent.parent.kind === SyntaxKind.JsxAttribute) {
return <JsxOpeningLikeElement>parent.parent.parent;
}
break;
}
}
return undefined;
}
function isFunction(kind: SyntaxKind): boolean {
switch (kind) {
case SyntaxKind.FunctionExpression:
@@ -3285,101 +3355,98 @@ namespace ts {
return false;
}
function isIdentifierDefinitionLocation(previousToken: Node): boolean {
if (previousToken) {
let containingNodeKind = previousToken.parent.kind;
switch (previousToken.kind) {
case SyntaxKind.CommaToken:
return containingNodeKind === SyntaxKind.VariableDeclaration ||
containingNodeKind === SyntaxKind.VariableDeclarationList ||
containingNodeKind === SyntaxKind.VariableStatement ||
containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { foo, |
isFunction(containingNodeKind) ||
containingNodeKind === SyntaxKind.ClassDeclaration || // class A<T, |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A<T, |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A<T, |
containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x, y|
function isIdentifierDefinitionLocation(contextToken: Node): boolean {
let containingNodeKind = contextToken.parent.kind;
switch (contextToken.kind) {
case SyntaxKind.CommaToken:
return containingNodeKind === SyntaxKind.VariableDeclaration ||
containingNodeKind === SyntaxKind.VariableDeclarationList ||
containingNodeKind === SyntaxKind.VariableStatement ||
containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { foo, |
isFunction(containingNodeKind) ||
containingNodeKind === SyntaxKind.ClassDeclaration || // class A<T, |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A<T, |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A<T, |
containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x, y|
case SyntaxKind.DotToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [.|
case SyntaxKind.DotToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [.|
case SyntaxKind.ColonToken:
return containingNodeKind === SyntaxKind.BindingElement; // var {x :html|
case SyntaxKind.ColonToken:
return containingNodeKind === SyntaxKind.BindingElement; // var {x :html|
case SyntaxKind.OpenBracketToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x|
case SyntaxKind.OpenBracketToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x|
case SyntaxKind.OpenParenToken:
return containingNodeKind === SyntaxKind.CatchClause ||
isFunction(containingNodeKind);
case SyntaxKind.OpenParenToken:
return containingNodeKind === SyntaxKind.CatchClause ||
isFunction(containingNodeKind);
case SyntaxKind.OpenBraceToken:
return containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface a { |
containingNodeKind === SyntaxKind.TypeLiteral; // let x : { |
case SyntaxKind.OpenBraceToken:
return containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface a { |
containingNodeKind === SyntaxKind.TypeLiteral; // let x : { |
case SyntaxKind.SemicolonToken:
return containingNodeKind === SyntaxKind.PropertySignature &&
previousToken.parent && previousToken.parent.parent &&
(previousToken.parent.parent.kind === SyntaxKind.InterfaceDeclaration || // interface a { f; |
previousToken.parent.parent.kind === SyntaxKind.TypeLiteral); // let x : { a; |
case SyntaxKind.SemicolonToken:
return containingNodeKind === SyntaxKind.PropertySignature &&
contextToken.parent && contextToken.parent.parent &&
(contextToken.parent.parent.kind === SyntaxKind.InterfaceDeclaration || // interface a { f; |
contextToken.parent.parent.kind === SyntaxKind.TypeLiteral); // let x : { a; |
case SyntaxKind.LessThanToken:
return containingNodeKind === SyntaxKind.ClassDeclaration || // class A< |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A< |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A< |
isFunction(containingNodeKind);
case SyntaxKind.LessThanToken:
return containingNodeKind === SyntaxKind.ClassDeclaration || // class A< |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A< |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A< |
isFunction(containingNodeKind);
case SyntaxKind.StaticKeyword:
return containingNodeKind === SyntaxKind.PropertyDeclaration;
case SyntaxKind.StaticKeyword:
return containingNodeKind === SyntaxKind.PropertyDeclaration;
case SyntaxKind.DotDotDotToken:
return containingNodeKind === SyntaxKind.Parameter ||
containingNodeKind === SyntaxKind.Constructor ||
(previousToken.parent && previousToken.parent.parent &&
previousToken.parent.parent.kind === SyntaxKind.ArrayBindingPattern); // var [...z|
case SyntaxKind.DotDotDotToken:
return containingNodeKind === SyntaxKind.Parameter ||
(contextToken.parent && contextToken.parent.parent &&
contextToken.parent.parent.kind === SyntaxKind.ArrayBindingPattern); // var [...z|
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return containingNodeKind === SyntaxKind.Parameter;
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return containingNodeKind === SyntaxKind.Parameter;
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.VarKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.ImportKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.YieldKeyword:
case SyntaxKind.TypeKeyword: // type htm|
return true;
}
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.VarKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.ImportKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.YieldKeyword:
case SyntaxKind.TypeKeyword: // type htm|
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
switch (previousToken.getText()) {
case "class":
case "interface":
case "enum":
case "function":
case "var":
case "static":
case "let":
case "const":
case "yield":
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
switch (contextToken.getText()) {
case "class":
case "interface":
case "enum":
case "function":
case "var":
case "static":
case "let":
case "const":
case "yield":
return true;
}
return false;
}
function isRightOfIllegalDot(previousToken: Node): boolean {
if (previousToken && previousToken.kind === SyntaxKind.NumericLiteral) {
let text = previousToken.getFullText();
function isDotOfNumericLiteral(contextToken: Node): boolean {
if (contextToken.kind === SyntaxKind.NumericLiteral) {
let text = contextToken.getFullText();
return text.charAt(text.length - 1) === ".";
}
@@ -3397,6 +3464,11 @@ namespace ts {
importDeclaration.importClause.namedBindings.kind === SyntaxKind.NamedImports) {
forEach((<NamedImports>importDeclaration.importClause.namedBindings).elements, el => {
// If this is the current item we are editing right now, do not filter it out
if (el.getStart() <= position && position <= el.getEnd()) {
return;
}
let name = el.propertyName || el.name;
exisingImports[name.text] = true;
});
@@ -3451,8 +3523,30 @@ namespace ts {
return filteredMembers;
}
function filterJsxAttributes(attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>, symbols: Symbol[]): Symbol[] {
let seenNames: Map<boolean> = {};
for (let attr of attributes) {
// If this is the current item we are editing right now, do not filter it out
if (attr.getStart() <= position && position <= attr.getEnd()) {
continue;
}
if (attr.kind === SyntaxKind.JsxAttribute) {
seenNames[(<JsxAttribute>attr).name.text] = true;
}
}
let result: Symbol[] = [];
for (let sym of symbols) {
if (!seenNames[sym.name]) {
result.push(sym);
}
}
return result;
}
}
function getCompletionsAtPosition(fileName: string, position: number): CompletionInfo {
synchronizeHostData();
@@ -3514,7 +3608,7 @@ namespace ts {
// Try to get a valid display name for this symbol, if we could not find one, then ignore it.
// We would like to only show things that can be added after a dot, so for instance numeric properties can
// not be accessed with a dot (a.1 <- invalid)
let displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true);
let displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location);
if (!displayName) {
return undefined;
}
@@ -3571,7 +3665,7 @@ namespace ts {
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
let symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false) === entryName ? s : undefined);
let symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location) === entryName ? s : undefined);
if (symbol) {
let { displayParts, documentation, symbolKind } = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, location, SemanticMeaning.All);
@@ -3604,7 +3698,8 @@ namespace ts {
function getSymbolKind(symbol: Symbol, location: Node): string {
let flags = symbol.getFlags();
if (flags & SymbolFlags.Class) return ScriptElementKind.classElement;
if (flags & SymbolFlags.Class) return getDeclarationOfKind(symbol, SyntaxKind.ClassExpression) ?
ScriptElementKind.localClassElement : ScriptElementKind.classElement;
if (flags & SymbolFlags.Enum) return ScriptElementKind.enumElement;
if (flags & SymbolFlags.TypeAlias) return ScriptElementKind.typeElement;
if (flags & SymbolFlags.Interface) return ScriptElementKind.interfaceElement;
@@ -3649,7 +3744,7 @@ namespace ts {
if (flags & SymbolFlags.Constructor) return ScriptElementKind.constructorImplementationElement;
if (flags & SymbolFlags.Property) {
if (flags & SymbolFlags.UnionProperty) {
if (flags & SymbolFlags.SyntheticProperty) {
// If union property is result of union of non method (property/accessors/variables), it is labeled as property
let unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), rootSymbol => {
let rootSymbolFlags = rootSymbol.getFlags();
@@ -3772,7 +3867,7 @@ namespace ts {
displayParts.push(spacePart());
}
if (!(type.flags & TypeFlags.Anonymous)) {
displayParts.push.apply(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
}
addSignatureDisplayParts(signature, allSignatures, TypeFormatFlags.WriteArrowStyleSignature);
break;
@@ -3813,7 +3908,16 @@ namespace ts {
}
}
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo) {
displayParts.push(keywordPart(SyntaxKind.ClassKeyword));
if (getDeclarationOfKind(symbol, SyntaxKind.ClassExpression)) {
// Special case for class expressions because we would like to indicate that
// the class name is local to the class body (similar to function expression)
// (local class) class <className>
pushTypePart(ScriptElementKind.localClassElement);
}
else {
// Class declaration has name which is not local.
displayParts.push(keywordPart(SyntaxKind.ClassKeyword));
}
displayParts.push(spacePart());
addFullSymbolName(symbol);
writeTypeParametersOfSymbol(symbol, sourceFile);
@@ -3833,7 +3937,7 @@ namespace ts {
displayParts.push(spacePart());
displayParts.push(operatorPart(SyntaxKind.EqualsToken));
displayParts.push(spacePart());
displayParts.push.apply(displayParts, typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration));
addRange(displayParts, typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration));
}
if (symbolFlags & SymbolFlags.Enum) {
addNewLineIfDisplayPartsExist();
@@ -3879,7 +3983,7 @@ namespace ts {
else if (signatureDeclaration.kind !== SyntaxKind.CallSignature && signatureDeclaration.name) {
addFullSymbolName(signatureDeclaration.symbol);
}
displayParts.push.apply(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
}
}
if (symbolFlags & SymbolFlags.EnumMember) {
@@ -3940,10 +4044,10 @@ namespace ts {
let typeParameterParts = mapToDisplayParts(writer => {
typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(<TypeParameter>type, writer, enclosingDeclaration);
});
displayParts.push.apply(displayParts, typeParameterParts);
addRange(displayParts, typeParameterParts);
}
else {
displayParts.push.apply(displayParts, typeToDisplayParts(typeChecker, type, enclosingDeclaration));
addRange(displayParts, typeToDisplayParts(typeChecker, type, enclosingDeclaration));
}
}
else if (symbolFlags & SymbolFlags.Function ||
@@ -3977,7 +4081,7 @@ namespace ts {
function addFullSymbolName(symbol: Symbol, enclosingDeclaration?: Node) {
let fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined,
SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing);
displayParts.push.apply(displayParts, fullSymbolDisplayParts);
addRange(displayParts, fullSymbolDisplayParts);
}
function addPrefixForAnyFunctionOrVar(symbol: Symbol, symbolKind: string) {
@@ -4007,7 +4111,7 @@ namespace ts {
}
function addSignatureDisplayParts(signature: Signature, allSignatures: Signature[], flags?: TypeFormatFlags) {
displayParts.push.apply(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | TypeFormatFlags.WriteTypeArgumentsOfSignature));
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | TypeFormatFlags.WriteTypeArgumentsOfSignature));
if (allSignatures.length > 1) {
displayParts.push(spacePart());
displayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
@@ -4024,7 +4128,7 @@ namespace ts {
let typeParameterParts = mapToDisplayParts(writer => {
typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration);
});
displayParts.push.apply(displayParts, typeParameterParts);
addRange(displayParts, typeParameterParts);
}
}
@@ -5019,7 +5123,7 @@ namespace ts {
// Get the text to search for.
// Note: if this is an external module symbol, the name doesn't include quotes.
let declaredName = getDeclaredName(typeChecker, symbol, node);
let declaredName = stripQuotes(getDeclaredName(typeChecker, symbol, node));
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
@@ -5096,10 +5200,10 @@ namespace ts {
* a reference to a symbol can occur anywhere.
*/
function getSymbolScope(symbol: Symbol): Node {
// If this is the symbol of a function expression, then named references
// are limited to its own scope.
// If this is the symbol of a named function expression or named class expression,
// then named references are limited to its own scope.
let valueDeclaration = symbol.valueDeclaration;
if (valueDeclaration && valueDeclaration.kind === SyntaxKind.FunctionExpression) {
if (valueDeclaration && (valueDeclaration.kind === SyntaxKind.FunctionExpression || valueDeclaration.kind === SyntaxKind.ClassExpression)) {
return valueDeclaration;
}
@@ -5119,7 +5223,7 @@ namespace ts {
// if this symbol is visible from its parent container, e.g. exported, then bail out
// if symbol correspond to the union property - bail out
if (symbol.parent || (symbol.flags & SymbolFlags.UnionProperty)) {
if (symbol.parent || (symbol.flags & SymbolFlags.SyntheticProperty)) {
return undefined;
}
@@ -5538,7 +5642,7 @@ namespace ts {
// type to the search set
if (isNameOfPropertyAssignment(location)) {
forEach(getPropertySymbolsFromContextualType(location), contextualSymbol => {
result.push.apply(result, typeChecker.getRootSymbols(contextualSymbol));
addRange(result, typeChecker.getRootSymbols(contextualSymbol));
});
/* Because in short-hand property assignment, location has two meaning : property name and as value of the property
@@ -5776,7 +5880,7 @@ namespace ts {
});
}
let emitOutput = program.emit(sourceFile, writeFile);
let emitOutput = program.emit(sourceFile, writeFile, cancellationToken);
return {
outputFiles,
@@ -6024,6 +6128,26 @@ namespace ts {
return convertClassifications(getEncodedSemanticClassifications(fileName, span));
}
function checkForClassificationCancellation(kind: SyntaxKind) {
// We don't want to actually call back into our host on every node to find out if we've
// been canceled. That would be an enormous amount of chattyness, along with the all
// the overhead of marshalling the data to/from the host. So instead we pick a few
// reasonable node kinds to bother checking on. These node kinds represent high level
// constructs that we would expect to see commonly, but just at a far less frequent
// interval.
//
// For example, in checker.ts (around 750k) we only have around 600 of these constructs.
// That means we're calling back into the host around every 1.2k of the file we process.
// Lib.d.ts has similar numbers.
switch (kind) {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.FunctionDeclaration:
cancellationToken.throwIfCancellationRequested();
}
}
function getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications {
synchronizeHostData();
@@ -6091,7 +6215,10 @@ namespace ts {
function processNode(node: Node) {
// Only walk into nodes that intersect the requested span.
if (node && textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) {
if (node.kind === SyntaxKind.Identifier && !nodeIsMissing(node)) {
let kind = node.kind;
checkForClassificationCancellation(kind);
if (kind === SyntaxKind.Identifier && !nodeIsMissing(node)) {
let identifier = <Identifier>node;
// Only bother calling into the typechecker if this is an identifier that
@@ -6458,6 +6585,8 @@ namespace ts {
// Ignore nodes that don't intersect the original span to classify.
if (decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
checkForClassificationCancellation(element.kind);
let children = element.getChildren(sourceFile);
for (let i = 0, n = children.length; i < n; i++) {
let child = children[i];
@@ -6745,7 +6874,7 @@ namespace ts {
}
}
let displayName = getDeclaredName(typeChecker, symbol, node);
let displayName = stripQuotes(getDeclaredName(typeChecker, symbol, node));
let kind = getSymbolKind(symbol, node);
if (kind) {
return {
@@ -7347,8 +7476,8 @@ namespace ts {
}
let proto = kind === SyntaxKind.SourceFile ? new SourceFileObject() : new NodeObject();
proto.kind = kind;
proto.pos = 0;
proto.end = 0;
proto.pos = -1;
proto.end = -1;
proto.flags = 0;
proto.parent = undefined;
Node.prototype = proto;
+27 -3
View File
@@ -51,7 +51,7 @@ namespace ts {
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): ScriptSnapshotShim;
getLocalizedDiagnosticMessages(): string;
getCancellationToken(): CancellationToken;
getCancellationToken(): HostCancellationToken;
getCurrentDirectory(): string;
getDefaultLibFileName(options: string): string;
getNewLine?(): string;
@@ -326,8 +326,9 @@ namespace ts {
}
}
public getCancellationToken(): CancellationToken {
return this.shimHost.getCancellationToken();
public getCancellationToken(): HostCancellationToken {
var hostCancellationToken = this.shimHost.getCancellationToken();
return new ThrottledCancellationToken(hostCancellationToken);
}
public getCurrentDirectory(): string {
@@ -346,6 +347,29 @@ namespace ts {
}
}
/** A cancellation that throttles calls to the host */
class ThrottledCancellationToken implements HostCancellationToken {
// Store when we last tried to cancel. Checking cancellation can be expensive (as we have
// to marshall over to the host layer). So we only bother actually checking once enough
// time has passed.
private lastCancellationCheckTime = 0;
constructor(private hostCancellationToken: HostCancellationToken) {
}
public isCancellationRequested(): boolean {
var time = Date.now();
var duration = Math.abs(time - this.lastCancellationCheckTime);
if (duration > 10) {
// Check no more than once every 10 ms.
this.lastCancellationCheckTime = time;
return this.hostCancellationToken.isCancellationRequested();
}
return false;
}
}
export class CoreServicesShimHostAdapter implements ParseConfigHost {
constructor(private shimHost: CoreServicesShimHost) {
+5 -5
View File
@@ -178,7 +178,7 @@ namespace ts.SignatureHelp {
argumentCount: number;
}
export function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, cancellationToken: CancellationTokenObject): SignatureHelpItems {
export function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, cancellationToken: CancellationToken): SignatureHelpItems {
let typeChecker = program.getTypeChecker();
// Decide whether to show signature help
@@ -550,7 +550,7 @@ namespace ts.SignatureHelp {
let suffixDisplayParts: SymbolDisplayPart[] = [];
if (callTargetDisplayParts) {
prefixDisplayParts.push.apply(prefixDisplayParts, callTargetDisplayParts);
addRange(prefixDisplayParts, callTargetDisplayParts);
}
if (isTypeParameterList) {
@@ -560,12 +560,12 @@ namespace ts.SignatureHelp {
suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
let parameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation));
suffixDisplayParts.push.apply(suffixDisplayParts, parameterParts);
addRange(suffixDisplayParts, parameterParts);
}
else {
let typeParameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation));
prefixDisplayParts.push.apply(prefixDisplayParts, typeParameterParts);
addRange(prefixDisplayParts, typeParameterParts);
prefixDisplayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
let parameters = candidateSignature.parameters;
@@ -575,7 +575,7 @@ namespace ts.SignatureHelp {
let returnTypeParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation));
suffixDisplayParts.push.apply(suffixDisplayParts, returnTypeParts);
addRange(suffixDisplayParts, returnTypeParts);
return {
isVariadic: candidateSignature.hasRestParameter,
+10 -2
View File
@@ -429,6 +429,7 @@ namespace ts {
if (flags & NodeFlags.Protected) result.push(ScriptElementKindModifier.protectedMemberModifier);
if (flags & NodeFlags.Public) result.push(ScriptElementKindModifier.publicMemberModifier);
if (flags & NodeFlags.Static) result.push(ScriptElementKindModifier.staticModifier);
if (flags & NodeFlags.Abstract) result.push(ScriptElementKindModifier.abstractModifier);
if (flags & NodeFlags.Export) result.push(ScriptElementKindModifier.exportedModifier);
if (isInAmbientContext(node)) result.push(ScriptElementKindModifier.ambientModifier);
@@ -666,7 +667,7 @@ namespace ts {
let name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
return stripQuotes(name);
return name;
}
export function isImportOrExportSpecifierName(location: Node): boolean {
@@ -675,9 +676,16 @@ namespace ts {
(<ImportOrExportSpecifier>location.parent).propertyName === location;
}
/**
* Strip off existed single quotes or double quotes from a given string
*
* @return non-quoted string
*/
export function stripQuotes(name: string) {
let length = name.length;
if (length >= 2 && name.charCodeAt(0) === CharacterCodes.doubleQuote && name.charCodeAt(length - 1) === CharacterCodes.doubleQuote) {
if (length >= 2 &&
name.charCodeAt(0) === name.charCodeAt(length - 1) &&
(name.charCodeAt(0) === CharacterCodes.doubleQuote || name.charCodeAt(0) === CharacterCodes.singleQuote)) {
return name.substring(1, length - 1);
};
return name;
+10 -10
View File
@@ -75,26 +75,26 @@ function delint(sourceFile) {
delintNode(sourceFile);
function delintNode(node) {
switch (node.kind) {
case 191 /* ForStatement */:
case 192 /* ForInStatement */:
case 190 /* WhileStatement */:
case 189 /* DoStatement */:
if (node.statement.kind !== 184 /* Block */) {
case 196 /* ForStatement */:
case 197 /* ForInStatement */:
case 195 /* WhileStatement */:
case 194 /* DoStatement */:
if (node.statement.kind !== 189 /* Block */) {
report(node, "A looping statement's contents should be wrapped in a block body.");
}
break;
case 188 /* IfStatement */:
case 193 /* IfStatement */:
var ifStatement = node;
if (ifStatement.thenStatement.kind !== 184 /* Block */) {
if (ifStatement.thenStatement.kind !== 189 /* Block */) {
report(ifStatement.thenStatement, "An if statement's contents should be wrapped in a block body.");
}
if (ifStatement.elseStatement &&
ifStatement.elseStatement.kind !== 184 /* Block */ &&
ifStatement.elseStatement.kind !== 188 /* IfStatement */) {
ifStatement.elseStatement.kind !== 189 /* Block */ &&
ifStatement.elseStatement.kind !== 193 /* IfStatement */) {
report(ifStatement.elseStatement, "An else statement's contents should be wrapped in a block body.");
}
break;
case 173 /* BinaryExpression */:
case 178 /* BinaryExpression */:
var op = node.operatorToken.kind;
if (op === 29 /* EqualsEqualsToken */ || op == 30 /* ExclamationEqualsToken */) {
report(node, "Use '===' and '!=='.");
@@ -1,8 +1,20 @@
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,16): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,26): error TS1005: ',' expected.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,29): error TS1138: Parameter declaration expected.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,29): error TS2304: Cannot find name 'yield'.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,34): error TS1005: ';' expected.
==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts (1 errors) ====
==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts (5 errors) ====
function * foo(a = yield => yield) {
~
!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
~~~~~~~~~
!!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
~~
!!! error TS1005: ',' expected.
~~~~~
!!! error TS1138: Parameter declaration expected.
~~~~~
!!! error TS2304: Cannot find name 'yield'.
~
!!! error TS1005: ';' expected.
}
@@ -3,6 +3,6 @@ function * foo(a = yield => yield) {
}
//// [FunctionDeclaration10_es6.js]
function foo(a) {
if (a === void 0) { a = function (yield) { return yield; }; }
yield;
{
}
@@ -1,5 +1,5 @@
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,18): error TS2304: Cannot find name 'yield'.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,18): error TS2523: 'yield' expressions cannot be used in a parameter initializer.
==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts (2 errors) ====
@@ -7,5 +7,5 @@ tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,1
~
!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
~~~~~
!!! error TS2304: Cannot find name 'yield'.
!!! error TS2523: 'yield' expressions cannot be used in a parameter initializer.
}
@@ -1,6 +1,6 @@
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,11): error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,20): error TS2304: Cannot find name 'yield'.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,20): error TS2523: 'yield' expressions cannot be used in a parameter initializer.
==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts (3 errors) ====
@@ -12,6 +12,6 @@ tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,2
~
!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher.
~~~~~
!!! error TS2304: Cannot find name 'yield'.
!!! error TS2523: 'yield' expressions cannot be used in a parameter initializer.
}
}
@@ -0,0 +1,14 @@
//// [abstractIdentifierNameStrict.ts]
var abstract = true;
function foo() {
"use strict";
var abstract = true;
}
//// [abstractIdentifierNameStrict.js]
var abstract = true;
function foo() {
"use strict";
var abstract = true;
}
@@ -0,0 +1,11 @@
=== tests/cases/compiler/abstractIdentifierNameStrict.ts ===
var abstract = true;
>abstract : Symbol(abstract, Decl(abstractIdentifierNameStrict.ts, 0, 3))
function foo() {
>foo : Symbol(foo, Decl(abstractIdentifierNameStrict.ts, 0, 20))
"use strict";
var abstract = true;
>abstract : Symbol(abstract, Decl(abstractIdentifierNameStrict.ts, 4, 7))
}
@@ -0,0 +1,15 @@
=== tests/cases/compiler/abstractIdentifierNameStrict.ts ===
var abstract = true;
>abstract : boolean
>true : boolean
function foo() {
>foo : () => void
"use strict";
>"use strict" : string
var abstract = true;
>abstract : boolean
>true : boolean
}
@@ -0,0 +1,8 @@
//// [abstractInterfaceIdentifierName.ts]
interface abstract {
abstract(): void;
}
//// [abstractInterfaceIdentifierName.js]
@@ -0,0 +1,9 @@
=== tests/cases/compiler/abstractInterfaceIdentifierName.ts ===
interface abstract {
>abstract : Symbol(abstract, Decl(abstractInterfaceIdentifierName.ts, 0, 0))
abstract(): void;
>abstract : Symbol(abstract, Decl(abstractInterfaceIdentifierName.ts, 1, 20))
}
@@ -0,0 +1,9 @@
=== tests/cases/compiler/abstractInterfaceIdentifierName.ts ===
interface abstract {
>abstract : abstract
abstract(): void;
>abstract : () => void
}
@@ -9,9 +9,9 @@ function doubleAndReturnAsArray(x: number, y: number, z: number): [number, numbe
let blah = arguments[Symbol.iterator];
>blah : Symbol(blah, Decl(argumentsObjectIterator02_ES6.ts, 2, 7))
>arguments : Symbol(arguments)
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31))
>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1186, 52), Decl(lib.d.ts, 1292, 11))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31))
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1249, 31))
>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1199, 52), Decl(lib.d.ts, 1305, 11))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1249, 31))
let result = [];
>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7))
@@ -72,14 +72,14 @@ var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
interface myArray extends Array<Number> { }
>myArray : Symbol(myArray, Decl(arrayLiterals2ES6.ts, 40, 67))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1452, 1))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1452, 1))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1))
>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1556, 1))
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES6.ts, 44, 3))
@@ -0,0 +1,24 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(2,11): error TS2304: Cannot find name 'async'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(2,17): error TS1005: ',' expected.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(2,20): error TS1005: '=' expected.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(2,24): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(4,11): error TS2304: Cannot find name 'await'.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts (5 errors) ====
var foo = async foo(): Promise<void> => {
~~~~~
!!! error TS2304: Cannot find name 'async'.
~~~
!!! error TS1005: ',' expected.
~
!!! error TS1005: '=' expected.
~~~~~~~~~~~~~
!!! error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement.
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
}
@@ -0,0 +1,13 @@
//// [asyncArrowFunction10_es6.ts]
var foo = async foo(): Promise<void> => {
// Legal to use 'await' in a type context.
var v: await;
}
//// [asyncArrowFunction10_es6.js]
var foo = async, foo = () => {
// Legal to use 'await' in a type context.
var v;
};
@@ -0,0 +1,8 @@
//// [asyncArrowFunction1_es6.ts]
var foo = async (): Promise<void> => {
};
//// [asyncArrowFunction1_es6.js]
var foo = () => __awaiter(this, void 0, Promise, function* () {
});
@@ -0,0 +1,7 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction1_es6.ts ===
var foo = async (): Promise<void> => {
>foo : Symbol(foo, Decl(asyncArrowFunction1_es6.ts, 1, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
};
@@ -0,0 +1,8 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction1_es6.ts ===
var foo = async (): Promise<void> => {
>foo : () => Promise<void>
>async (): Promise<void> => {} : () => Promise<void>
>Promise : Promise<T>
};
@@ -0,0 +1,7 @@
//// [asyncArrowFunction2_es6.ts]
var f = (await) => {
}
//// [asyncArrowFunction2_es6.js]
var f = (await) => {
};
@@ -0,0 +1,5 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction2_es6.ts ===
var f = (await) => {
>f : Symbol(f, Decl(asyncArrowFunction2_es6.ts, 0, 3))
>await : Symbol(await, Decl(asyncArrowFunction2_es6.ts, 0, 9))
}
@@ -0,0 +1,6 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction2_es6.ts ===
var f = (await) => {
>f : (await: any) => void
>(await) => {} : (await: any) => void
>await : any
}
@@ -0,0 +1,8 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction3_es6.ts(1,20): error TS2372: Parameter 'await' cannot be referenced in its initializer.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction3_es6.ts (1 errors) ====
function f(await = await) {
~~~~~
!!! error TS2372: Parameter 'await' cannot be referenced in its initializer.
}
@@ -0,0 +1,7 @@
//// [asyncArrowFunction3_es6.ts]
function f(await = await) {
}
//// [asyncArrowFunction3_es6.js]
function f(await = await) {
}
@@ -0,0 +1,7 @@
//// [asyncArrowFunction4_es6.ts]
var await = () => {
}
//// [asyncArrowFunction4_es6.js]
var await = () => {
};
@@ -0,0 +1,4 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction4_es6.ts ===
var await = () => {
>await : Symbol(await, Decl(asyncArrowFunction4_es6.ts, 0, 3))
}
@@ -0,0 +1,5 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction4_es6.ts ===
var await = () => {
>await : () => void
>() => {} : () => void
}
@@ -0,0 +1,24 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(2,11): error TS2304: Cannot find name 'async'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(2,18): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(2,24): error TS1005: ',' expected.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(2,26): error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(2,33): error TS1005: '=' expected.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(2,40): error TS1109: Expression expected.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts (6 errors) ====
var foo = async (await): Promise<void> => {
~~~~~
!!! error TS2304: Cannot find name 'async'.
~~~~~
!!! error TS2304: Cannot find name 'await'.
~
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'.
~
!!! error TS1005: '=' expected.
~~
!!! error TS1109: Expression expected.
}
@@ -0,0 +1,9 @@
//// [asyncArrowFunction5_es6.ts]
var foo = async (await): Promise<void> => {
}
//// [asyncArrowFunction5_es6.js]
var foo = async(await), Promise = ;
{
}
@@ -0,0 +1,12 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction6_es6.ts(2,22): error TS2524: 'await' expressions cannot be used in a parameter initializer.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction6_es6.ts(2,27): error TS1109: Expression expected.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction6_es6.ts (2 errors) ====
var foo = async (a = await): Promise<void> => {
~~~~~
!!! error TS2524: 'await' expressions cannot be used in a parameter initializer.
~
!!! error TS1109: Expression expected.
}
@@ -0,0 +1,8 @@
//// [asyncArrowFunction6_es6.ts]
var foo = async (a = await): Promise<void> => {
}
//// [asyncArrowFunction6_es6.js]
var foo = (a = yield ) => __awaiter(this, void 0, Promise, function* () {
});
@@ -0,0 +1,15 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction7_es6.ts(4,24): error TS2524: 'await' expressions cannot be used in a parameter initializer.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction7_es6.ts(4,29): error TS1109: Expression expected.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction7_es6.ts (2 errors) ====
var bar = async (): Promise<void> => {
// 'await' here is an identifier, and not an await expression.
var foo = async (a = await): Promise<void> => {
~~~~~
!!! error TS2524: 'await' expressions cannot be used in a parameter initializer.
~
!!! error TS1109: Expression expected.
}
}
@@ -0,0 +1,14 @@
//// [asyncArrowFunction7_es6.ts]
var bar = async (): Promise<void> => {
// 'await' here is an identifier, and not an await expression.
var foo = async (a = await): Promise<void> => {
}
}
//// [asyncArrowFunction7_es6.js]
var bar = () => __awaiter(this, void 0, Promise, function* () {
// 'await' here is an identifier, and not an await expression.
var foo = (a = yield ) => __awaiter(this, void 0, Promise, function* () {
});
});
@@ -0,0 +1,10 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction8_es6.ts(3,19): error TS1109: Expression expected.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction8_es6.ts (1 errors) ====
var foo = async (): Promise<void> => {
var v = { [await]: foo }
~
!!! error TS1109: Expression expected.
}
@@ -0,0 +1,10 @@
//// [asyncArrowFunction8_es6.ts]
var foo = async (): Promise<void> => {
var v = { [await]: foo }
}
//// [asyncArrowFunction8_es6.js]
var foo = () => __awaiter(this, void 0, Promise, function* () {
var v = { [yield ]: foo };
});
@@ -0,0 +1,23 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(1,11): error TS2304: Cannot find name 'async'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(1,18): error TS2304: Cannot find name 'a'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(1,37): error TS1005: ',' expected.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(1,39): error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(1,46): error TS1005: '=' expected.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(1,53): error TS1109: Expression expected.
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts (6 errors) ====
var foo = async (a = await => await): Promise<void> => {
~~~~~
!!! error TS2304: Cannot find name 'async'.
~
!!! error TS2304: Cannot find name 'a'.
~
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'.
~
!!! error TS1005: '=' expected.
~~
!!! error TS1109: Expression expected.
}
@@ -0,0 +1,8 @@
//// [asyncArrowFunction9_es6.ts]
var foo = async (a = await => await): Promise<void> => {
}
//// [asyncArrowFunction9_es6.js]
var foo = async(a = await => await), Promise = ;
{
}
@@ -0,0 +1,16 @@
//// [asyncArrowFunctionCapturesArguments_es6.ts]
class C {
method() {
function other() {}
var fn = async () => await other.apply(this, arguments);
}
}
//// [asyncArrowFunctionCapturesArguments_es6.js]
class C {
method() {
function other() { }
var fn = () => __awaiter(this, arguments, Promise, function* (_arguments) { return yield other.apply(this, _arguments); });
}
}
@@ -0,0 +1,20 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es6.ts ===
class C {
>C : Symbol(C, Decl(asyncArrowFunctionCapturesArguments_es6.ts, 0, 0))
method() {
>method : Symbol(method, Decl(asyncArrowFunctionCapturesArguments_es6.ts, 0, 9))
function other() {}
>other : Symbol(other, Decl(asyncArrowFunctionCapturesArguments_es6.ts, 1, 13))
var fn = async () => await other.apply(this, arguments);
>fn : Symbol(fn, Decl(asyncArrowFunctionCapturesArguments_es6.ts, 3, 9))
>other.apply : Symbol(Function.apply, Decl(lib.d.ts, 228, 20))
>other : Symbol(other, Decl(asyncArrowFunctionCapturesArguments_es6.ts, 1, 13))
>apply : Symbol(Function.apply, Decl(lib.d.ts, 228, 20))
>this : Symbol(C, Decl(asyncArrowFunctionCapturesArguments_es6.ts, 0, 0))
>arguments : Symbol(arguments)
}
}
@@ -0,0 +1,22 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es6.ts ===
class C {
>C : C
method() {
>method : () => void
function other() {}
>other : () => void
var fn = async () => await other.apply(this, arguments);
>fn : () => Promise<any>
>async () => await other.apply(this, arguments) : () => Promise<any>
>other.apply(this, arguments) : any
>other.apply : (thisArg: any, argArray?: any) => any
>other : () => void
>apply : (thisArg: any, argArray?: any) => any
>this : C
>arguments : IArguments
}
}
@@ -0,0 +1,14 @@
//// [asyncArrowFunctionCapturesThis_es6.ts]
class C {
method() {
var fn = async () => await this;
}
}
//// [asyncArrowFunctionCapturesThis_es6.js]
class C {
method() {
var fn = () => __awaiter(this, void 0, Promise, function* () { return yield this; });
}
}
@@ -0,0 +1,13 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunctionCapturesThis_es6.ts ===
class C {
>C : Symbol(C, Decl(asyncArrowFunctionCapturesThis_es6.ts, 0, 0))
method() {
>method : Symbol(method, Decl(asyncArrowFunctionCapturesThis_es6.ts, 0, 9))
var fn = async () => await this;
>fn : Symbol(fn, Decl(asyncArrowFunctionCapturesThis_es6.ts, 2, 9))
>this : Symbol(C, Decl(asyncArrowFunctionCapturesThis_es6.ts, 0, 0))
}
}
@@ -0,0 +1,14 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunctionCapturesThis_es6.ts ===
class C {
>C : C
method() {
>method : () => void
var fn = async () => await this;
>fn : () => Promise<C>
>async () => await this : () => Promise<C>
>this : C
}
}
@@ -0,0 +1,45 @@
tests/cases/conformance/async/es6/asyncAwaitIsolatedModules_es6.ts(1,27): error TS2307: Cannot find module 'missing'.
==== tests/cases/conformance/async/es6/asyncAwaitIsolatedModules_es6.ts (1 errors) ====
import { MyPromise } from "missing";
~~~~~~~~~
!!! error TS2307: Cannot find module 'missing'.
declare var p: Promise<number>;
declare var mp: MyPromise<number>;
async function f0() { }
async function f1(): Promise<void> { }
async function f3(): MyPromise<void> { }
let f4 = async function() { }
let f5 = async function(): Promise<void> { }
let f6 = async function(): MyPromise<void> { }
let f7 = async () => { };
let f8 = async (): Promise<void> => { };
let f9 = async (): MyPromise<void> => { };
let f10 = async () => p;
let f11 = async () => mp;
let f12 = async (): Promise<number> => mp;
let f13 = async (): MyPromise<number> => p;
let o = {
async m1() { },
async m2(): Promise<void> { },
async m3(): MyPromise<void> { }
};
class C {
async m1() { }
async m2(): Promise<void> { }
async m3(): MyPromise<void> { }
static async m4() { }
static async m5(): Promise<void> { }
static async m6(): MyPromise<void> { }
}
module M {
export async function f1() { }
}
@@ -0,0 +1,118 @@
//// [asyncAwaitIsolatedModules_es6.ts]
import { MyPromise } from "missing";
declare var p: Promise<number>;
declare var mp: MyPromise<number>;
async function f0() { }
async function f1(): Promise<void> { }
async function f3(): MyPromise<void> { }
let f4 = async function() { }
let f5 = async function(): Promise<void> { }
let f6 = async function(): MyPromise<void> { }
let f7 = async () => { };
let f8 = async (): Promise<void> => { };
let f9 = async (): MyPromise<void> => { };
let f10 = async () => p;
let f11 = async () => mp;
let f12 = async (): Promise<number> => mp;
let f13 = async (): MyPromise<number> => p;
let o = {
async m1() { },
async m2(): Promise<void> { },
async m3(): MyPromise<void> { }
};
class C {
async m1() { }
async m2(): Promise<void> { }
async m3(): MyPromise<void> { }
static async m4() { }
static async m5(): Promise<void> { }
static async m6(): MyPromise<void> { }
}
module M {
export async function f1() { }
}
//// [asyncAwaitIsolatedModules_es6.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
return new Promise(function (resolve, reject) {
generator = generator.call(thisArg, _arguments);
function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
function step(verb, value) {
var result = generator[verb](value);
result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
}
step("next", void 0);
});
};
function f0() {
return __awaiter(this, void 0, Promise, function* () { });
}
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
}
function f3() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
let f4 = function () {
return __awaiter(this, void 0, Promise, function* () { });
};
let f5 = function () {
return __awaiter(this, void 0, Promise, function* () { });
};
let f6 = function () {
return __awaiter(this, void 0, MyPromise, function* () { });
};
let f7 = () => __awaiter(this, void 0, Promise, function* () { });
let f8 = () => __awaiter(this, void 0, Promise, function* () { });
let f9 = () => __awaiter(this, void 0, MyPromise, function* () { });
let f10 = () => __awaiter(this, void 0, Promise, function* () { return p; });
let f11 = () => __awaiter(this, void 0, Promise, function* () { return mp; });
let f12 = () => __awaiter(this, void 0, Promise, function* () { return mp; });
let f13 = () => __awaiter(this, void 0, MyPromise, function* () { return p; });
let o = {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
},
m2() {
return __awaiter(this, void 0, Promise, function* () { });
},
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
};
class C {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
}
m2() {
return __awaiter(this, void 0, Promise, function* () { });
}
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
static m4() {
return __awaiter(this, void 0, Promise, function* () { });
}
static m5() {
return __awaiter(this, void 0, Promise, function* () { });
}
static m6() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
}
var M;
(function (M) {
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
}
M.f1 = f1;
})(M || (M = {}));
+118
View File
@@ -0,0 +1,118 @@
//// [asyncAwait_es6.ts]
type MyPromise<T> = Promise<T>;
declare var MyPromise: typeof Promise;
declare var p: Promise<number>;
declare var mp: MyPromise<number>;
async function f0() { }
async function f1(): Promise<void> { }
async function f3(): MyPromise<void> { }
let f4 = async function() { }
let f5 = async function(): Promise<void> { }
let f6 = async function(): MyPromise<void> { }
let f7 = async () => { };
let f8 = async (): Promise<void> => { };
let f9 = async (): MyPromise<void> => { };
let f10 = async () => p;
let f11 = async () => mp;
let f12 = async (): Promise<number> => mp;
let f13 = async (): MyPromise<number> => p;
let o = {
async m1() { },
async m2(): Promise<void> { },
async m3(): MyPromise<void> { }
};
class C {
async m1() { }
async m2(): Promise<void> { }
async m3(): MyPromise<void> { }
static async m4() { }
static async m5(): Promise<void> { }
static async m6(): MyPromise<void> { }
}
module M {
export async function f1() { }
}
//// [asyncAwait_es6.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
return new Promise(function (resolve, reject) {
generator = generator.call(thisArg, _arguments);
function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
function step(verb, value) {
var result = generator[verb](value);
result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
}
step("next", void 0);
});
};
function f0() {
return __awaiter(this, void 0, Promise, function* () { });
}
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
}
function f3() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
let f4 = function () {
return __awaiter(this, void 0, Promise, function* () { });
};
let f5 = function () {
return __awaiter(this, void 0, Promise, function* () { });
};
let f6 = function () {
return __awaiter(this, void 0, MyPromise, function* () { });
};
let f7 = () => __awaiter(this, void 0, Promise, function* () { });
let f8 = () => __awaiter(this, void 0, Promise, function* () { });
let f9 = () => __awaiter(this, void 0, MyPromise, function* () { });
let f10 = () => __awaiter(this, void 0, Promise, function* () { return p; });
let f11 = () => __awaiter(this, void 0, Promise, function* () { return mp; });
let f12 = () => __awaiter(this, void 0, Promise, function* () { return mp; });
let f13 = () => __awaiter(this, void 0, MyPromise, function* () { return p; });
let o = {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
},
m2() {
return __awaiter(this, void 0, Promise, function* () { });
},
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
};
class C {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
}
m2() {
return __awaiter(this, void 0, Promise, function* () { });
}
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
static m4() {
return __awaiter(this, void 0, Promise, function* () { });
}
static m5() {
return __awaiter(this, void 0, Promise, function* () { });
}
static m6() {
return __awaiter(this, void 0, MyPromise, function* () { });
}
}
var M;
(function (M) {
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
}
M.f1 = f1;
})(M || (M = {}));
@@ -0,0 +1,118 @@
=== tests/cases/conformance/async/es6/asyncAwait_es6.ts ===
type MyPromise<T> = Promise<T>;
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
>T : Symbol(T, Decl(asyncAwait_es6.ts, 0, 15))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>T : Symbol(T, Decl(asyncAwait_es6.ts, 0, 15))
declare var MyPromise: typeof Promise;
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
declare var p: Promise<number>;
>p : Symbol(p, Decl(asyncAwait_es6.ts, 2, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
declare var mp: MyPromise<number>;
>mp : Symbol(mp, Decl(asyncAwait_es6.ts, 3, 11))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
async function f0() { }
>f0 : Symbol(f0, Decl(asyncAwait_es6.ts, 3, 34))
async function f1(): Promise<void> { }
>f1 : Symbol(f1, Decl(asyncAwait_es6.ts, 5, 23))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
async function f3(): MyPromise<void> { }
>f3 : Symbol(f3, Decl(asyncAwait_es6.ts, 6, 38))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
let f4 = async function() { }
>f4 : Symbol(f4, Decl(asyncAwait_es6.ts, 9, 3))
let f5 = async function(): Promise<void> { }
>f5 : Symbol(f5, Decl(asyncAwait_es6.ts, 10, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
let f6 = async function(): MyPromise<void> { }
>f6 : Symbol(f6, Decl(asyncAwait_es6.ts, 11, 3))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
let f7 = async () => { };
>f7 : Symbol(f7, Decl(asyncAwait_es6.ts, 13, 3))
let f8 = async (): Promise<void> => { };
>f8 : Symbol(f8, Decl(asyncAwait_es6.ts, 14, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
let f9 = async (): MyPromise<void> => { };
>f9 : Symbol(f9, Decl(asyncAwait_es6.ts, 15, 3))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
let f10 = async () => p;
>f10 : Symbol(f10, Decl(asyncAwait_es6.ts, 16, 3))
>p : Symbol(p, Decl(asyncAwait_es6.ts, 2, 11))
let f11 = async () => mp;
>f11 : Symbol(f11, Decl(asyncAwait_es6.ts, 17, 3))
>mp : Symbol(mp, Decl(asyncAwait_es6.ts, 3, 11))
let f12 = async (): Promise<number> => mp;
>f12 : Symbol(f12, Decl(asyncAwait_es6.ts, 18, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>mp : Symbol(mp, Decl(asyncAwait_es6.ts, 3, 11))
let f13 = async (): MyPromise<number> => p;
>f13 : Symbol(f13, Decl(asyncAwait_es6.ts, 19, 3))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
>p : Symbol(p, Decl(asyncAwait_es6.ts, 2, 11))
let o = {
>o : Symbol(o, Decl(asyncAwait_es6.ts, 21, 3))
async m1() { },
>m1 : Symbol(m1, Decl(asyncAwait_es6.ts, 21, 9))
async m2(): Promise<void> { },
>m2 : Symbol(m2, Decl(asyncAwait_es6.ts, 22, 16))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
async m3(): MyPromise<void> { }
>m3 : Symbol(m3, Decl(asyncAwait_es6.ts, 23, 31))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
};
class C {
>C : Symbol(C, Decl(asyncAwait_es6.ts, 25, 2))
async m1() { }
>m1 : Symbol(m1, Decl(asyncAwait_es6.ts, 27, 9))
async m2(): Promise<void> { }
>m2 : Symbol(m2, Decl(asyncAwait_es6.ts, 28, 15))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
async m3(): MyPromise<void> { }
>m3 : Symbol(m3, Decl(asyncAwait_es6.ts, 29, 30))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
static async m4() { }
>m4 : Symbol(C.m4, Decl(asyncAwait_es6.ts, 30, 32))
static async m5(): Promise<void> { }
>m5 : Symbol(C.m5, Decl(asyncAwait_es6.ts, 31, 22))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
static async m6(): MyPromise<void> { }
>m6 : Symbol(C.m6, Decl(asyncAwait_es6.ts, 32, 37))
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
}
module M {
>M : Symbol(M, Decl(asyncAwait_es6.ts, 34, 1))
export async function f1() { }
>f1 : Symbol(f1, Decl(asyncAwait_es6.ts, 36, 10))
}
@@ -0,0 +1,129 @@
=== tests/cases/conformance/async/es6/asyncAwait_es6.ts ===
type MyPromise<T> = Promise<T>;
>MyPromise : Promise<T>
>T : T
>Promise : Promise<T>
>T : T
declare var MyPromise: typeof Promise;
>MyPromise : PromiseConstructor
>Promise : PromiseConstructor
declare var p: Promise<number>;
>p : Promise<number>
>Promise : Promise<T>
declare var mp: MyPromise<number>;
>mp : Promise<number>
>MyPromise : Promise<T>
async function f0() { }
>f0 : () => Promise<void>
async function f1(): Promise<void> { }
>f1 : () => Promise<void>
>Promise : Promise<T>
async function f3(): MyPromise<void> { }
>f3 : () => Promise<void>
>MyPromise : Promise<T>
let f4 = async function() { }
>f4 : () => Promise<void>
>async function() { } : () => Promise<void>
let f5 = async function(): Promise<void> { }
>f5 : () => Promise<void>
>async function(): Promise<void> { } : () => Promise<void>
>Promise : Promise<T>
let f6 = async function(): MyPromise<void> { }
>f6 : () => Promise<void>
>async function(): MyPromise<void> { } : () => Promise<void>
>MyPromise : Promise<T>
let f7 = async () => { };
>f7 : () => Promise<void>
>async () => { } : () => Promise<void>
let f8 = async (): Promise<void> => { };
>f8 : () => Promise<void>
>async (): Promise<void> => { } : () => Promise<void>
>Promise : Promise<T>
let f9 = async (): MyPromise<void> => { };
>f9 : () => Promise<void>
>async (): MyPromise<void> => { } : () => Promise<void>
>MyPromise : Promise<T>
let f10 = async () => p;
>f10 : () => Promise<number>
>async () => p : () => Promise<number>
>p : Promise<number>
let f11 = async () => mp;
>f11 : () => Promise<number>
>async () => mp : () => Promise<number>
>mp : Promise<number>
let f12 = async (): Promise<number> => mp;
>f12 : () => Promise<number>
>async (): Promise<number> => mp : () => Promise<number>
>Promise : Promise<T>
>mp : Promise<number>
let f13 = async (): MyPromise<number> => p;
>f13 : () => Promise<number>
>async (): MyPromise<number> => p : () => Promise<number>
>MyPromise : Promise<T>
>p : Promise<number>
let o = {
>o : { m1(): Promise<void>; m2(): Promise<void>; m3(): Promise<void>; }
>{ async m1() { }, async m2(): Promise<void> { }, async m3(): MyPromise<void> { }} : { m1(): Promise<void>; m2(): Promise<void>; m3(): Promise<void>; }
async m1() { },
>m1 : () => Promise<void>
async m2(): Promise<void> { },
>m2 : () => Promise<void>
>Promise : Promise<T>
async m3(): MyPromise<void> { }
>m3 : () => Promise<void>
>MyPromise : Promise<T>
};
class C {
>C : C
async m1() { }
>m1 : () => Promise<void>
async m2(): Promise<void> { }
>m2 : () => Promise<void>
>Promise : Promise<T>
async m3(): MyPromise<void> { }
>m3 : () => Promise<void>
>MyPromise : Promise<T>
static async m4() { }
>m4 : () => Promise<void>
static async m5(): Promise<void> { }
>m5 : () => Promise<void>
>Promise : Promise<T>
static async m6(): MyPromise<void> { }
>m6 : () => Promise<void>
>MyPromise : Promise<T>
}
module M {
>M : typeof M
export async function f1() { }
>f1 : () => Promise<void>
}
@@ -0,0 +1,8 @@
tests/cases/conformance/async/es6/asyncClass_es6.ts(1,1): error TS1042: 'async' modifier cannot be used here.
==== tests/cases/conformance/async/es6/asyncClass_es6.ts (1 errors) ====
async class C {
~~~~~
!!! error TS1042: 'async' modifier cannot be used here.
}
@@ -0,0 +1,7 @@
//// [asyncClass_es6.ts]
async class C {
}
//// [asyncClass_es6.js]
class C {
}
@@ -0,0 +1,10 @@
tests/cases/conformance/async/es6/asyncConstructor_es6.ts(2,3): error TS1089: 'async' modifier cannot appear on a constructor declaration.
==== tests/cases/conformance/async/es6/asyncConstructor_es6.ts (1 errors) ====
class C {
async constructor() {
~~~~~
!!! error TS1089: 'async' modifier cannot appear on a constructor declaration.
}
}
@@ -0,0 +1,11 @@
//// [asyncConstructor_es6.ts]
class C {
async constructor() {
}
}
//// [asyncConstructor_es6.js]
class C {
constructor() {
}
}
@@ -0,0 +1,7 @@
tests/cases/conformance/async/es6/asyncDeclare_es6.ts(1,9): error TS1040: 'async' modifier cannot be used in an ambient context.
==== tests/cases/conformance/async/es6/asyncDeclare_es6.ts (1 errors) ====
declare async function foo(): Promise<void>;
~~~~~
!!! error TS1040: 'async' modifier cannot be used in an ambient context.
@@ -0,0 +1,4 @@
//// [asyncDeclare_es6.ts]
declare async function foo(): Promise<void>;
//// [asyncDeclare_es6.js]
@@ -0,0 +1,9 @@
tests/cases/conformance/async/es6/asyncEnum_es6.ts(1,1): error TS1042: 'async' modifier cannot be used here.
==== tests/cases/conformance/async/es6/asyncEnum_es6.ts (1 errors) ====
async enum E {
~~~~~
!!! error TS1042: 'async' modifier cannot be used here.
Value
}
@@ -0,0 +1,10 @@
//// [asyncEnum_es6.ts]
async enum E {
Value
}
//// [asyncEnum_es6.js]
var E;
(function (E) {
E[E["Value"] = 0] = "Value";
})(E || (E = {}));
@@ -0,0 +1,26 @@
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,20): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,30): error TS1109: Expression expected.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,33): error TS1138: Parameter declaration expected.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,33): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,38): error TS1005: ';' expected.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,39): error TS1128: Declaration or statement expected.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts(1,53): error TS1109: Expression expected.
==== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration10_es6.ts (7 errors) ====
async function foo(a = await => await): Promise<void> {
~~~~~~~~~
!!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
~~
!!! error TS1109: Expression expected.
~~~~~
!!! error TS1138: Parameter declaration expected.
~~~~~
!!! error TS2304: Cannot find name 'await'.
~
!!! error TS1005: ';' expected.
~
!!! error TS1128: Declaration or statement expected.
~
!!! error TS1109: Expression expected.
}
@@ -0,0 +1,7 @@
//// [asyncFunctionDeclaration10_es6.ts]
async function foo(a = await => await): Promise<void> {
}
//// [asyncFunctionDeclaration10_es6.js]
await;
Promise < void > {};
@@ -0,0 +1,9 @@
//// [asyncFunctionDeclaration11_es6.ts]
async function await(): Promise<void> {
}
//// [asyncFunctionDeclaration11_es6.js]
function await() {
return __awaiter(this, void 0, Promise, function* () {
});
}
@@ -0,0 +1,5 @@
=== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration11_es6.ts ===
async function await(): Promise<void> {
>await : Symbol(await, Decl(asyncFunctionDeclaration11_es6.ts, 0, 0))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
}
@@ -0,0 +1,5 @@
=== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration11_es6.ts ===
async function await(): Promise<void> {
>await : () => Promise<void>
>Promise : Promise<T>
}
@@ -0,0 +1,16 @@
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration12_es6.ts(1,24): error TS1005: '(' expected.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration12_es6.ts(1,29): error TS1005: '=' expected.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration12_es6.ts(1,33): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration12_es6.ts(1,47): error TS1005: '=>' expected.
==== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration12_es6.ts (4 errors) ====
var v = async function await(): Promise<void> { }
~~~~~
!!! error TS1005: '(' expected.
~
!!! error TS1005: '=' expected.
~~~~~~~~~~~~~
!!! error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement.
~
!!! error TS1005: '=>' expected.
@@ -0,0 +1,5 @@
//// [asyncFunctionDeclaration12_es6.ts]
var v = async function await(): Promise<void> { }
//// [asyncFunctionDeclaration12_es6.js]
var v = , await = () => { };
@@ -0,0 +1,11 @@
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration13_es6.ts(3,11): error TS2304: Cannot find name 'await'.
==== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration13_es6.ts (1 errors) ====
async function foo(): Promise<void> {
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
}
@@ -0,0 +1,14 @@
//// [asyncFunctionDeclaration13_es6.ts]
async function foo(): Promise<void> {
// Legal to use 'await' in a type context.
var v: await;
}
//// [asyncFunctionDeclaration13_es6.js]
function foo() {
return __awaiter(this, void 0, Promise, function* () {
// Legal to use 'await' in a type context.
var v;
});
}
@@ -0,0 +1,11 @@
//// [asyncFunctionDeclaration14_es6.ts]
async function foo(): Promise<void> {
return;
}
//// [asyncFunctionDeclaration14_es6.js]
function foo() {
return __awaiter(this, void 0, Promise, function* () {
return;
});
}
@@ -0,0 +1,7 @@
=== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration14_es6.ts ===
async function foo(): Promise<void> {
>foo : Symbol(foo, Decl(asyncFunctionDeclaration14_es6.ts, 0, 0))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
return;
}

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