Merge remote-tracking branch 'origin/master' into reuseProgramStructure

This commit is contained in:
Vladimir Matveev 2015-07-09 14:40:54 -07:00
commit 6a502cdacc
861 changed files with 22582 additions and 2546 deletions

View file

@ -716,3 +716,9 @@ task('tsc-instrumented', [loggedIOJsPath, instrumenterJsPath, tscFile], function
});
ex.run();
}, { async: true });
desc("Updates the sublime plugin's tsserver");
task("update-sublime", [serverFile], function() {
jake.cpR(serverFile, "../TypeScript-Sublime-Plugin/tsserver/");
jake.cpR(serverFile + ".map", "../TypeScript-Sublime-Plugin/tsserver/");
});

87
scripts/errorCheck.ts Normal file
View file

@ -0,0 +1,87 @@
declare var require: any;
let fs = require('fs');
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');
for (let k of keys) {
messages[k]['seen'] = false;
}
let errRegex = /\(\d+,\d+\): error TS([^:]+):/g;
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 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;
}
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 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;
}
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');
});
});

View 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,10 +189,11 @@ 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.
// 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
@ -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) {
@ -314,6 +323,7 @@ namespace ts {
addToContainerChain(container);
}
else if (containerFlags & ContainerFlags.IsBlockScopedContainer) {
blockScopeContainer = node;
blockScopeContainer.locals = undefined;
@ -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,7 +965,8 @@ 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;

File diff suppressed because it is too large Load diff

View file

@ -38,6 +38,16 @@ namespace ts {
name: "inlineSources",
type: "boolean",
},
{
name: "jsx",
type: {
"preserve": JsxEmit.Preserve,
"react": JsxEmit.React
},
paramType: Diagnostics.KIND,
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
error: Diagnostics.Argument_for_jsx_must_be_preserve_or_react
},
{
name: "listFiles",
type: "boolean",
@ -193,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",
@ -401,18 +416,29 @@ namespace ts {
}
function getFileNames(): string[] {
var fileNames: string[] = [];
let fileNames: string[] = [];
if (hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
}
else {
var exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude);
for (var i = 0; i < sysFiles.length; i++) {
var name = sysFiles[i];
if (!fileExtensionIs(name, ".d.ts") || !contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) {
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));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
let baseName = name.substr(0, name.length - ".d.ts".length);
if (!contains(sysFiles, baseName + ".tsx") && !contains(sysFiles, baseName + ".ts")) {
fileNames.push(name);
}
}
else if (fileExtensionIs(name, ".ts")) {
if (!contains(sysFiles, name + "x")) {
fileNames.push(name)
}
}
else {
fileNames.push(name);
}
}

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> {
@ -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++) {
@ -702,9 +709,9 @@ namespace ts {
/**
* List of supported extensions in order of file resolution precedence.
*/
export const supportedExtensions = [".ts", ".d.ts"];
export const supportedExtensions = [".tsx", ".ts", ".d.ts"];
const extensionsToRemove = [".d.ts", ".ts", ".js"];
const extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"];
export function removeFileExtension(path: string): string {
for (let ext of extensionsToRemove) {
if (fileExtensionIs(path, ext)) {
@ -757,8 +764,8 @@ namespace ts {
}
Node.prototype = {
kind: kind,
pos: 0,
end: 0,
pos: -1,
end: -1,
flags: 0,
parent: undefined,
};
@ -798,4 +805,4 @@ namespace ts {
Debug.assert(false, message);
}
}
}
}

View file

@ -40,7 +40,6 @@ namespace ts {
function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit {
let newLine = host.getNewLine();
let compilerOptions = host.getCompilerOptions();
let languageVersion = compilerOptions.target || ScriptTarget.ES3;
let write: (s: string) => void;
let writeLine: () => void;
@ -189,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.
@ -199,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;
}
@ -341,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:
@ -352,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) {
@ -361,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) {
@ -397,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);
@ -417,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);
@ -589,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) {
@ -634,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);
@ -913,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;
@ -1505,7 +1525,7 @@ namespace ts {
}
}
}
}
}
}
function emitNode(node: Node) {
@ -1565,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);

View file

@ -20,22 +20,21 @@ namespace ts {
An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation." },
An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." },
An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." },
A_class_or_interface_declaration_can_only_have_one_extends_clause: { code: 1024, category: DiagnosticCategory.Error, key: "A class or interface declaration can only have one 'extends' clause." },
An_extends_clause_must_precede_an_implements_clause: { code: 1025, category: DiagnosticCategory.Error, key: "An 'extends' clause must precede an 'implements' clause." },
A_class_can_only_extend_a_single_class: { code: 1026, category: DiagnosticCategory.Error, key: "A class can only extend a single class." },
A_class_declaration_can_only_have_one_implements_clause: { code: 1027, category: DiagnosticCategory.Error, key: "A class declaration can only have one 'implements' clause." },
Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen." },
_0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." },
_0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen." },
_0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." },
An_interface_declaration_cannot_have_an_implements_clause: { code: 1032, category: DiagnosticCategory.Error, key: "An interface declaration cannot have an 'implements' clause." },
super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." },
Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." },
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_declare_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an interface declaration." },
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." },
@ -44,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." },
@ -94,7 +99,6 @@ namespace ts {
case_or_default_expected: { code: 1130, category: DiagnosticCategory.Error, key: "'case' or 'default' expected." },
Property_or_signature_expected: { code: 1131, category: DiagnosticCategory.Error, key: "Property or signature expected." },
Enum_member_expected: { code: 1132, category: DiagnosticCategory.Error, key: "Enum member expected." },
Type_reference_expected: { code: 1133, category: DiagnosticCategory.Error, key: "Type reference expected." },
Variable_declaration_expected: { code: 1134, category: DiagnosticCategory.Error, key: "Variable declaration expected." },
Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected." },
Property_assignment_expected: { code: 1136, category: DiagnosticCategory.Error, key: "Property assignment expected." },
@ -111,9 +115,6 @@ namespace ts {
Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile modules unless the '--module' flag is provided." },
File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "File name '{0}' differs from already included file name '{1}' only in casing" },
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
var_let_or_const_expected: { code: 1152, category: DiagnosticCategory.Error, key: "'var', 'let' or 'const' expected." },
let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1153, category: DiagnosticCategory.Error, key: "'let' declarations are only available when targeting ECMAScript 6 and higher." },
const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1154, category: DiagnosticCategory.Error, key: "'const' declarations are only available when targeting ECMAScript 6 and higher." },
const_declarations_must_be_initialized: { code: 1155, category: DiagnosticCategory.Error, key: "'const' declarations must be initialized" },
const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block." },
let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block." },
@ -124,7 +125,6 @@ namespace ts {
Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in enums." },
A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: DiagnosticCategory.Error, key: "A computed property name in an ambient context must directly refer to a built-in symbol." },
A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: DiagnosticCategory.Error, key: "A computed property name in a class property declaration must directly refer to a built-in symbol." },
Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1167, category: DiagnosticCategory.Error, key: "Computed property names are only available when targeting ECMAScript 6 and higher." },
A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: DiagnosticCategory.Error, key: "A computed property name in a method overload must directly refer to a built-in symbol." },
A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: DiagnosticCategory.Error, key: "A computed property name in an interface must directly refer to a built-in symbol." },
A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: DiagnosticCategory.Error, key: "A computed property name in a type literal must directly refer to a built-in symbol." },
@ -140,7 +140,6 @@ namespace ts {
Property_destructuring_pattern_expected: { code: 1180, category: DiagnosticCategory.Error, key: "Property destructuring pattern expected." },
Array_element_destructuring_pattern_expected: { code: 1181, category: DiagnosticCategory.Error, key: "Array element destructuring pattern expected." },
A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer." },
Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts." },
An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts." },
Modifiers_cannot_appear_here: { code: 1184, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." },
Merge_conflict_marker_encountered: { code: 1185, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." },
@ -191,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." },
@ -205,7 +212,6 @@ namespace ts {
Module_0_has_no_exported_member_1: { code: 2305, category: DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." },
File_0_is_not_a_module: { code: 2306, category: DiagnosticCategory.Error, key: "File '{0}' is not a module." },
Cannot_find_module_0: { code: 2307, category: DiagnosticCategory.Error, key: "Cannot find module '{0}'." },
A_module_cannot_have_more_than_one_export_assignment: { code: 2308, category: DiagnosticCategory.Error, key: "A module cannot have more than one export assignment." },
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." },
Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." },
A_class_may_only_extend_another_class: { code: 2311, category: DiagnosticCategory.Error, key: "A class may only extend another class." },
@ -233,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}'." },
@ -395,6 +401,29 @@ 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." },
Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: DiagnosticCategory.Error, key: "Property '{0}' in type '{1}' is not assignable to type '{2}'" },
JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: DiagnosticCategory.Error, key: "JSX element type '{0}' does not have any construct or call signatures." },
JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: DiagnosticCategory.Error, key: "JSX element type '{0}' is not a constructor function for JSX elements." },
Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: DiagnosticCategory.Error, key: "Property '{0}' of JSX spread attribute is not assignable to target property." },
JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" },
The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" },
Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@ -531,15 +560,18 @@ namespace ts {
File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: DiagnosticCategory.Error, key: "File '{0}' has unsupported extension. The only supported extensions are {1}." },
Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: DiagnosticCategory.Message, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." },
Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: DiagnosticCategory.Message, key: "Do not emit declarations for code that has an '@internal' annotation." },
Preserve_new_lines_when_emitting_code: { code: 6057, category: DiagnosticCategory.Message, key: "Preserve new-lines when emitting code." },
Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: DiagnosticCategory.Message, key: "Specifies the root directory of input files. Use to control the output directory structure with --outDir." },
File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: DiagnosticCategory.Error, key: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." },
Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." },
NEWLINE: { code: 6061, category: DiagnosticCategory.Message, key: "NEWLINE" },
Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: DiagnosticCategory.Message, key: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: DiagnosticCategory.Message, key: "Argument for '--jsx' must be 'preserve' or 'react'." },
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." },
@ -556,6 +588,7 @@ namespace ts {
_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: DiagnosticCategory.Error, key: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." },
JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" },
You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." },
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: DiagnosticCategory.Error, key: "You cannot rename elements that are defined in the standard TypeScript library." },
import_can_only_be_used_in_a_ts_file: { code: 8002, category: DiagnosticCategory.Error, key: "'import ... =' can only be used in a .ts file." },
@ -573,5 +606,12 @@ namespace ts {
enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." },
type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." },
decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." },
Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." },
class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." },
JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: DiagnosticCategory.Error, key: "JSX attributes must only be assigned a non-empty 'expression'." },
JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: DiagnosticCategory.Error, key: "JSX elements cannot have multiple attributes with the same name." },
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." },
};
}

View file

@ -67,22 +67,6 @@
"category": "Error",
"code": 1023
},
"A class or interface declaration can only have one 'extends' clause.": {
"category": "Error",
"code": 1024
},
"An 'extends' clause must precede an 'implements' clause.": {
"category": "Error",
"code": 1025
},
"A class can only extend a single class.": {
"category": "Error",
"code": 1026
},
"A class declaration can only have one 'implements' clause.": {
"category": "Error",
"code": 1027
},
"Accessibility modifier already seen.": {
"category": "Error",
"code": 1028
@ -99,10 +83,6 @@
"category": "Error",
"code": 1031
},
"An interface declaration cannot have an 'implements' clause.": {
"category": "Error",
"code": 1032
},
"'super' must be followed by an argument list or member access.": {
"category": "Error",
"code": 1034
@ -123,11 +103,27 @@
"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 'declare' modifier cannot be used with an interface declaration.": {
"A '{0}' modifier cannot be used with an interface declaration.": {
"category": "Error",
"code": 1045
},
@ -163,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
@ -183,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
},
@ -363,10 +383,6 @@
"category": "Error",
"code": 1132
},
"Type reference expected.": {
"category": "Error",
"code": 1133
},
"Variable declaration expected.": {
"category": "Error",
"code": 1134
@ -431,18 +447,6 @@
"category": "Error",
"code": 1150
},
"'var', 'let' or 'const' expected.": {
"category": "Error",
"code": 1152
},
"'let' declarations are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1153
},
"'const' declarations are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1154
},
"'const' declarations must be initialized": {
"category": "Error",
"code": 1155
@ -483,10 +487,6 @@
"category": "Error",
"code": 1166
},
"Computed property names are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1167
},
"A computed property name in a method overload must directly refer to a built-in symbol.": {
"category": "Error",
"code": 1168
@ -547,10 +547,6 @@
"category": "Error",
"code": 1182
},
"Destructuring declarations are not allowed in ambient contexts.": {
"category": "Error",
"code": 1183
},
"An implementation cannot be declared in ambient contexts.": {
"category": "Error",
"code": 1184
@ -686,7 +682,7 @@
"Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": {
"category": "Error",
"code": 1219
},
},
"Generators are only available when targeting ECMAScript 6 or higher.": {
"category": "Error",
"code": 1220
@ -751,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
@ -777,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
@ -810,10 +837,6 @@
"category": "Error",
"code": 2307
},
"A module cannot have more than one export assignment.": {
"category": "Error",
"code": 2308
},
"An export assignment cannot be used in a module with other exported elements.": {
"category": "Error",
"code": 2309
@ -922,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
},
@ -934,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
},
@ -1570,7 +1593,98 @@
"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
},
"The return type of a JSX element constructor must return an object type.": {
"category": "Error",
"code": 2601
},
"JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist.": {
"category": "Error",
"code": 2602
},
"Property '{0}' in type '{1}' is not assignable to type '{2}'": {
"category": "Error",
"code": 2603
},
"JSX element type '{0}' does not have any construct or call signatures.": {
"category": "Error",
"code": 2604
},
"JSX element type '{0}' is not a constructor function for JSX elements.": {
"category": "Error",
"code": 2605
},
"Property '{0}' of JSX spread attribute is not assignable to target property.": {
"category": "Error",
"code": 2606
},
"JSX element class does not support attributes because it does not have a '{0}' property": {
"category": "Error",
"code": 2607
},
"The global type 'JSX.{0}' may not have more than one property": {
"category": "Error",
"code": 2608
},
"Cannot emit namespaced JSX elements in React": {
"category": "Error",
"code": 2650
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@ -1939,7 +2053,7 @@
"category": "Error",
"code": 5050
},
"Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.": {
"Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.": {
"category": "Error",
"code": 5051
},
@ -2116,10 +2230,6 @@
"category": "Message",
"code": 6056
},
"Preserve new-lines when emitting code.": {
"category": "Message",
"code": 6057
},
"Specifies the root directory of input files. Use to control the output directory structure with --outDir.": {
"category": "Message",
"code": 6058
@ -2132,14 +2242,22 @@
"category": "Message",
"code": 6060
},
"NEWLINE": {
"category": "Message",
"NEWLINE": {
"category": "Message",
"code": 6061
},
"Argument for '--newLine' option must be 'CRLF' or 'LF'.": {
"category": "Error",
"category": "Error",
"code": 6062
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
},
"Argument for '--jsx' must be 'preserve' or 'react'.": {
"category": "Message",
"code": 6081
},
"Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified.": {
"category": "Error",
"code": 6064
@ -2152,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",
@ -2217,6 +2343,12 @@
"category": "Error",
"code": 7025
},
"JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists": {
"category": "Error",
"code": 7026
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@ -2284,5 +2416,34 @@
"'decorators' can only be used in a .ts file.": {
"category": "Error",
"code": 8017
},
"Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": {
"category": "Error",
"code": 9002
},
"'class' expressions are not currently supported.": {
"category": "Error",
"code": 9003
},
"JSX attributes must only be assigned a non-empty 'expression'.": {
"category": "Error",
"code": 17000
},
"JSX elements cannot have multiple attributes with the same name.": {
"category": "Error",
"code": 17001
},
"Expected corresponding JSX closing tag for '{0}'.": {
"category": "Error",
"code": 17002
},
"JSX attribute expected.": {
"category": "Error",
"code": 17003
},
"Cannot use JSX unless the '--jsx' flag is provided.": {
"category": "Error",
"code": 17004
}
}

View file

@ -47,16 +47,33 @@ 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;
let sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
let diagnostics: Diagnostic[] = [];
let newLine = host.getNewLine();
let jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve;
let shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring);
if (targetSourceFile === undefined) {
forEach(host.getSourceFiles(), sourceFile => {
if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js");
let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, sourceFile);
}
});
@ -68,7 +85,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
else {
// targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service)
if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {
let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js");
let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, forEach(host.getSourceFiles(), shouldEmitJsx) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
else if (!isDeclarationFile(targetSourceFile) && compilerOptions.out) {
@ -112,7 +129,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
let writeLine = writer.writeLine;
let increaseIndent = writer.increaseIndent;
let decreaseIndent = writer.decreaseIndent;
let currentSourceFile: SourceFile;
// name of an exporter function if file is a System external module
// System.register([...], function (<exporter>) {...})
@ -129,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[];
@ -1111,6 +1129,224 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emit(span.literal);
}
function jsxEmitReact(node: JsxElement|JsxSelfClosingElement) {
/// Emit a tag name, which is either '"div"' for lower-cased names, or
/// 'Div' for upper-cased or dotted names
function emitTagName(name: Identifier|QualifiedName) {
if (name.kind === SyntaxKind.Identifier && isIntrinsicJsxName((<Identifier>name).text)) {
write('"');
emit(name);
write('"');
}
else {
emit(name);
}
}
/// Emit an attribute name, which is quoted if it needs to be quoted. Because
/// these emit into an object literal property name, we don't need to be worried
/// about keywords, just non-identifier characters
function emitAttributeName(name: Identifier) {
if (/[A-Za-z_]+[\w*]/.test(name.text)) {
write('"');
emit(name);
write('"');
}
else {
emit(name);
}
}
/// Emit an name/value pair for an attribute (e.g. "x: 3")
function emitJsxAttribute(node: JsxAttribute) {
emitAttributeName(node.name);
write(": ");
if (node.initializer) {
emit(node.initializer);
}
else {
write("true");
}
}
function emitJsxElement(openingNode: JsxOpeningLikeElement, children?: JsxChild[]) {
// Call React.createElement(tag, ...
emitLeadingComments(openingNode);
write("React.createElement(");
emitTagName(openingNode.tagName);
write(", ");
// Attribute list
if (openingNode.attributes.length === 0) {
// When there are no attributes, React wants "null"
write("null");
}
else {
// Either emit one big object literal (no spread attribs), or
// a call to React.__spread
let attrs = openingNode.attributes;
if (forEach(attrs, attr => attr.kind === SyntaxKind.JsxSpreadAttribute)) {
write("React.__spread(");
let haveOpenedObjectLiteral = false;
for (let i = 0; i < attrs.length; i++) {
if (attrs[i].kind === SyntaxKind.JsxSpreadAttribute) {
// If this is the first argument, we need to emit a {} as the first argument
if (i === 0) {
write("{}, ");
}
if (haveOpenedObjectLiteral) {
write("}");
haveOpenedObjectLiteral = false;
}
if (i > 0) {
write(", ");
}
emit((<JsxSpreadAttribute>attrs[i]).expression);
}
else {
Debug.assert(attrs[i].kind === SyntaxKind.JsxAttribute);
if (haveOpenedObjectLiteral) {
write(", ");
}
else {
haveOpenedObjectLiteral = true;
if (i > 0) {
write(", ");
}
write("{");
}
emitJsxAttribute(<JsxAttribute>attrs[i]);
}
}
if (haveOpenedObjectLiteral) write("}");
write(")"); // closing paren to React.__spread(
}
else {
// One object literal with all the attributes in them
write("{");
for (var i = 0; i < attrs.length; i++) {
if (i > 0) {
write(", ");
}
emitJsxAttribute(<JsxAttribute>attrs[i]);
}
write("}");
}
}
// Children
if (children) {
for (var i = 0; i < children.length; i++) {
// Don't emit empty expressions
if (children[i].kind === SyntaxKind.JsxExpression && !((<JsxExpression>children[i]).expression)) {
continue;
}
// Don't emit empty strings
if (children[i].kind === SyntaxKind.JsxText) {
let text = getTextToEmit(<JsxText>children[i]);
if(text !== undefined) {
write(', "');
write(text);
write('"');
}
}
else {
write(", ");
emit(children[i]);
}
}
}
// Closing paren
write(")"); // closes "React.createElement("
emitTrailingComments(openingNode);
}
if (node.kind === SyntaxKind.JsxElement) {
emitJsxElement((<JsxElement>node).openingElement, (<JsxElement>node).children);
}
else {
Debug.assert(node.kind === SyntaxKind.JsxSelfClosingElement);
emitJsxElement(<JsxSelfClosingElement>node);
}
}
function jsxEmitPreserve(node: JsxElement|JsxSelfClosingElement) {
function emitJsxAttribute(node: JsxAttribute) {
emit(node.name);
write("=");
emit(node.initializer);
}
function emitJsxSpreadAttribute(node: JsxSpreadAttribute) {
write("{...");
emit(node.expression);
write("}");
}
function emitAttributes(attribs: NodeArray<JsxAttribute|JsxSpreadAttribute>) {
for (let i = 0, n = attribs.length; i < n; i++) {
if (i > 0) {
write(" ");
}
if (attribs[i].kind === SyntaxKind.JsxSpreadAttribute) {
emitJsxSpreadAttribute(<JsxSpreadAttribute>attribs[i]);
}
else {
Debug.assert(attribs[i].kind === SyntaxKind.JsxAttribute);
emitJsxAttribute(<JsxAttribute>attribs[i]);
}
}
}
function emitJsxOpeningOrSelfClosingElement(node: JsxOpeningElement|JsxSelfClosingElement) {
write("<");
emit(node.tagName);
if (node.attributes.length > 0 || (node.kind === SyntaxKind.JsxSelfClosingElement)) {
write(" ");
}
emitAttributes(node.attributes);
if (node.kind === SyntaxKind.JsxSelfClosingElement) {
write("/>");
}
else {
write(">");
}
}
function emitJsxClosingElement(node: JsxClosingElement) {
write("</");
emit(node.tagName);
write(">");
}
function emitJsxElement(node: JsxElement) {
emitJsxOpeningOrSelfClosingElement(node.openingElement);
for (var i = 0, n = node.children.length; i < n; i++) {
emit(node.children[i]);
}
emitJsxClosingElement(node.closingElement);
}
if (node.kind === SyntaxKind.JsxElement) {
emitJsxElement(<JsxElement>node);
}
else {
Debug.assert(node.kind === SyntaxKind.JsxSelfClosingElement);
emitJsxOpeningOrSelfClosingElement(<JsxSelfClosingElement>node);
}
}
// This function specifically handles numeric/string literals for enum and accessor 'identifiers'.
// In a sense, it does not actually emit identifiers as much as it declares a name for a specific property.
// For example, this is utilized when feeding in a result to Object.defineProperty.
@ -1187,6 +1423,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.NewExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.PostfixUnaryExpression:
@ -1226,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) {
@ -1365,6 +1608,30 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emit(node.expression);
}
}
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) {
@ -1663,8 +1930,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
function parenthesizeForAccess(expr: Expression): LeftHandSideExpression {
// When diagnosing whether the expression needs parentheses, the decision should be based
// on the innermost expression in a chain of nested type assertions.
while (expr.kind === SyntaxKind.TypeAssertionExpression) {
expr = (<TypeAssertion>expr).expression;
while (expr.kind === SyntaxKind.TypeAssertionExpression || expr.kind === SyntaxKind.AsExpression) {
expr = (<AssertionExpression>expr).expression;
}
// isLeftHandSideExpression is almost the correct criterion for when it is not necessary
@ -1824,8 +2091,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
function skipParentheses(node: Expression): Expression {
while (node.kind === SyntaxKind.ParenthesizedExpression || node.kind === SyntaxKind.TypeAssertionExpression) {
node = (<ParenthesizedExpression | TypeAssertion>node).expression;
while (node.kind === SyntaxKind.ParenthesizedExpression || node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression) {
node = (<ParenthesizedExpression | AssertionExpression>node).expression;
}
return node;
}
@ -1975,12 +2242,12 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
// not the user. If we didn't want them, the emitter would not have put them
// there.
if (!nodeIsSynthesized(node) && node.parent.kind !== SyntaxKind.ArrowFunction) {
if (node.expression.kind === SyntaxKind.TypeAssertionExpression) {
if (node.expression.kind === SyntaxKind.TypeAssertionExpression || node.expression.kind === SyntaxKind.AsExpression) {
let operand = (<TypeAssertion>node.expression).expression;
// Make sure we consider all nested cast expressions, e.g.:
// (<any><number><any>-A).x;
while (operand.kind === SyntaxKind.TypeAssertionExpression) {
while (operand.kind === SyntaxKind.TypeAssertionExpression || operand.kind === SyntaxKind.AsExpression) {
operand = (<TypeAssertion>operand).expression;
}
@ -3345,8 +3612,149 @@ 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;
@ -3364,19 +3772,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
else {
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)) {
emitExportMemberAssignment(node);
}
@ -3394,7 +3798,7 @@ 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;
}
@ -3842,7 +4246,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
emitClassLikeDeclarationForES6AndHigher(node);
}
}
function emitClassLikeDeclarationForES6AndHigher(node: ClassLikeDeclaration) {
let thisNodeIsDecorated = nodeIsDecorated(node);
if (node.kind === SyntaxKind.ClassDeclaration) {
@ -4101,7 +4505,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write(".prototype");
}
}
function emitDecoratorsOfClass(node: ClassLikeDeclaration) {
emitDecoratorsOfMembers(node, /*staticFlag*/ 0);
emitDecoratorsOfMembers(node, NodeFlags.Static);
@ -5013,7 +5417,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
let started = false;
for (let importNode of externalImports) {
// do not create variable declaration for exports and imports that lack import clause
let skipNode =
let skipNode =
importNode.kind === SyntaxKind.ExportDeclaration ||
(importNode.kind === SyntaxKind.ImportDeclaration && !(<ImportDeclaration>importNode).importClause)
@ -5110,7 +5514,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
write("};");
return emitExportStarFunction(exportedNamesStorageRef);
function emitExportStarFunction(localNames: string): string {
const exportStarFunction = makeUniqueName("exportStar");
@ -5137,7 +5541,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
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
@ -5433,7 +5837,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
if (importNode.kind === SyntaxKind.ImportDeclaration &&
(<ImportDeclaration>importNode).importClause.namedBindings) {
let namedBindings = (<ImportDeclaration>importNode).importClause.namedBindings;
if (namedBindings.kind === SyntaxKind.NamespaceImport) {
// emit re-export for namespace
@ -5692,6 +6096,99 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
}
}
function emitJsxElement(node: JsxElement | JsxSelfClosingElement) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
jsxEmitReact(node);
break;
case JsxEmit.Preserve:
// Fall back to preserve if None was specified (we'll error earlier)
default:
jsxEmitPreserve(node);
break;
}
}
function trimReactWhitespace(node: JsxText): string {
let result: string = undefined;
let text = getTextOfNode(node);
let firstNonWhitespace = 0;
let lastNonWhitespace = -1;
// JSX trims whitespace at the end and beginning of lines, except that the
// start/end of a tag is considered a start/end of a line only if that line is
// on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
for (let i = 0; i < text.length; i++) {
let c = text.charCodeAt(i);
if (isLineBreak(c)) {
if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
let part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
result = (result ? result + '" + \' \' + "' : '') + part;
}
firstNonWhitespace = -1;
}
else if (!isWhiteSpace(c)) {
lastNonWhitespace = i;
if (firstNonWhitespace === -1) {
firstNonWhitespace = i;
}
}
}
if (firstNonWhitespace !== -1) {
let part = text.substr(firstNonWhitespace);
result = (result ? result + '" + \' \' + "' : '') + part;
}
return result;
}
function getTextToEmit(node: JsxText) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
let text = trimReactWhitespace(node);
if (text.length === 0) {
return undefined;
}
else {
return text;
}
case JsxEmit.Preserve:
default:
return getTextOfNode(node, true);
}
}
function emitJsxText(node: JsxText) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
write('"');
write(trimReactWhitespace(node));
write('"');
break;
case JsxEmit.Preserve:
default: // Emit JSX-preserve as default when no --jsx flag is specified
write(getTextOfNode(node, true));
break;
}
}
function emitJsxExpression(node: JsxExpression) {
if (node.expression) {
switch (compilerOptions.jsx) {
case JsxEmit.Preserve:
default:
write('{');
emit(node.expression);
write('}');
break;
case JsxEmit.React:
emit(node.expression);
break;
}
}
}
function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean): number {
for (let i = 0; i < statements.length; ++i) {
if (isPrologueDirective(statements[i])) {
@ -5748,6 +6245,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) {
@ -5834,7 +6336,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
if (node.kind !== SyntaxKind.Block &&
node.parent &&
node.parent.kind === SyntaxKind.ArrowFunction &&
(<ArrowFunction>node.parent).body === node &&
(<ArrowFunction>node.parent).body === node &&
compilerOptions.target <= ScriptTarget.ES5) {
return false;
@ -5879,6 +6381,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return emitTemplateExpression(<TemplateExpression>node);
case SyntaxKind.TemplateSpan:
return emitTemplateSpan(<TemplateSpan>node);
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
return emitJsxElement(<JsxElement|JsxSelfClosingElement>node);
case SyntaxKind.JsxText:
return emitJsxText(<JsxText>node);
case SyntaxKind.JsxExpression:
return emitJsxExpression(<JsxExpression>node);
case SyntaxKind.QualifiedName:
return emitQualifiedName(<QualifiedName>node);
case SyntaxKind.ObjectBindingPattern:
@ -5909,6 +6418,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return emitTaggedTemplateExpression(<TaggedTemplateExpression>node);
case SyntaxKind.TypeAssertionExpression:
return emit((<TypeAssertion>node).expression);
case SyntaxKind.AsExpression:
return emit((<AsExpression>node).expression);
case SyntaxKind.ParenthesizedExpression:
return emitParenExpression(<ParenthesizedExpression>node);
case SyntaxKind.FunctionDeclaration:
@ -5921,6 +6432,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:

File diff suppressed because it is too large Load diff

View file

@ -106,14 +106,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);
@ -313,10 +313,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 };
}
@ -345,53 +350,86 @@ 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);
throw e;
}
}
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);
}
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.
var writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
});
}
function getOptionsDiagnostics(): Diagnostic[] {
@ -473,7 +511,6 @@ namespace ts {
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
let start: number;
let length: number;
let extensions: string;
let diagnosticArgument: string[];
if (refEnd !== undefined && refPos !== undefined) {
start = refPos;
@ -812,6 +849,11 @@ namespace ts {
!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));
}
}
}
}

View file

@ -21,12 +21,16 @@ namespace ts {
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scan(): SyntaxKind;
// Sets the text for the scanner to scan. An optional subrange starting point and length
// can be provided to have the scanner only scan a portion of the text.
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
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
// was in immediately prior to invoking the callback. The result of invoking the callback
@ -41,6 +45,7 @@ namespace ts {
}
let textToToken: Map<SyntaxKind> = {
"abstract": SyntaxKind.AbstractKeyword,
"any": SyntaxKind.AnyKeyword,
"as": SyntaxKind.AsKeyword,
"boolean": SyntaxKind.BooleanKeyword,
@ -102,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,
@ -130,6 +137,7 @@ namespace ts {
"++": SyntaxKind.PlusPlusToken,
"--": SyntaxKind.MinusMinusToken,
"<<": SyntaxKind.LessThanLessThanToken,
"</": SyntaxKind.LessThanSlashToken,
">>": SyntaxKind.GreaterThanGreaterThanToken,
">>>": SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
"&": SyntaxKind.AmpersandToken,
@ -621,11 +629,12 @@ 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.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
text?: string,
onError?: ErrorCallback,
start?: number,
@ -665,9 +674,13 @@ namespace ts {
reScanGreaterToken,
reScanSlashToken,
reScanTemplateToken,
scanJsxIdentifier,
reScanJsxToken,
scanJsxToken,
scan,
setText,
setScriptTarget,
setLanguageVariant,
setOnError,
setTextPos,
tryScan,
@ -1302,6 +1315,9 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.LessThanEqualsToken;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.slash && languageVariant === LanguageVariant.JSX) {
return pos += 2, token = SyntaxKind.LessThanSlashToken;
}
return pos++, token = SyntaxKind.LessThanToken;
case CharacterCodes.equals:
if (isConflictMarkerTrivia(text, pos)) {
@ -1481,6 +1497,62 @@ namespace ts {
return token = scanTemplateAndSetTokenValue();
}
function reScanJsxToken(): SyntaxKind {
pos = tokenPos = startPos;
return token = scanJsxToken();
}
function scanJsxToken(): SyntaxKind {
startPos = tokenPos = pos;
if (pos >= end) {
return token = SyntaxKind.EndOfFileToken;
}
let char = text.charCodeAt(pos);
if (char === CharacterCodes.lessThan) {
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
return token = SyntaxKind.LessThanSlashToken;
}
pos++;
return token = SyntaxKind.LessThanToken;
}
if (char === CharacterCodes.openBrace) {
pos++;
return token = SyntaxKind.OpenBraceToken;
}
while (pos < end) {
pos++;
char = text.charCodeAt(pos);
if ((char === CharacterCodes.openBrace) || (char === CharacterCodes.lessThan)) {
break;
}
}
return token = SyntaxKind.JsxText;
}
// Scans a JSX identifier; these differ from normal identifiers in that
// they allow dashes
function scanJsxIdentifier(): SyntaxKind {
if (token === SyntaxKind.Identifier) {
let firstCharPosition = pos;
while (pos < end) {
let ch = text.charCodeAt(pos);
if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch) : isIdentifierPart(ch))) {
pos++;
}
else {
break;
}
}
tokenValue += text.substr(firstCharPosition, pos - firstCharPosition);
}
return token;
}
function speculationHelper<T>(callback: () => T, isLookahead: boolean): T {
let savePos = pos;
let saveStartPos = startPos;
@ -1525,6 +1597,10 @@ namespace ts {
languageVersion = scriptTarget;
}
function setLanguageVariant(variant: LanguageVariant) {
languageVariant = variant;
}
function setTextPos(textPos: number) {
Debug.assert(textPos >= 0);
pos = textPos;

View file

@ -191,7 +191,8 @@ namespace ts {
return sys.exit(ExitStatus.Success);
}
if (commandLine.options.watch) {
// Firefox has Object.prototype.watch
if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"));
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);

View file

@ -48,6 +48,7 @@ namespace ts {
SemicolonToken,
CommaToken,
LessThanToken,
LessThanSlashToken,
GreaterThanToken,
LessThanEqualsToken,
GreaterThanEqualsToken,
@ -139,8 +140,11 @@ namespace ts {
StaticKeyword,
YieldKeyword,
// Contextual keywords
AbstractKeyword,
AsKeyword,
AnyKeyword,
AsyncKeyword,
AwaitKeyword,
BooleanKeyword,
ConstructorKeyword,
DeclareKeyword,
@ -187,6 +191,7 @@ namespace ts {
ArrayType,
TupleType,
UnionType,
IntersectionType,
ParenthesizedType,
// Binding patterns
ObjectBindingPattern,
@ -207,6 +212,7 @@ namespace ts {
DeleteExpression,
TypeOfExpression,
VoidExpression,
AwaitExpression,
PrefixUnaryExpression,
PostfixUnaryExpression,
BinaryExpression,
@ -217,6 +223,8 @@ namespace ts {
ClassExpression,
OmittedExpression,
ExpressionWithTypeArguments,
AsExpression,
// Misc
TemplateSpan,
SemicolonClassElement,
@ -265,6 +273,16 @@ namespace ts {
// Module references
ExternalModuleReference,
//JSX
JsxElement,
JsxSelfClosingElement,
JsxOpeningElement,
JsxText,
JsxClosingElement,
JsxAttribute,
JsxSpreadAttribute,
JsxExpression,
// Clauses
CaseClause,
DefaultClause,
@ -343,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
}
@ -363,39 +383,53 @@ 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 {
None = 0,
IntrinsicNamedElement = 1 << 0,
IntrinsicIndexedElement = 1 << 1,
ClassElement = 1 << 2,
UnknownElement = 1 << 3,
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement
}
/* @internal */
export const enum RelationComparisonResult {
Succeeded = 1, // Should be truthy
@ -634,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;
}
@ -702,6 +740,10 @@ namespace ts {
expression: UnaryExpression;
}
export interface AwaitExpression extends UnaryExpression {
expression: UnaryExpression;
}
export interface YieldExpression extends Expression {
asteriskToken?: Node;
expression?: Expression;
@ -799,11 +841,64 @@ namespace ts {
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
export interface AsExpression extends Expression {
expression: Expression;
type: TypeNode;
}
export interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
}
export type AssertionExpression = TypeAssertion | AsExpression;
/// A JSX expression of the form <TagName attrs>...</TagName>
export interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
closingElement: JsxClosingElement;
}
/// The opening element of a <Tag>...</Tag> JsxElement
export interface JsxOpeningElement extends Expression {
_openingElementBrand?: any;
tagName: EntityName;
attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>;
}
/// A JSX expression of the form <TagName attrs />
export interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement {
_selfClosingElementBrand?: any;
}
/// Either the opening tag in a <Tag>...</Tag> pair, or the lone <Tag /> in a self-closing form
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
export interface JsxAttribute extends Node {
name: Identifier;
/// JSX attribute initializers are optional; <X y /> is sugar for <X y={true} />
initializer?: Expression;
}
export interface JsxSpreadAttribute extends Node {
expression: Expression;
}
export interface JsxClosingElement extends Node {
tagName: EntityName;
}
export interface JsxExpression extends Expression {
expression?: Expression;
}
export interface JsxText extends Node {
_jsxTextExpressionBrand: any;
}
export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement;
export interface Statement extends Node {
_statementBrand: any;
}
@ -1144,6 +1239,7 @@ namespace ts {
amdDependencies: {path: string; name: string}[];
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
/**
* lib.d.ts should have a reference comment like
@ -1197,6 +1293,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 {
/**
@ -1219,13 +1324,13 @@ 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.
@ -1335,10 +1440,13 @@ namespace ts {
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
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;
@ -1491,7 +1599,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
@ -1515,8 +1623,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),
@ -1570,7 +1678,7 @@ 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
@ -1589,21 +1697,26 @@ namespace ts {
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 */
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
@ -1615,6 +1728,8 @@ namespace ts {
assignmentChecks?: Map<boolean>; // Cache of assignment checks
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
importOnRightSide?: Symbol; // for import declarations - import that appear on the right side
jsxFlags?: JsxFlags; // flags for knowning what kind of element/attributes we're dealing with
resolvedJsxType?: Type; // resolved element attributes type of a JSX openinglike element
}
export const enum TypeFlags {
@ -1632,17 +1747,18 @@ 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 */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@ -1651,6 +1767,8 @@ namespace ts {
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
}
@ -1710,7 +1828,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)
@ -1718,9 +1836,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
@ -1846,6 +1968,7 @@ namespace ts {
help?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
listFiles?: boolean;
locale?: string;
mapRoot?: string;
@ -1872,6 +1995,7 @@ namespace ts {
watch?: boolean;
isolatedModules?: boolean;
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
/* @internal */ stripInternal?: boolean;
@ -1889,6 +2013,12 @@ namespace ts {
System = 4,
}
export const enum JsxEmit {
None = 0,
Preserve = 1,
React = 2
}
export const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
@ -1909,6 +2039,11 @@ namespace ts {
Latest = ES6,
}
export const enum LanguageVariant {
Standard,
JSX
}
export interface ParsedCommandLine {
options: CompilerOptions;
fileNames: string[];
@ -2064,14 +2199,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;

View file

@ -179,7 +179,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) {
@ -204,13 +204,13 @@ namespace ts {
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string {
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia = false): string {
if (nodeIsMissing(node)) {
return "";
}
let text = sourceFile.text;
return text.substring(skipTrivia(text, node.pos), node.end);
return text.substring(includeTrivia ? node.pos : skipTrivia(text, node.pos), node.end);
}
export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string {
@ -221,8 +221,8 @@ namespace ts {
return sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
}
export function getTextOfNode(node: Node): string {
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node);
export function getTextOfNode(node: Node, includeTrivia = false): string {
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
}
// Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__'
@ -309,7 +309,7 @@ namespace ts {
}
export function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan {
let scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.text, /*onError:*/ undefined, pos);
let scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
scanner.scan();
let start = scanner.getTokenPos();
return createTextSpanFromBounds(start, scanner.getTextPos());
@ -781,6 +781,22 @@ 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) {
@ -883,6 +899,7 @@ namespace ts {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.FunctionExpression:
@ -899,6 +916,8 @@ namespace ts {
case SyntaxKind.TemplateExpression:
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.OmittedExpression:
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.YieldExpression:
return true;
case SyntaxKind.QualifiedName:
@ -945,7 +964,8 @@ namespace ts {
return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) ||
forInStatement.expression === node;
case SyntaxKind.TypeAssertionExpression:
return node === (<TypeAssertion>parent).expression;
case SyntaxKind.AsExpression:
return node === (<AssertionExpression>parent).expression;
case SyntaxKind.TemplateSpan:
return node === (<TemplateSpan>parent).expression;
case SyntaxKind.ComputedPropertyName:
@ -1352,6 +1372,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
@ -1402,14 +1426,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;
@ -1437,8 +1463,6 @@ 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;
}
@ -1565,6 +1589,11 @@ namespace ts {
}
}
export function isIntrinsicJsxName(name: string) {
let ch = name.substr(0, 1);
return ch.toLowerCase() === ch;
}
function get16BitUnicodeEscapeSequence(charCode: number): string {
let hexCharCode = charCode.toString(16).toUpperCase();
let paddedHexCode = ("0000" + hexCharCode).slice(-4);
@ -1905,10 +1934,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;
}
@ -1920,6 +1951,8 @@ namespace ts {
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ParenthesizedExpression:
@ -1971,7 +2004,7 @@ namespace ts {
return false;
}
}
export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
return (node.parent.kind === SyntaxKind.QualifiedName && (<QualifiedName>node.parent).right === node) ||
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node);
@ -1985,6 +2018,10 @@ namespace ts {
return fileExtensionIs(fileName, ".js");
}
export function isTsx(fileName: string) {
return fileExtensionIs(fileName, ".tsx");
}
/**
* 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.
@ -1992,7 +2029,6 @@ namespace ts {
function getExpandedCharCodes(input: string): number[] {
let output: number[] = [];
let length = input.length;
let leadSurrogate: number = undefined;
for (let i = 0; i < length; i++) {
let charCode = input.charCodeAt(i);

View file

@ -149,7 +149,7 @@ class CompilerBaselineRunner extends RunnerBase {
// check errors
it('Correct errors for ' + fileName, () => {
if (this.errors) {
Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.ts$/, '.errors.txt'), (): string => {
Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.tsx?$/, '.errors.txt'), (): string => {
if (result.errors.length === 0) return null;
return getErrorBaseline(toBeCompiled, otherFiles, result);
});
@ -159,7 +159,7 @@ class CompilerBaselineRunner extends RunnerBase {
// Source maps?
it('Correct sourcemap content for ' + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.ts$/, '.sourcemap.txt'), () => {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => {
var record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
@ -177,7 +177,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
// check js output
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.ts/, '.js'), () => {
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => {
var tsCode = '';
var tsSources = otherFiles.concat(toBeCompiled);
if (tsSources.length > 1) {
@ -235,7 +235,7 @@ class CompilerBaselineRunner extends RunnerBase {
throw new Error('Number of sourcemap files should be same as js files.');
}
Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.ts/, '.js.map'), () => {
Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.tsx?/, '.js.map'), () => {
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
// We need to return null here or the runBaseLine will actually create a empty file.
// Baselining isn't required here because there is no output.
@ -320,11 +320,11 @@ class CompilerBaselineRunner extends RunnerBase {
let pullExtension = isSymbolBaseLine ? '.symbols.pull' : '.types.pull';
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.ts/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.ts/, pullExtension), () => pullBaseLine);
Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.ts/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
@ -391,7 +391,7 @@ class CompilerBaselineRunner extends RunnerBase {
// this will set up a series of describe/it blocks to run between the setup and cleanup phases
if (this.tests.length === 0) {
var testFiles = this.enumerateFiles(this.basePath, /\.ts$/, { recursive: true });
var testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true });
testFiles.forEach(fn => {
fn = fn.replace(/\\/g, "/");
this.checkTestCodeOutput(fn);

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;
}
}
@ -660,8 +660,7 @@ module FourSlash {
}
errorMsg += "]\n";
Harness.IO.log(errorMsg);
this.raiseError("Member list is not empty at Caret");
this.raiseError("Member list is not empty at Caret: " + errorMsg);
}
}
@ -744,7 +743,7 @@ module FourSlash {
var reference = references[i];
if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) {
if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) {
this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
return;
}
@ -885,8 +884,16 @@ module FourSlash {
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments);
var ranges = this.getRanges();
if (!references) {
if (ranges.length !== 0) {
this.raiseError(`Expected ${ranges.length} rename locations; got none.`);
}
return;
}
if (ranges.length !== references.length) {
this.raiseError(this.assertionMessage("Rename locations", references.length, ranges.length));
this.raiseError("Rename location count does not match result.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
@ -899,9 +906,7 @@ module FourSlash {
if (reference.textSpan.start !== range.start ||
ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError(this.assertionMessage("Rename location",
"[" + reference.textSpan.start + "," + ts.textSpanEnd(reference.textSpan) + ")",
"[" + range.start + "," + range.end + ")"));
this.raiseError("Rename location results do not match.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
}
}

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);
});
}

View file

@ -212,7 +212,7 @@ module Utils {
}
var result = "";
ts.forEach(Object.getOwnPropertyNames(flags),(v: any) => {
ts.forEach(Object.getOwnPropertyNames(flags), (v: any) => {
if (isFinite(v)) {
v = +v;
if (f === +v) {
@ -410,7 +410,7 @@ module Harness {
deleteFile(fileName: string): void;
listFiles(path: string, filter: RegExp, options?: { recursive?: boolean }): string[];
log(text: string): void;
getMemoryUsage? (): number;
getMemoryUsage?(): number;
}
module IOImpl {
@ -794,7 +794,7 @@ module Harness {
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[]{
public toArray(): { fileName: string; file: WriterAggregator; }[] {
var result: { fileName: string; file: WriterAggregator; }[] = [];
for (var p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
@ -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';
@ -1166,6 +1170,12 @@ module Harness {
options.inlineSources = setting.value === 'true';
break;
case 'jsx':
options.jsx = setting.value.toLowerCase() === 'react' ? ts.JsxEmit.React :
setting.value.toLowerCase() === 'preserve' ? ts.JsxEmit.Preserve :
ts.JsxEmit.None;
break;
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
}
@ -1229,7 +1239,7 @@ module Harness {
}
var dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
@ -1428,6 +1438,10 @@ module Harness {
return stringEndsWith(fileName, '.ts');
}
export function isTSX(fileName: string) {
return stringEndsWith(fileName, '.tsx');
}
export function isDTS(fileName: string) {
return stringEndsWith(fileName, '.d.ts');
}
@ -1435,6 +1449,9 @@ module Harness {
export function isJS(fileName: string) {
return stringEndsWith(fileName, '.js');
}
export function isJSX(fileName: string) {
return stringEndsWith(fileName, '.jsx');
}
export function isJSMap(fileName: string) {
return stringEndsWith(fileName, '.js.map');
@ -1455,12 +1472,15 @@ module Harness {
if (isDTS(emittedFile.fileName)) {
// .d.ts file, add to declFiles emit
this.declFilesCode.push(emittedFile);
} else if (isJS(emittedFile.fileName)) {
}
else if (isJS(emittedFile.fileName) || isJSX(emittedFile.fileName)) {
// .js file, add to files
this.files.push(emittedFile);
} else if (isJSMap(emittedFile.fileName)) {
}
else if (isJSMap(emittedFile.fileName)) {
this.sourceMaps.push(emittedFile);
} else {
}
else {
throw new Error('Unrecognized file extension for file ' + emittedFile.fileName);
}
});
@ -1495,6 +1515,16 @@ module Harness {
// Regex for parsing options in the format "@Alpha: Value of any sort"
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module",
"nolib", "sourcemap", "target", "out", "outdir", "noemithelpers", "noemitonerror",
"noimplicitany", "noresolve", "newline", "normalizenewline", "emitbom",
"errortruncation", "usecasesensitivefilenames", "preserveconstenums",
"includebuiltfile", "suppressimplicitanyindexerrors", "stripinternal",
"isolatedmodules", "inlinesourcemap", "maproot", "sourceroot",
"inlinesources", "emitdecoratormetadata", "experimentaldecorators",
"skipdefaultlibcheck", "jsx"];
function extractCompilerSettings(content: string): CompilerSetting[] {
var opts: CompilerSetting[] = [];

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);

View file

@ -49,6 +49,7 @@ if (testConfigFile !== '') {
if (!option) {
continue;
}
switch (option) {
case 'compiler':
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));

View file

@ -27,7 +27,7 @@ class RunnerBase {
var fixedPath = path;
// full paths either start with a drive letter or / for *nix, shouldn't have \ in the path at this point
var fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.ts/g;
var fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
var fullPathList = fixedPath.match(fullPath);
if (fullPathList) {
fullPathList.forEach((match: string) => fixedPath = fixedPath.replace(match, Harness.Path.getFileName(match)));

13
src/lib/core.d.ts vendored
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>;
}

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;
@ -3370,8 +3365,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.
*/
@ -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.
*/
@ -10281,8 +10274,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 +10346,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 +10454,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 +10974,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 +11818,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;
@ -12650,8 +12622,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;
@ -12978,4 +12949,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;

12
src/lib/es6.d.ts vendored
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;
}

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;

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.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));
@ -470,6 +470,7 @@ namespace ts.formatting {
switch (context.contextNode.kind) {
case SyntaxKind.BinaryExpression:
case SyntaxKind.ConditionalExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypePredicate:
return true;

View file

@ -112,7 +112,7 @@ namespace ts.formatting {
static AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([SyntaxKind.MultiLineCommentTrivia]));
static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword);
static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator);
static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.IsKeyword]);
static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]);
static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]);
static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);

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[] = [];

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);

File diff suppressed because it is too large Load diff

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) {

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,

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);
@ -652,4 +653,34 @@ namespace ts {
typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags);
});
}
export function getDeclaredName(typeChecker: TypeChecker, symbol: Symbol, location: Node): string {
// If this is an export or import specifier it could have been renamed using the 'as' syntax.
// If so we want to search for whatever is under the cursor.
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
// Try to get the local symbol if we're dealing with an 'export default'
// since that symbol has the "true" name.
let localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol);
let name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
return stripQuotes(name);
}
export function isImportOrExportSpecifierName(location: Node): boolean {
return location.parent &&
(location.parent.kind === SyntaxKind.ImportSpecifier || location.parent.kind === SyntaxKind.ExportSpecifier) &&
(<ImportOrExportSpecifier>location.parent).propertyName === location;
}
export function stripQuotes(name: string) {
let length = name.length;
if (length >= 2 && name.charCodeAt(0) === CharacterCodes.doubleQuote && name.charCodeAt(length - 1) === CharacterCodes.doubleQuote) {
return name.substring(1, length - 1);
};
return name;
}
}

View file

@ -75,28 +75,28 @@ function delint(sourceFile) {
delintNode(sourceFile);
function delintNode(node) {
switch (node.kind) {
case 189 /* ForStatement */:
case 190 /* ForInStatement */:
case 188 /* WhileStatement */:
case 187 /* DoStatement */:
if (node.statement.kind !== 182 /* 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 186 /* IfStatement */:
case 193 /* IfStatement */:
var ifStatement = node;
if (ifStatement.thenStatement.kind !== 182 /* 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 !== 182 /* Block */ &&
ifStatement.elseStatement.kind !== 186 /* 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 172 /* BinaryExpression */:
case 178 /* BinaryExpression */:
var op = node.operatorToken.kind;
if (op === 28 /* EqualsEqualsToken */ || op == 29 /* ExclamationEqualsToken */) {
if (op === 29 /* EqualsEqualsToken */ || op == 30 /* ExclamationEqualsToken */) {
report(node, "Use '===' and '!=='.");
}
break;

View file

@ -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.
}

View file

@ -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;
{
}

View file

@ -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.
}

View file

@ -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.
}
}

View file

@ -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;
}

View file

@ -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))
}

View file

@ -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
}

View file

@ -0,0 +1,8 @@
//// [abstractInterfaceIdentifierName.ts]
interface abstract {
abstract(): void;
}
//// [abstractInterfaceIdentifierName.js]

View file

@ -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))
}

View file

@ -0,0 +1,9 @@
=== tests/cases/compiler/abstractInterfaceIdentifierName.ts ===
interface abstract {
>abstract : abstract
abstract(): void;
>abstract : () => void
}

View file

@ -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))

View file

@ -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))

View file

@ -0,0 +1,19 @@
//// [asOperator1.ts]
var as = 43;
var x = undefined as number;
var y = (null as string).length;
var z = Date as any as string;
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
j = '';
//// [asOperator1.js]
var as = 43;
var x = undefined;
var y = null.length;
var z = Date;
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32;
j = '';

View file

@ -0,0 +1,24 @@
=== tests/cases/conformance/expressions/asOperator/asOperator1.ts ===
var as = 43;
>as : Symbol(as, Decl(asOperator1.ts, 0, 3))
var x = undefined as number;
>x : Symbol(x, Decl(asOperator1.ts, 1, 3))
>undefined : Symbol(undefined)
var y = (null as string).length;
>y : Symbol(y, Decl(asOperator1.ts, 2, 3))
>(null as string).length : Symbol(String.length, Decl(lib.d.ts, 414, 19))
>length : Symbol(String.length, Decl(lib.d.ts, 414, 19))
var z = Date as any as string;
>z : Symbol(z, Decl(asOperator1.ts, 3, 3))
>Date : Symbol(Date, Decl(lib.d.ts, 633, 23), Decl(lib.d.ts, 815, 11))
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
>j : Symbol(j, Decl(asOperator1.ts, 6, 3))
j = '';
>j : Symbol(j, Decl(asOperator1.ts, 6, 3))

View file

@ -0,0 +1,35 @@
=== tests/cases/conformance/expressions/asOperator/asOperator1.ts ===
var as = 43;
>as : number
>43 : number
var x = undefined as number;
>x : number
>undefined as number : number
>undefined : undefined
var y = (null as string).length;
>y : number
>(null as string).length : number
>(null as string) : string
>null as string : string
>null : null
>length : number
var z = Date as any as string;
>z : string
>Date as any as string : string
>Date as any : any
>Date : DateConstructor
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
>j : string | number
>32 as number|string : string | number
>32 : number
j = '';
>j = '' : string
>j : string | number
>'' : string

View file

@ -0,0 +1,8 @@
tests/cases/conformance/expressions/asOperator/asOperator2.ts(1,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
==== tests/cases/conformance/expressions/asOperator/asOperator2.ts (1 errors) ====
var x = 23 as string;
~~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.

View file

@ -0,0 +1,6 @@
//// [asOperator2.ts]
var x = 23 as string;
//// [asOperator2.js]
var x = 23;

View file

@ -0,0 +1,22 @@
//// [asOperator3.ts]
declare function tag(...x: any[]): any;
var a = `${123 + 456 as number}`;
var b = `leading ${123 + 456 as number}`;
var c = `${123 + 456 as number} trailing`;
var d = `Hello ${123} World` as string;
var e = `Hello` as string;
var f = 1 + `${1} end of string` as string;
var g = tag `Hello ${123} World` as string;
var h = tag `Hello` as string;
//// [asOperator3.js]
var a = "" + 123 + 456;
var b = "leading " + 123 + 456;
var c = 123 + 456 + " trailing";
var d = ("Hello " + 123 + " World");
var e = "Hello";
var f = 1 + (1 + " end of string");
var g = (_a = ["Hello ", " World"], _a.raw = ["Hello ", " World"], tag(_a, 123));
var h = (_b = ["Hello"], _b.raw = ["Hello"], tag(_b));
var _a, _b;

View file

@ -0,0 +1,31 @@
=== tests/cases/conformance/expressions/asOperator/asOperator3.ts ===
declare function tag(...x: any[]): any;
>tag : Symbol(tag, Decl(asOperator3.ts, 0, 0))
>x : Symbol(x, Decl(asOperator3.ts, 0, 21))
var a = `${123 + 456 as number}`;
>a : Symbol(a, Decl(asOperator3.ts, 2, 3))
var b = `leading ${123 + 456 as number}`;
>b : Symbol(b, Decl(asOperator3.ts, 3, 3))
var c = `${123 + 456 as number} trailing`;
>c : Symbol(c, Decl(asOperator3.ts, 4, 3))
var d = `Hello ${123} World` as string;
>d : Symbol(d, Decl(asOperator3.ts, 5, 3))
var e = `Hello` as string;
>e : Symbol(e, Decl(asOperator3.ts, 6, 3))
var f = 1 + `${1} end of string` as string;
>f : Symbol(f, Decl(asOperator3.ts, 7, 3))
var g = tag `Hello ${123} World` as string;
>g : Symbol(g, Decl(asOperator3.ts, 8, 3))
>tag : Symbol(tag, Decl(asOperator3.ts, 0, 0))
var h = tag `Hello` as string;
>h : Symbol(h, Decl(asOperator3.ts, 9, 3))
>tag : Symbol(tag, Decl(asOperator3.ts, 0, 0))

View file

@ -0,0 +1,63 @@
=== tests/cases/conformance/expressions/asOperator/asOperator3.ts ===
declare function tag(...x: any[]): any;
>tag : (...x: any[]) => any
>x : any[]
var a = `${123 + 456 as number}`;
>a : string
>`${123 + 456 as number}` : string
>123 + 456 as number : number
>123 + 456 : number
>123 : number
>456 : number
var b = `leading ${123 + 456 as number}`;
>b : string
>`leading ${123 + 456 as number}` : string
>123 + 456 as number : number
>123 + 456 : number
>123 : number
>456 : number
var c = `${123 + 456 as number} trailing`;
>c : string
>`${123 + 456 as number} trailing` : string
>123 + 456 as number : number
>123 + 456 : number
>123 : number
>456 : number
var d = `Hello ${123} World` as string;
>d : string
>`Hello ${123} World` as string : string
>`Hello ${123} World` : string
>123 : number
var e = `Hello` as string;
>e : string
>`Hello` as string : string
>`Hello` : string
var f = 1 + `${1} end of string` as string;
>f : string
>1 + `${1} end of string` as string : string
>1 + `${1} end of string` : string
>1 : number
>`${1} end of string` : string
>1 : number
var g = tag `Hello ${123} World` as string;
>g : string
>tag `Hello ${123} World` as string : string
>tag `Hello ${123} World` : any
>tag : (...x: any[]) => any
>`Hello ${123} World` : string
>123 : number
var h = tag `Hello` as string;
>h : string
>tag `Hello` as string : string
>tag `Hello` : any
>tag : (...x: any[]) => any
>`Hello` : string

View file

@ -0,0 +1,26 @@
//// [asOperatorASI.ts]
class Foo { }
declare function as(...args: any[]);
// Example 1
var x = 10
as `Hello world`; // should not error
// Example 2
var y = 20
as(Foo); // should emit
//// [asOperatorASI.js]
var Foo = (function () {
function Foo() {
}
return Foo;
})();
// Example 1
var x = 10;
(_a = ["Hello world"], _a.raw = ["Hello world"], as(_a)); // should not error
// Example 2
var y = 20;
as(Foo); // should emit
var _a;

View file

@ -0,0 +1,23 @@
=== tests/cases/conformance/expressions/asOperator/asOperatorASI.ts ===
class Foo { }
>Foo : Symbol(Foo, Decl(asOperatorASI.ts, 0, 0))
declare function as(...args: any[]);
>as : Symbol(as, Decl(asOperatorASI.ts, 0, 13))
>args : Symbol(args, Decl(asOperatorASI.ts, 1, 20))
// Example 1
var x = 10
>x : Symbol(x, Decl(asOperatorASI.ts, 4, 3))
as `Hello world`; // should not error
>as : Symbol(as, Decl(asOperatorASI.ts, 0, 13))
// Example 2
var y = 20
>y : Symbol(y, Decl(asOperatorASI.ts, 8, 3))
as(Foo); // should emit
>as : Symbol(as, Decl(asOperatorASI.ts, 0, 13))
>Foo : Symbol(Foo, Decl(asOperatorASI.ts, 0, 0))

View file

@ -0,0 +1,28 @@
=== tests/cases/conformance/expressions/asOperator/asOperatorASI.ts ===
class Foo { }
>Foo : Foo
declare function as(...args: any[]);
>as : (...args: any[]) => any
>args : any[]
// Example 1
var x = 10
>x : number
>10 : number
as `Hello world`; // should not error
>as `Hello world` : any
>as : (...args: any[]) => any
>`Hello world` : string
// Example 2
var y = 20
>y : number
>20 : number
as(Foo); // should emit
>as(Foo) : any
>as : (...args: any[]) => any
>Foo : typeof Foo

View file

@ -0,0 +1,15 @@
tests/cases/conformance/expressions/asOperator/asOperatorAmbiguity.ts(7,14): error TS2339: Property 'm' does not exist on type 'A<B>'.
==== tests/cases/conformance/expressions/asOperator/asOperatorAmbiguity.ts (1 errors) ====
interface A<T> { x: T; }
interface B { m: string; }
// Make sure this is a type assertion to an array type, and not nested comparison operators.
var x: any;
var y = x as A<B>[];
var z = y[0].m; // z should be string
~
!!! error TS2339: Property 'm' does not exist on type 'A<B>'.

View file

@ -0,0 +1,16 @@
//// [asOperatorAmbiguity.ts]
interface A<T> { x: T; }
interface B { m: string; }
// Make sure this is a type assertion to an array type, and not nested comparison operators.
var x: any;
var y = x as A<B>[];
var z = y[0].m; // z should be string
//// [asOperatorAmbiguity.js]
// Make sure this is a type assertion to an array type, and not nested comparison operators.
var x;
var y = x;
var z = y[0].m; // z should be string

View file

@ -0,0 +1,10 @@
tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts(2,9): error TS2352: Neither type '(v: number) => number' nor type '(x: number) => string' is assignable to the other.
Type 'number' is not assignable to type 'string'.
==== tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts (1 errors) ====
// should error
var x = (v => v) as (x: number) => string;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2352: Neither type '(v: number) => number' nor type '(x: number) => string' is assignable to the other.
!!! error TS2352: Type 'number' is not assignable to type 'string'.

View file

@ -0,0 +1,7 @@
//// [asOperatorContextualType.ts]
// should error
var x = (v => v) as (x: number) => string;
//// [asOperatorContextualType.js]
// should error
var x = (function (v) { return v; });

View file

@ -0,0 +1,11 @@
tests/cases/conformance/expressions/asOperator/asOperatorNames.ts(2,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
==== tests/cases/conformance/expressions/asOperator/asOperatorNames.ts (1 errors) ====
var a = 20;
var b = a as string;
~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
var as = "hello";
var as1 = as as string;

View file

@ -0,0 +1,12 @@
//// [asOperatorNames.ts]
var a = 20;
var b = a as string;
var as = "hello";
var as1 = as as string;
//// [asOperatorNames.js]
var a = 20;
var b = a;
var as = "hello";
var as1 = as;

View file

@ -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'.
}

View file

@ -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;
};

View file

@ -0,0 +1,8 @@
//// [asyncArrowFunction1_es6.ts]
var foo = async (): Promise<void> => {
};
//// [asyncArrowFunction1_es6.js]
var foo = () => __awaiter(this, void 0, Promise, function* () {
});

View file

@ -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))
};

View file

@ -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>
};

View file

@ -0,0 +1,7 @@
//// [asyncArrowFunction2_es6.ts]
var f = (await) => {
}
//// [asyncArrowFunction2_es6.js]
var f = (await) => {
};

View file

@ -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))
}

View file

@ -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
}

View file

@ -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.
}

View file

@ -0,0 +1,7 @@
//// [asyncArrowFunction3_es6.ts]
function f(await = await) {
}
//// [asyncArrowFunction3_es6.js]
function f(await = await) {
}

View file

@ -0,0 +1,7 @@
//// [asyncArrowFunction4_es6.ts]
var await = () => {
}
//// [asyncArrowFunction4_es6.js]
var await = () => {
};

View file

@ -0,0 +1,4 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction4_es6.ts ===
var await = () => {
>await : Symbol(await, Decl(asyncArrowFunction4_es6.ts, 0, 3))
}

View file

@ -0,0 +1,5 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction4_es6.ts ===
var await = () => {
>await : () => void
>() => {} : () => void
}

View file

@ -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.
}

View file

@ -0,0 +1,9 @@
//// [asyncArrowFunction5_es6.ts]
var foo = async (await): Promise<void> => {
}
//// [asyncArrowFunction5_es6.js]
var foo = async(await), Promise = ;
{
}

View file

@ -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.
}

View file

@ -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* () {
});

View file

@ -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.
}
}

View file

@ -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* () {
});
});

View file

@ -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.
}

View file

@ -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 };
});

View file

@ -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.
}

View file

@ -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 = ;
{
}

View file

@ -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); });
}
}

View file

@ -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)
}
}

View file

@ -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
}
}

View file

@ -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; });
}
}

View file

@ -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))
}
}

View file

@ -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
}
}

View file

@ -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() { }
}

View file

@ -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 = {}));

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 = {}));

View file

@ -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))
}

View file

@ -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>
}

View file

@ -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.
}

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