Merge pull request #5 from Microsoft/master

fetch lastest code
This commit is contained in:
York Yao
2016-02-03 09:38:30 +08:00
710 changed files with 20369 additions and 2807 deletions
+20
View File
@@ -2,9 +2,11 @@ TypeScript is authored by:
* Adam Freidin
* Ahmad Farid
* Akshar Patel
* Anders Hejlsberg
* Arnav Singh
* Arthur Ozga
* Asad Saeeduddin
* Basarat Ali Syed
* Ben Duffield
* Bill Ticehurst
@@ -15,30 +17,39 @@ TypeScript is authored by:
* Colby Russell
* Colin Snover
* Cyrus Najmabadi
* Dan Corder
* Dan Quirk
* Daniel Rosenwasser
* @dashaus
* David Li
* Denis Nedelyaev
* Dick van den Brink
* Dirk Bäumer
* Dirk Holtwick
* Eyas Sharaiha
* @falsandtru
* Frank Wallis
* Gabriel Isenberg
* Gilad Peleg
* Graeme Wicksted
* Guillaume Salles
* Guy Bedford
* Harald Niesche
* Iain Monro
* Ingvar Stepanyan
* Ivo Gabe de Wolff
* James Whitney
* Jason Freeman
* Jason Killian
* Jason Ramsay
* Jed Mao
* Jeffrey Morlan
* Johannes Rieken
* John Vilk
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Turner
* Jonathon Smith
* Josh Kalderimis
* Julian Williams
* Kagami Sascha Rosylight
@@ -46,21 +57,27 @@ TypeScript is authored by:
* Ken Howard
* Kenji Imamula
* Lorant Pinter
* Lucien Greathouse
* Martin Všetička
* Masahiro Wakame
* Mattias Buelens
* Max Deepfield
* Micah Zoltu
* Mohamed Hegazy
* Nathan Shively-Sanders
* Nathan Yee
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Paul van Brenk
* @pcbro
* Pedro Maltez
* Philip Bulley
* piloopin
* @progre
* Punya Biswal
* Richard Sentino
* Ron Buckton
* Rowan Wyborn
* Ryan Cavanaugh
* Ryohei Ikegami
* Sébastien Arod
@@ -71,7 +88,9 @@ TypeScript is authored by:
* Solal Pirelli
* Stan Thomas
* Steve Lucco
* Thomas Loubiou
* Tien Hoanhtien
* Tim Perry
* Tingan Ho
* togru
* Tomas Grubliauskas
@@ -81,5 +100,6 @@ TypeScript is authored by:
* Wesley Wigham
* York Yao
* Yui Tanglertsampan
* Yuichi Nukiyama
* Zev Spitz
* Zhengbo Li
+2 -2
View File
@@ -30,7 +30,7 @@ You can try out the nightly build of TypeScript (`npm install typescript@next`)
We also accept suggestions in the issue tracker.
Be sure to [check the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) and [search](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) first.
In general, things we find useful when reviewing suggestins are:
In general, things we find useful when reviewing suggestions are:
* A description of the problem you're trying to solve
* An overview of the suggested solution
* Examples of how the suggestion would work in various places
@@ -71,7 +71,7 @@ Your pull request should:
* Tests should include reasonable permutations of the target fix/change
* Include baseline changes with your change
* All changed code must have 100% code coverage
* Follow the code conventions descriped in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines)
* Follow the code conventions described in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines)
* To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration
## Contributing `lib.d.ts` fixes
Binary file not shown.
+1 -1
View File
@@ -3885,7 +3885,7 @@ function g(x: number) {
the inferred return type for 'f' and 'g' is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type 'number' to either breaks the cycle and causes the return type 'number' to be inferred for the other.
An explicitly typed function whose return type isn't the Void or the Any type must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement.
An explicitly typed function whose return type isn't the Void type, the Any type, or a union type containing the Void or Any type as a constituent must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement.
The type of 'this' in a function implementation is the Any type.
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "1.8.0",
"version": "1.9.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
+16 -7
View File
@@ -1110,7 +1110,7 @@ namespace ts {
}
function checkStrictModeNumericLiteral(node: LiteralExpression) {
if (inStrictMode && node.flags & NodeFlags.OctalLiteral) {
if (inStrictMode && node.isOctalLiteral) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
}
}
@@ -1384,7 +1384,7 @@ namespace ts {
// Export assignment in some sort of block construct
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
}
else if (boundExpression.kind === SyntaxKind.Identifier) {
else if (boundExpression.kind === SyntaxKind.Identifier && node.kind === SyntaxKind.ExportAssignment) {
// An export default clause with an identifier exports all meanings of that identifier
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
@@ -1435,7 +1435,8 @@ namespace ts {
// Declare a 'member' in case it turns out the container was an ES5 class
if (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) {
container.symbol.members = container.symbol.members || {};
declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
// It's acceptable for multiple 'this' assignments of the same identifier to occur
declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property);
}
}
@@ -1444,8 +1445,16 @@ namespace ts {
// Look up the function in the local scope, since prototype assignments should
// follow the function declaration
const classId = <Identifier>(<PropertyAccessExpression>(<PropertyAccessExpression>node.left).expression).expression;
const funcSymbol = container.locals[classId.text];
const leftSideOfAssignment = node.left as PropertyAccessExpression;
const classPrototype = leftSideOfAssignment.expression as PropertyAccessExpression;
const constructorFunction = classPrototype.expression as Identifier;
// Fix up parent pointers since we're going to use these nodes before we bind into them
leftSideOfAssignment.parent = node;
constructorFunction.parent = classPrototype;
classPrototype.parent = leftSideOfAssignment;
const funcSymbol = container.locals[constructorFunction.text];
if (!funcSymbol || !(funcSymbol.flags & SymbolFlags.Function)) {
return;
}
@@ -1456,13 +1465,13 @@ namespace ts {
}
// Declare the method/property
declareSymbol(funcSymbol.members, funcSymbol, <PropertyAccessExpression>node.left, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
function bindCallExpression(node: CallExpression) {
// We're only inspecting call expressions to detect CommonJS modules, so we can skip
// this check if we've already seen the module indicator
if (!file.commonJsModuleIndicator && isRequireCall(node)) {
if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteral*/false)) {
setCommonJsModuleIndicator(node);
}
}
+597 -406
View File
File diff suppressed because it is too large Load Diff
+91 -31
View File
@@ -255,7 +255,7 @@ namespace ts {
name: "moduleResolution",
type: {
"node": ModuleResolutionKind.NodeJs,
"classic": ModuleResolutionKind.Classic
"classic": ModuleResolutionKind.Classic,
},
description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
error: Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic,
@@ -286,14 +286,40 @@ namespace ts {
description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
},
{
name: "allowSyntheticDefaultImports",
name: "baseUrl",
type: "string",
isFilePath: true,
description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names
},
{
// this option can only be specified in tsconfig.json
// use type = object to copy the value as-is
name: "paths",
type: "object",
isTSConfigOnly: true
},
{
// this option can only be specified in tsconfig.json
// use type = object to copy the value as-is
name: "rootDirs",
type: "object",
isTSConfigOnly: true,
isFilePath: true
},
{
name: "traceModuleResolution",
type: "boolean",
description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
description: Diagnostics.Enable_tracing_of_the_module_resolution_process
},
{
name: "allowJs",
type: "boolean",
description: Diagnostics.Allow_javascript_files_to_be_compiled
},
{
name: "allowSyntheticDefaultImports",
type: "boolean",
description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
}
];
@@ -355,34 +381,39 @@ namespace ts {
if (hasProperty(optionNameMap, s)) {
const opt = optionNameMap[s];
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
if (opt.isTSConfigOnly) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
}
else {
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i]);
i++;
break;
case "boolean":
options[opt.name] = true;
break;
case "string":
options[opt.name] = args[i] || "";
i++;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
let map = <Map<number>>opt.type;
let key = (args[i] || "").toLowerCase();
i++;
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i]);
i++;
break;
case "boolean":
options[opt.name] = true;
break;
case "string":
options[opt.name] = args[i] || "";
i++;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
let map = <Map<number>>opt.type;
let key = (args[i] || "").toLowerCase();
i++;
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
}
}
}
}
else {
@@ -485,7 +516,6 @@ namespace ts {
return output;
}
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
@@ -497,6 +527,7 @@ namespace ts {
const { options: optionsFromJsonConfigFile, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName);
const options = extend(existingOptions, optionsFromJsonConfigFile);
return {
options,
fileNames: getFileNames(),
@@ -580,7 +611,36 @@ namespace ts {
}
}
if (opt.isFilePath) {
value = normalizePath(combinePaths(basePath, value));
switch (typeof value) {
case "string":
value = normalizePath(combinePaths(basePath, value));
break;
case "object":
// "object" options with 'isFilePath' = true expected to be string arrays
let paths: string[] = [];
let invalidOptionType = false;
if (!isArray(value)) {
invalidOptionType = true;
}
else {
for (const element of <any[]>value) {
if (typeof element === "string") {
paths.push(normalizePath(combinePaths(basePath, element)));
}
else {
invalidOptionType = true;
break;
}
}
}
if (invalidOptionType) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name));
}
else {
value = paths;
}
break;
}
if (value === "") {
value = ".";
}
+11 -2
View File
@@ -74,8 +74,6 @@ namespace ts {
GreaterThan = 1
}
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.
@@ -441,6 +439,17 @@ namespace ts {
};
}
/* internal */
export function formatMessage(dummy: any, message: DiagnosticMessage): string {
let text = getLocaleSpecificMessage(message);
if (arguments.length > 2) {
text = formatStringFromArgs(text, arguments, 2);
}
return text;
}
export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic;
export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic {
let text = getLocaleSpecificMessage(message);
+18 -13
View File
@@ -637,18 +637,21 @@ namespace ts {
}
}
function emitClassMemberDeclarationFlags(node: Declaration) {
if (node.flags & NodeFlags.Private) {
function emitClassMemberDeclarationFlags(flags: NodeFlags) {
if (flags & NodeFlags.Private) {
write("private ");
}
else if (node.flags & NodeFlags.Protected) {
else if (flags & NodeFlags.Protected) {
write("protected ");
}
if (node.flags & NodeFlags.Static) {
if (flags & NodeFlags.Static) {
write("static ");
}
if (node.flags & NodeFlags.Abstract) {
if (flags & NodeFlags.Readonly) {
write("readonly ");
}
if (flags & NodeFlags.Abstract) {
write("abstract ");
}
}
@@ -1074,7 +1077,7 @@ namespace ts {
}
emitJsDocComments(node);
emitClassMemberDeclarationFlags(node);
emitClassMemberDeclarationFlags(node.flags);
emitVariableDeclaration(<VariableDeclaration>node);
write(";");
writeLine();
@@ -1227,7 +1230,7 @@ namespace ts {
if (node === accessors.firstAccessor) {
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : NodeFlags.Readonly));
writeTextOfNode(currentText, node.name);
if (!(node.flags & NodeFlags.Private)) {
accessorWithTypeAnnotation = node;
@@ -1314,7 +1317,7 @@ namespace ts {
emitModuleElementDeclarationFlags(node);
}
else if (node.kind === SyntaxKind.MethodDeclaration) {
emitClassMemberDeclarationFlags(node);
emitClassMemberDeclarationFlags(node.flags);
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
write("function ");
@@ -1342,15 +1345,17 @@ namespace ts {
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
// Construct signature or constructor type write new Signature
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
}
emitTypeParameters(node.typeParameters);
if (node.kind === SyntaxKind.IndexSignature) {
// Index signature can have readonly modifier
emitClassMemberDeclarationFlags(node.flags);
write("[");
}
else {
// Construct signature or constructor type write new Signature
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
}
emitTypeParameters(node.typeParameters);
write("(");
}
+163 -18
View File
@@ -67,6 +67,10 @@
"category": "Error",
"code": 1023
},
"'readonly' modifier can only appear on a property declaration or index signature.": {
"category": "Error",
"code": 1024
},
"Accessibility modifier already seen.": {
"category": "Error",
"code": 1028
@@ -195,6 +199,10 @@
"category": "Error",
"code": 1063
},
"The return type of an async function or method must be the global Promise<T> type.": {
"category": "Error",
"code": 1064
},
"In ambient enum declarations member initializer must be constant expression.": {
"category": "Error",
"code": 1066
@@ -203,6 +211,14 @@
"category": "Error",
"code": 1068
},
"'{0}' modifier cannot appear on a type member.": {
"category": "Error",
"code": 1070
},
"'{0}' modifier cannot appear on an index signature.": {
"category": "Error",
"code": 1071
},
"A '{0}' modifier cannot be used with an import declaration.": {
"category": "Error",
"code": 1079
@@ -423,10 +439,6 @@
"category": "Error",
"code": 1144
},
"Modifiers not permitted on index signature members.": {
"category": "Error",
"code": 1145
},
"Declaration expected.": {
"category": "Error",
"code": 1146
@@ -794,7 +806,7 @@
"A decorator can only decorate a method implementation, not an overload.": {
"category": "Error",
"code": 1249
},
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
@@ -1379,11 +1391,11 @@
"category": "Error",
"code": 2448
},
"The operand of an increment or decrement operator cannot be a constant.": {
"The operand of an increment or decrement operator cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2449
},
"Left-hand side of assignment expression cannot be a constant.": {
"Left-hand side of assignment expression cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2450
},
@@ -1515,11 +1527,11 @@
"category": "Error",
"code": 2484
},
"The left-hand side of a 'for...of' statement cannot be a previously defined constant.": {
"The left-hand side of a 'for...of' statement cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2485
},
"The left-hand side of a 'for...in' statement cannot be a previously defined constant.": {
"The left-hand side of a 'for...in' statement cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2486
},
@@ -1687,6 +1699,10 @@
"category": "Error",
"code": 2528
},
"Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions.": {
"category": "Error",
"code": 2529
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -1803,6 +1819,10 @@
"category": "Error",
"code": 2670
},
"Cannot augment module '{0}' because it resolves to a non-module entity.": {
"category": "Error",
"code": 2671
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2155,11 +2175,22 @@
"category": "Error",
"code": 5058
},
"Invalide value for '--reactNamespace'. '{0}' is not a valid identifier.": {
"Invalid value for '--reactNamespace'. '{0}' is not a valid identifier.": {
"category": "Error",
"code": 5059
},
"Option 'paths' cannot be used without specifying '--baseUrl' option.": {
"category": "Error",
"code": 5060
},
"Pattern '{0}' can have at most one '*' character": {
"category": "Error",
"code": 5061
},
"Substitution '{0}' in pattern '{1}' in can have at most one '*' character": {
"category": "Error",
"code": 5062
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@@ -2296,10 +2327,10 @@
"category": "Error",
"code": 6046
},
"Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.": {
"category": "Error",
"code": 6047
},
"Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.": {
"category": "Error",
"code": 6047
},
"Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'.": {
"category": "Error",
"code": 6048
@@ -2360,7 +2391,10 @@
"category": "Error",
"code": 6063
},
"Option '{0}' can only be specified in 'tsconfig.json' file.": {
"category": "Error",
"code": 6064
},
"Enables experimental support for ES7 decorators.": {
"category": "Message",
"code": 6065
@@ -2425,7 +2459,7 @@
"category": "Error",
"code": 6082
},
"Allow javascript files to be compiled.": {
"Base directory to resolve non-absolute module names.": {
"category": "Message",
"code": 6083
},
@@ -2433,7 +2467,114 @@
"category": "Message",
"code": 6084
},
"Enable tracing of the module resolution process.": {
"category": "Message",
"code": 6085
},
"======== Resolving module '{0}' from '{1}'. ========": {
"category": "Message",
"code": 6086
},
"Explicitly specified module resolution kind: '{0}'.": {
"category": "Message",
"code": 6087
},
"Module resolution kind is not specified, using '{0}'.": {
"category": "Message",
"code": 6088
},
"======== Module name '{0}' was successfully resolved to '{1}'. ========": {
"category": "Message",
"code": 6089
},
"======== Module name '{0}' was not resolved. ========": {
"category": "Message",
"code": 6090
},
"'paths' option is specified, looking for a pattern to match module name '{0}'.": {
"category": "Message",
"code": 6091
},
"Module name '{0}', matched pattern '{1}'.": {
"category": "Message",
"code": 6092
},
"Trying substitution '{0}', candidate module location: '{1}'.": {
"category": "Message",
"code": 6093
},
"Resolving module name '{0}' relative to base url '{1}' - '{2}'.": {
"category": "Message",
"code": 6094
},
"Loading module as file / folder, candidate module location '{0}'.": {
"category": "Message",
"code": 6095
},
"File '{0}' does not exist.": {
"category": "Message",
"code": 6096
},
"File '{0}' exist - use it as a module resolution result.": {
"category": "Message",
"code": 6097
},
"Loading module '{0}' from 'node_modules' folder.": {
"category": "Message",
"code": 6098
},
"Found 'package.json' at '{0}'.": {
"category": "Message",
"code": 6099
},
"'package.json' does not have 'typings' field.": {
"category": "Message",
"code": 6100
},
"'package.json' has 'typings' field '{0}' that references '{1}'.": {
"category": "Message",
"code": 6101
},
"Allow javascript files to be compiled.": {
"category": "Message",
"code": 6102
},
"Option '{0}' should have array of strings as a value.": {
"category": "Error",
"code": 6103
},
"Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'.": {
"category": "Message",
"code": 6104
},
"Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'.": {
"category": "Message",
"code": 6105
},
"'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'": {
"category": "Message",
"code": 6106
},
"'rootDirs' option is set, using it to resolve relative module name '{0}'": {
"category": "Message",
"code": 6107
},
"Longest matching prefix for '{0}' is '{1}'": {
"category": "Message",
"code": 6108
},
"Loading '{0}' from the root dir '{1}', candidate location '{2}'": {
"category": "Message",
"code": 6109
},
"Trying other entries in 'rootDirs'": {
"category": "Message",
"code": 6110
},
"Module resolution using 'rootDirs' has failed": {
"category": "Message",
"code": 6111
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2634,5 +2775,9 @@
"JSX element '{0}' has no corresponding closing tag.": {
"category": "Error",
"code": 17008
},
"'super' must be called before accessing 'this' in the constructor of a derived class.": {
"category": "Error",
"code": 17009
}
}
+322 -136
View File
@@ -320,11 +320,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
const awaiterHelper = `
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};`;
@@ -477,10 +477,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// =>
// var x;... exporter("x", x = 1)
let exportFunctionForFile: string;
let contextObjectForFile: string;
let generatedNameSet: Map<string>;
let nodeToGeneratedName: string[];
let computedPropertyNamesToGeneratedNames: string[];
let decoratedClassAliases: string[];
let convertedLoopState: ConvertedLoopState;
@@ -531,6 +533,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
generatedNameSet = {};
nodeToGeneratedName = [];
decoratedClassAliases = [];
isOwnFileEmit = !isBundledEmit;
// Emit helpers from all the files
@@ -557,8 +560,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
currentText = undefined;
currentLineMap = undefined;
exportFunctionForFile = undefined;
contextObjectForFile = undefined;
generatedNameSet = undefined;
nodeToGeneratedName = undefined;
decoratedClassAliases = undefined;
computedPropertyNamesToGeneratedNames = undefined;
convertedLoopState = undefined;
extendsEmitted = false;
@@ -585,6 +590,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
currentText = sourceFile.text;
currentLineMap = getLineStarts(sourceFile);
exportFunctionForFile = undefined;
contextObjectForFile = undefined;
isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"];
renamedDependencies = sourceFile.renamedDependencies;
currentFileIdentifiers = sourceFile.identifiers;
@@ -1257,26 +1263,50 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// Children
if (children) {
for (let i = 0; i < children.length; i++) {
// Don't emit empty expressions
if (children[i].kind === SyntaxKind.JsxExpression && !((<JsxExpression>children[i]).expression)) {
continue;
}
let firstChild: JsxChild;
let multipleEmittableChildren = false;
// Don't emit empty strings
if (children[i].kind === SyntaxKind.JsxText) {
const text = getTextToEmit(<JsxText>children[i]);
if (text !== undefined) {
write(", \"");
write(text);
write("\"");
for (let i = 0, n = children.length; i < n; i++) {
const jsxChild = children[i];
if (isJsxChildEmittable(jsxChild)) {
// we need to decide whether to emit in single line or multiple lines as indented list
// store firstChild reference, if we see another emittable child, then emit accordingly
if (!firstChild) {
write(", ");
firstChild = jsxChild;
}
else {
// more than one emittable child, emit indented list
if (!multipleEmittableChildren) {
multipleEmittableChildren = true;
increaseIndent();
writeLine();
emit(firstChild);
}
write(", ");
writeLine();
emit(jsxChild);
}
}
else {
write(", ");
emit(children[i]);
}
}
if (multipleEmittableChildren) {
decreaseIndent();
}
else if (firstChild) {
if (firstChild.kind !== SyntaxKind.JsxElement && firstChild.kind !== SyntaxKind.JsxSelfClosingElement) {
emit(firstChild);
}
else {
// If the only child is jsx element, put it on a new indented line
increaseIndent();
writeLine();
emit(firstChild);
writeLine();
decreaseIndent();
}
}
}
@@ -1488,11 +1518,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
function emitExpressionIdentifier(node: Identifier) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.LexicalArguments) {
write("_arguments");
return;
}
const container = resolver.getReferencedExportContainer(node);
if (container) {
if (container.kind === SyntaxKind.SourceFile) {
@@ -1534,13 +1559,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
if (languageVersion !== ScriptTarget.ES6) {
const declaration = resolver.getReferencedNestedRedeclaration(node);
if (languageVersion < ScriptTarget.ES6) {
const declaration = resolver.getReferencedDeclarationWithCollidingName(node);
if (declaration) {
write(getGeneratedNameForNode(declaration.name));
return;
}
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BodyScopedClassBinding) {
// Due to the emit for class decorators, any reference to the class from inside of the class body
// must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
// behavior of class names in ES6.
const declaration = resolver.getReferencedValueDeclaration(node);
if (declaration) {
const classAlias = decoratedClassAliases[getNodeId(declaration)];
if (classAlias !== undefined) {
write(classAlias);
return;
}
}
}
}
if (nodeIsSynthesized(node)) {
@@ -1551,7 +1589,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
function isNameOfNestedRedeclaration(node: Identifier) {
function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node: Identifier) {
if (languageVersion < ScriptTarget.ES6) {
const parent = node.parent;
switch (parent.kind) {
@@ -1559,7 +1597,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.VariableDeclaration:
return (<Declaration>parent).name === node && resolver.isNestedRedeclaration(<Declaration>parent);
return (<Declaration>parent).name === node && resolver.isDeclarationWithCollidingName(<Declaration>parent);
}
}
return false;
@@ -1581,7 +1619,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
else if (isExpressionIdentifier(node)) {
emitExpressionIdentifier(node);
}
else if (isNameOfNestedRedeclaration(node)) {
else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) {
write(getGeneratedNameForNode(node));
}
else if (nodeIsSynthesized(node)) {
@@ -1766,7 +1804,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write("]");
}
else {
emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/(node.flags & NodeFlags.MultiLine) !== 0,
emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ node.multiLine,
/*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true);
}
}
@@ -1789,7 +1827,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= ScriptTarget.ES5, /*spacesBetweenBraces*/ true);
}
else {
const multiLine = (node.flags & NodeFlags.MultiLine) !== 0;
const multiLine = node.multiLine;
if (!multiLine) {
write(" ");
}
@@ -1812,7 +1850,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
function emitDownlevelObjectLiteralWithComputedProperties(node: ObjectLiteralExpression, firstComputedPropertyIndex: number) {
const multiLine = (node.flags & NodeFlags.MultiLine) !== 0;
const multiLine = node.multiLine;
const properties = node.properties;
write("(");
@@ -2122,6 +2160,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return;
}
if (languageVersion === ScriptTarget.ES6 &&
node.expression.kind === SyntaxKind.SuperKeyword &&
isInAsyncMethodWithSuperInES6(node)) {
const name = <StringLiteral>createSynthesizedNode(SyntaxKind.StringLiteral);
name.text = node.name.text;
emitSuperAccessInAsyncMethod(node.expression, name);
return;
}
emit(node.expression);
const indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
@@ -2207,6 +2254,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (tryEmitConstantValue(node)) {
return;
}
if (languageVersion === ScriptTarget.ES6 &&
node.expression.kind === SyntaxKind.SuperKeyword &&
isInAsyncMethodWithSuperInES6(node)) {
emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression);
return;
}
emit(node.expression);
write("[");
emit(node.argumentExpression);
@@ -2282,23 +2337,47 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write(")");
}
function isInAsyncMethodWithSuperInES6(node: Node) {
if (languageVersion === ScriptTarget.ES6) {
const container = getSuperContainer(node, /*includeFunctions*/ false);
if (container && resolver.getNodeCheckFlags(container) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding)) {
return true;
}
}
return false;
}
function emitSuperAccessInAsyncMethod(superNode: Node, argumentExpression: Expression) {
const container = getSuperContainer(superNode, /*includeFunctions*/ false);
const isSuperBinding = resolver.getNodeCheckFlags(container) & NodeCheckFlags.AsyncMethodWithSuperBinding;
write("_super(");
emit(argumentExpression);
write(isSuperBinding ? ").value" : ")");
}
function emitCallExpression(node: CallExpression) {
if (languageVersion < ScriptTarget.ES6 && hasSpreadElement(node.arguments)) {
emitCallWithSpread(node);
return;
}
const expression = node.expression;
let superCall = false;
if (node.expression.kind === SyntaxKind.SuperKeyword) {
emitSuper(node.expression);
let isAsyncMethodWithSuper = false;
if (expression.kind === SyntaxKind.SuperKeyword) {
emitSuper(expression);
superCall = true;
}
else {
emit(node.expression);
superCall = node.expression.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.expression).expression.kind === SyntaxKind.SuperKeyword;
superCall = isSuperPropertyOrElementAccess(expression);
isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node);
emit(expression);
}
if (superCall && languageVersion < ScriptTarget.ES6) {
if (superCall && (languageVersion < ScriptTarget.ES6 || isAsyncMethodWithSuper)) {
write(".call(");
emitThis(node.expression);
emitThis(expression);
if (node.arguments.length) {
write(", ");
emitCommaList(node.arguments);
@@ -2528,12 +2607,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return false;
}
let current: Node = node;
let current = getRootDeclaration(node).parent;
while (current) {
if (current.kind === SyntaxKind.SourceFile) {
return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0);
}
else if (isFunctionLike(current) || current.kind === SyntaxKind.ModuleBlock) {
else if (isDeclaration(current)) {
return false;
}
else {
@@ -2855,7 +2934,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function shouldConvertLoopBody(node: IterationStatement): boolean {
return languageVersion < ScriptTarget.ES6 &&
(resolver.getNodeCheckFlags(node) & NodeCheckFlags.LoopWithBlockScopedBindingCapturedInFunction) !== 0;
(resolver.getNodeCheckFlags(node) & NodeCheckFlags.LoopWithCapturedBlockScopedBinding) !== 0;
}
function emitLoop(node: IterationStatement, loopEmitter: (n: IterationStatement, convertedLoop: ConvertedLoop) => void): void {
@@ -3009,7 +3088,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function collectNames(name: Identifier | BindingPattern): void {
if (name.kind === SyntaxKind.Identifier) {
const nameText = isNameOfNestedRedeclaration(<Identifier>name) ? getGeneratedNameForNode(name) : (<Identifier>name).text;
const nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(<Identifier>name) ? getGeneratedNameForNode(name) : (<Identifier>name).text;
loopParameters.push(nameText);
}
else {
@@ -3083,7 +3162,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
else {
// top level converted loop - return unwrapped value
write(`return ${loopResult}.value`);
write(`return ${loopResult}.value;`);
}
writeLine();
}
@@ -3853,7 +3932,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// We create a synthetic copy of the identifier in order to avoid the rewriting that might
// otherwise occur when the identifier is emitted.
index = <Identifier | LiteralExpression>createSynthesizedNode(propName.kind);
(<Identifier | LiteralExpression>index).text = (<Identifier | LiteralExpression>propName).text;
// We need to unescape identifier here because when parsing an identifier prefixing with "__"
// the parser need to append "_" in order to escape colliding with magic identifiers such as "__proto__"
// Therefore, in order to correctly emit identifiers that are written in original TypeScript file,
// we will unescapeIdentifier to remove additional underscore (if no underscore is added, the function will return original input string)
(<Identifier | LiteralExpression>index).text = unescapeIdentifier((<Identifier | LiteralExpression>propName).text);
}
return !nameIsComputed && index.kind === SyntaxKind.Identifier
@@ -4025,22 +4108,56 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
else {
let initializer = node.initializer;
if (!initializer && languageVersion < ScriptTarget.ES6) {
if (!initializer &&
languageVersion < ScriptTarget.ES6 &&
// for names - binding patterns that lack initializer there is no point to emit explicit initializer
// since downlevel codegen for destructuring will fail in the absence of initializer so all binding elements will say uninitialized
node.name.kind === SyntaxKind.Identifier) {
// downlevel emit for non-initialized let bindings defined in loops
// for (...) { let x; }
// should be
// for (...) { var <some-uniqie-name> = void 0; }
// this is necessary to preserve ES6 semantic in scenarios like
// for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations
const isLetDefinedInLoop =
(resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) &&
(getCombinedFlagsForIdentifier(<Identifier>node.name) & NodeFlags.Let);
const container = getEnclosingBlockScopeContainer(node);
const flags = resolver.getNodeCheckFlags(node);
// NOTE: default initialization should not be added to let bindings in for-in\for-of statements
if (isLetDefinedInLoop &&
node.parent.parent.kind !== SyntaxKind.ForInStatement &&
node.parent.parent.kind !== SyntaxKind.ForOfStatement) {
// nested let bindings might need to be initialized explicitly to preserve ES6 semantic
// { let x = 1; }
// { let x; } // x here should be undefined. not 1
// NOTES:
// Top level bindings never collide with anything and thus don't require explicit initialization.
// As for nested let bindings there are two cases:
// - nested let bindings that were not renamed definitely should be initialized explicitly
// { let x = 1; }
// { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
// Without explicit initialization code in /*1*/ can be executed even if some-condition is evaluated to false
// - renaming introduces fresh name that should not collide with any existing names, however renamed bindings sometimes also should be
// explicitly initialized. One particular case: non-captured binding declared inside loop body (but not in loop initializer)
// let x;
// for (;;) {
// let x;
// }
// in downlevel codegen inner 'x' will be renamed so it won't collide with outer 'x' however it will should be reset on every iteration
// as if it was declared anew.
// * Why non-captured binding - because if loop contains block scoped binding captured in some function then loop body will be rewritten
// to have a fresh scope on every iteration so everything will just work.
// * Why loop initializer is excluded - since we've introduced a fresh name it already will be undefined.
const isCapturedInFunction = flags & NodeCheckFlags.CapturedBlockScopedBinding;
const isDeclaredInLoop = flags & NodeCheckFlags.BlockScopedBindingInLoop;
const emittedAsTopLevel =
isBlockScopedContainerTopLevel(container) ||
(isCapturedInFunction && isDeclaredInLoop && container.kind === SyntaxKind.Block && isIterationStatement(container.parent, /*lookInLabeledStatements*/ false));
const emittedAsNestedLetDeclaration =
getCombinedNodeFlags(node) & NodeFlags.Let &&
!emittedAsTopLevel;
const emitExplicitInitializer =
emittedAsNestedLetDeclaration &&
container.kind !== SyntaxKind.ForInStatement &&
container.kind !== SyntaxKind.ForOfStatement &&
(
!resolver.isDeclarationWithCollidingName(node) ||
(isDeclaredInLoop && !isCapturedInFunction && !isIterationStatement(container, /*lookInLabeledStatements*/ false))
);
if (emitExplicitInitializer) {
initializer = createVoidZero();
}
}
@@ -4075,14 +4192,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
function getCombinedFlagsForIdentifier(node: Identifier): NodeFlags {
if (!node.parent || (node.parent.kind !== SyntaxKind.VariableDeclaration && node.parent.kind !== SyntaxKind.BindingElement)) {
return 0;
}
return getCombinedNodeFlags(node.parent);
}
function isES6ExportedDeclaration(node: Node) {
return !!(node.flags & NodeFlags.Export) &&
modulekind === ModuleKind.ES6 &&
@@ -4470,6 +4579,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write(" {");
increaseIndent();
writeLine();
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
writeLines(`
const _super = (function (geti, seti) {
const cache = Object.create(null);
return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });
})(name => super[name], (name, value) => super[name] = value);`);
writeLine();
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
write(`const _super = name => super[name];`);
writeLine();
}
write("return");
}
@@ -4481,20 +4604,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write(", void 0, ");
}
if (promiseConstructor) {
emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false);
if (languageVersion >= ScriptTarget.ES6 || !promiseConstructor) {
write("void 0");
}
else {
write("Promise");
emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false);
}
// Emit the call to __awaiter.
if (hasLexicalArguments) {
write(", function* (_arguments)");
}
else {
write(", function* ()");
}
write(", function* ()");
// Emit the signature and body for the inner generator function.
emitFunctionBody(node);
@@ -5031,64 +5149,107 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
function emitClassLikeDeclarationForES6AndHigher(node: ClassLikeDeclaration) {
let decoratedClassAlias: string;
const thisNodeIsDecorated = nodeIsDecorated(node);
if (node.kind === SyntaxKind.ClassDeclaration) {
if (thisNodeIsDecorated) {
// To preserve the correct runtime semantics when decorators are applied to the class,
// the emit needs to follow one of the following rules:
// When we emit an ES6 class that has a class decorator, we must tailor the
// emit to certain specific cases.
//
// * For a local class declaration:
// In the simplest case, we emit the class declaration as a let declaration, and
// evaluate decorators after the close of the class body:
//
// @dec class C {
// }
// TypeScript | Javascript
// --------------------------------|------------------------------------
// @dec | let C = class C {
// class C { | }
// } | C = __decorate([dec], C);
// --------------------------------|------------------------------------
// @dec | export let C = class C {
// export class C { | }
// } | C = __decorate([dec], C);
// ---------------------------------------------------------------------
// [Example 1]
//
// The emit should be:
// If a class declaration contains a reference to itself *inside* of the class body,
// this introduces two bindings to the class: One outside of the class body, and one
// inside of the class body. If we apply decorators as in [Example 1] above, there
// is the possibility that the decorator `dec` will return a new value for the
// constructor, which would result in the binding inside of the class no longer
// pointing to the same reference as the binding outside of the class.
//
// let C = class {
// };
// C = __decorate([dec], C);
// As a result, we must instead rewrite all references to the class *inside* of the
// class body to instead point to a local temporary alias for the class:
//
// * For an exported class declaration:
// TypeScript | Javascript
// --------------------------------|------------------------------------
// @dec | let C_1;
// class C { | let C = C_1 = class C {
// static x() { return C.y; } | static x() { return C_1.y; }
// static y = 1; | }
// } | C.y = 1;
// | C = C_1 = __decorate([dec], C);
// --------------------------------|------------------------------------
// @dec | let C_1;
// export class C { | export let C = C_1 = class C {
// static x() { return C.y; } | static x() { return C_1.y; }
// static y = 1; | }
// } | C.y = 1;
// | C = C_1 = __decorate([dec], C);
// ---------------------------------------------------------------------
// [Example 2]
//
// @dec export class C {
// }
// If a class declaration is the default export of a module, we instead emit
// the export after the decorated declaration:
//
// The emit should be:
// TypeScript | Javascript
// --------------------------------|------------------------------------
// @dec | let default_1 = class {
// export default class { | }
// } | default_1 = __decorate([dec], default_1);
// | export default default_1;
// --------------------------------|------------------------------------
// @dec | let C = class C {
// export default class { | }
// } | C = __decorate([dec], C);
// | export default C;
// ---------------------------------------------------------------------
// [Example 3]
//
// export let C = class {
// };
// C = __decorate([dec], C);
// If the class declaration is the default export and a reference to itself
// inside of the class body, we must emit both an alias for the class *and*
// move the export after the declaration:
//
// * For a default export of a class declaration with a name:
//
// @dec default export class C {
// }
//
// The emit should be:
//
// let C = class {
// }
// C = __decorate([dec], C);
// export default C;
//
// * For a default export of a class declaration without a name:
//
// @dec default export class {
// }
//
// The emit should be:
//
// let _default = class {
// }
// _default = __decorate([dec], _default);
// export default _default;
// TypeScript | Javascript
// --------------------------------|------------------------------------
// @dec | let C_1;
// export default class C { | let C = C_1 = class C {
// static x() { return C.y; } | static x() { return C_1.y; }
// static y = 1; | }
// } | C.y = 1;
// | C = C_1 = __decorate([dec], C);
// | export default C;
// ---------------------------------------------------------------------
// [Example 4]
//
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithBodyScopedClassBinding) {
decoratedClassAlias = unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default"));
decoratedClassAliases[getNodeId(node)] = decoratedClassAlias;
write(`let ${decoratedClassAlias};`);
writeLine();
}
if (isES6ExportedDeclaration(node) && !(node.flags & NodeFlags.Default)) {
write("export ");
}
write("let ");
emitDeclarationName(node);
if (decoratedClassAlias !== undefined) {
write(` = ${decoratedClassAlias}`);
}
write(" = ");
}
else if (isES6ExportedDeclaration(node)) {
@@ -5127,7 +5288,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// emit name if
// - node has a name
// - this is default export with static initializers
if ((node.name || (node.flags & NodeFlags.Default && (staticProperties.length > 0 || modulekind !== ModuleKind.ES6))) && !thisNodeIsDecorated) {
if (node.name || (node.flags & NodeFlags.Default && (staticProperties.length > 0 || modulekind !== ModuleKind.ES6) && !thisNodeIsDecorated)) {
write(" ");
emitDeclarationName(node);
}
@@ -5147,16 +5308,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
// TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now.
// For a decorated class, we need to assign its name (if it has one). This is because we emit
// the class as a class expression to avoid the double-binding of the identifier:
//
// let C = class {
// }
// Object.defineProperty(C, "name", { value: "C", configurable: true });
//
if (thisNodeIsDecorated) {
decoratedClassAliases[getNodeId(node)] = undefined;
write(";");
}
@@ -5181,7 +5334,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
else {
writeLine();
emitPropertyDeclarations(node, staticProperties);
emitDecoratorsOfClass(node);
emitDecoratorsOfClass(node, decoratedClassAlias);
}
if (!(node.flags & NodeFlags.Export)) {
@@ -5255,7 +5408,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
emitMemberFunctionsForES5AndLower(node);
emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true));
writeLine();
emitDecoratorsOfClass(node);
emitDecoratorsOfClass(node, /*decoratedClassAlias*/ undefined);
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end, () => {
write("return ");
@@ -5297,13 +5450,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
function emitDecoratorsOfClass(node: ClassLikeDeclaration) {
function emitDecoratorsOfClass(node: ClassLikeDeclaration, decoratedClassAlias: string) {
emitDecoratorsOfMembers(node, /*staticFlag*/ 0);
emitDecoratorsOfMembers(node, NodeFlags.Static);
emitDecoratorsOfConstructor(node);
emitDecoratorsOfConstructor(node, decoratedClassAlias);
}
function emitDecoratorsOfConstructor(node: ClassLikeDeclaration) {
function emitDecoratorsOfConstructor(node: ClassLikeDeclaration, decoratedClassAlias: string) {
const decorators = node.decorators;
const constructor = getFirstConstructorWithBody(node);
const firstParameterDecorator = constructor && forEach(constructor.parameters, parameter => parameter.decorators);
@@ -5327,6 +5480,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
writeLine();
emitStart(node.decorators || firstParameterDecorator);
emitDeclarationName(node);
if (decoratedClassAlias !== undefined) {
write(` = ${decoratedClassAlias}`);
}
write(" = __decorate([");
increaseIndent();
writeLine();
@@ -6100,6 +6257,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (contains(externalImports, node)) {
const isExportedImport = node.kind === SyntaxKind.ImportEqualsDeclaration && (node.flags & NodeFlags.Export) !== 0;
const namespaceDeclaration = getNamespaceDeclarationNode(node);
const varOrConst = (languageVersion <= ScriptTarget.ES5) ? "var " : "const ";
if (modulekind !== ModuleKind.AMD) {
emitLeadingComments(node);
@@ -6107,7 +6265,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (namespaceDeclaration && !isDefaultImport(node)) {
// import x = require("foo")
// import * as x from "foo"
if (!isExportedImport) write("var ");
if (!isExportedImport) {
write(varOrConst);
};
emitModuleMemberName(namespaceDeclaration);
write(" = ");
}
@@ -6119,7 +6279,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// import d, { x, y } from "foo"
const isNakedImport = SyntaxKind.ImportDeclaration && !(<ImportDeclaration>node).importClause;
if (!isNakedImport) {
write("var ");
write(varOrConst);
write(getGeneratedNameForNode(<ImportDeclaration>node));
write(" = ");
}
@@ -6146,7 +6306,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
else if (namespaceDeclaration && isDefaultImport(node)) {
// import d, * as x from "foo"
write("var ");
write(varOrConst);
emitModuleMemberName(namespaceDeclaration);
write(" = ");
write(getGeneratedNameForNode(<ImportDeclaration>node));
@@ -6980,6 +7140,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
Debug.assert(!exportFunctionForFile);
// make sure that name of 'exports' function does not conflict with existing identifiers
exportFunctionForFile = makeUniqueName("exports");
contextObjectForFile = makeUniqueName("context");
writeLine();
write("System.register(");
writeModuleName(node, emitRelativePathAsModuleName);
@@ -6990,14 +7151,22 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
for (let i = 0; i < externalImports.length; i++) {
const text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName);
if (hasProperty(groupIndices, text)) {
if (text === undefined) {
continue;
}
// text should be quoted string
// for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same
const key = text.substr(1, text.length - 2);
if (hasProperty(groupIndices, key)) {
// deduplicate/group entries in dependency list by the dependency name
const groupIndex = groupIndices[text];
const groupIndex = groupIndices[key];
dependencyGroups[groupIndex].push(externalImports[i]);
continue;
}
else {
groupIndices[text] = dependencyGroups.length;
groupIndices[key] = dependencyGroups.length;
dependencyGroups.push([externalImports[i]]);
}
@@ -7007,10 +7176,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write(text);
}
write(`], function(${exportFunctionForFile}) {`);
write(`], function(${exportFunctionForFile}, ${contextObjectForFile}) {`);
writeLine();
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
writeLine();
write(`var __moduleName = ${contextObjectForFile} && ${contextObjectForFile}.id;`);
writeLine();
emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitSystemModuleBody(node, dependencyGroups, startIndex);
@@ -7251,7 +7423,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return result;
}
function getTextToEmit(node: JsxText) {
function isJsxChildEmittable(child: JsxChild): boolean {
if (child.kind === SyntaxKind.JsxExpression) {
// Don't emit empty expressions
return !!(<JsxExpression>child).expression;
}
else if (child.kind === SyntaxKind.JsxText) {
// Don't emit empty strings
return !!getTextToEmit(<JsxText>child);
}
return true;
};
function getTextToEmit(node: JsxText): string {
switch (compilerOptions.jsx) {
case JsxEmit.React:
let text = trimReactWhitespaceAndApplyEntities(node);
+85 -116
View File
@@ -438,7 +438,7 @@ namespace ts {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
const disallowInAndDecoratorContext = ParserContextFlags.DisallowIn | ParserContextFlags.Decorator;
const disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext;
// capture constructors in 'initializeState' to avoid null checks
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
@@ -502,7 +502,7 @@ namespace ts {
// Note: it should not be necessary to save/restore these flags during speculative/lookahead
// parsing. These context flags are naturally stored and restored through normal recursive
// descent parsing and unwinding.
let contextFlags: ParserContextFlags;
let contextFlags: NodeFlags;
// Whether or not we've had a parse error since creating the last AST node. If we have
// encountered an error, it will be stored on the next AST node we create. Parse errors
@@ -546,7 +546,7 @@ namespace ts {
function getLanguageVariant(fileName: string) {
// .tsx and .jsx files are treated as jsx language variant.
return fileExtensionIs(fileName, ".tsx") || fileExtensionIs(fileName, ".jsx") ? LanguageVariant.JSX : LanguageVariant.Standard;
return fileExtensionIs(fileName, ".tsx") || fileExtensionIs(fileName, ".jsx") || fileExtensionIs(fileName, ".js") ? LanguageVariant.JSX : LanguageVariant.Standard;
}
function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, isJavaScriptFile: boolean, _syntaxCursor: IncrementalParser.SyntaxCursor) {
@@ -562,7 +562,7 @@ namespace ts {
identifierCount = 0;
nodeCount = 0;
contextFlags = isJavaScriptFile ? ParserContextFlags.JavaScriptFile : ParserContextFlags.None;
contextFlags = isJavaScriptFile ? NodeFlags.JavaScriptFile : NodeFlags.None;
parseErrorBeforeNextFinishedNode = false;
// Initialize and prime the scanner before parsing the source elements.
@@ -587,10 +587,7 @@ namespace ts {
function parseSourceFileWorker(fileName: string, languageVersion: ScriptTarget, setParentNodes: boolean): SourceFile {
sourceFile = createSourceFile(fileName, languageVersion);
if (contextFlags & ParserContextFlags.JavaScriptFile) {
sourceFile.parserContextFlags = ParserContextFlags.JavaScriptFile;
}
sourceFile.flags = contextFlags;
// Prime the scanner.
token = nextToken();
@@ -616,7 +613,7 @@ namespace ts {
function addJSDocComment<T extends Node>(node: T): T {
if (contextFlags & ParserContextFlags.JavaScriptFile) {
if (contextFlags & NodeFlags.JavaScriptFile) {
const comments = getLeadingCommentRangesOfNode(node, sourceFile);
if (comments) {
for (const comment of comments) {
@@ -666,13 +663,13 @@ namespace ts {
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = normalizePath(fileName);
sourceFile.flags = fileExtensionIs(sourceFile.fileName, ".d.ts") ? NodeFlags.DeclarationFile : 0;
sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName);
sourceFile.isDeclarationFile = fileExtensionIs(sourceFile.fileName, ".d.ts");
return sourceFile;
}
function setContextFlag(val: boolean, flag: ParserContextFlags) {
function setContextFlag(val: boolean, flag: NodeFlags) {
if (val) {
contextFlags |= flag;
}
@@ -682,22 +679,22 @@ namespace ts {
}
function setDisallowInContext(val: boolean) {
setContextFlag(val, ParserContextFlags.DisallowIn);
setContextFlag(val, NodeFlags.DisallowInContext);
}
function setYieldContext(val: boolean) {
setContextFlag(val, ParserContextFlags.Yield);
setContextFlag(val, NodeFlags.YieldContext);
}
function setDecoratorContext(val: boolean) {
setContextFlag(val, ParserContextFlags.Decorator);
setContextFlag(val, NodeFlags.DecoratorContext);
}
function setAwaitContext(val: boolean) {
setContextFlag(val, ParserContextFlags.Await);
setContextFlag(val, NodeFlags.AwaitContext);
}
function doOutsideOfContext<T>(context: ParserContextFlags, func: () => T): T {
function doOutsideOfContext<T>(context: NodeFlags, func: () => T): T {
// contextFlagsToClear will contain only the context flags that are
// currently set that we need to temporarily clear
// We don't just blindly reset to the previous flags to ensure
@@ -718,7 +715,7 @@ namespace ts {
return func();
}
function doInsideOfContext<T>(context: ParserContextFlags, func: () => T): T {
function doInsideOfContext<T>(context: NodeFlags, func: () => T): T {
// contextFlagsToSet will contain only the context flags that
// are not currently set that we need to temporarily enable.
// We don't just blindly reset to the previous flags to ensure
@@ -740,51 +737,51 @@ namespace ts {
}
function allowInAnd<T>(func: () => T): T {
return doOutsideOfContext(ParserContextFlags.DisallowIn, func);
return doOutsideOfContext(NodeFlags.DisallowInContext, func);
}
function disallowInAnd<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.DisallowIn, func);
return doInsideOfContext(NodeFlags.DisallowInContext, func);
}
function doInYieldContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Yield, func);
return doInsideOfContext(NodeFlags.YieldContext, func);
}
function doInDecoratorContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Decorator, func);
return doInsideOfContext(NodeFlags.DecoratorContext, func);
}
function doInAwaitContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Await, func);
return doInsideOfContext(NodeFlags.AwaitContext, func);
}
function doOutsideOfAwaitContext<T>(func: () => T): T {
return doOutsideOfContext(ParserContextFlags.Await, func);
return doOutsideOfContext(NodeFlags.AwaitContext, func);
}
function doInYieldAndAwaitContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Yield | ParserContextFlags.Await, func);
return doInsideOfContext(NodeFlags.YieldContext | NodeFlags.AwaitContext, func);
}
function inContext(flags: ParserContextFlags) {
function inContext(flags: NodeFlags) {
return (contextFlags & flags) !== 0;
}
function inYieldContext() {
return inContext(ParserContextFlags.Yield);
return inContext(NodeFlags.YieldContext);
}
function inDisallowInContext() {
return inContext(ParserContextFlags.DisallowIn);
return inContext(NodeFlags.DisallowInContext);
}
function inDecoratorContext() {
return inContext(ParserContextFlags.Decorator);
return inContext(NodeFlags.DecoratorContext);
}
function inAwaitContext() {
return inContext(ParserContextFlags.Await);
return inContext(NodeFlags.AwaitContext);
}
function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void {
@@ -996,7 +993,7 @@ namespace ts {
node.end = end === undefined ? scanner.getStartPos() : end;
if (contextFlags) {
node.parserContextFlags = contextFlags;
node.flags |= contextFlags;
}
// Keep track on the node if we encountered an error while parsing it. If we did, then
@@ -1004,7 +1001,7 @@ namespace ts {
// flag so that we don't mark any subsequent nodes.
if (parseErrorBeforeNextFinishedNode) {
parseErrorBeforeNextFinishedNode = false;
node.parserContextFlags |= ParserContextFlags.ThisNodeHasError;
node.flags |= NodeFlags.ThisNodeHasError;
}
return node;
@@ -1172,7 +1169,7 @@ namespace ts {
case ParsingContext.SwitchClauses:
return token === SyntaxKind.CaseKeyword || token === SyntaxKind.DefaultKeyword;
case ParsingContext.TypeMembers:
return isStartOfTypeMember();
return lookAhead(isTypeMemberStart);
case ParsingContext.ClassMembers:
// We allow semicolons as class elements (as specified by ES6) as long as we're
// not in error recovery. If we're in error recovery, we don't want an errant
@@ -1453,7 +1450,7 @@ namespace ts {
// differently depending on what mode it is in.
//
// This also applies to all our other context flags as well.
const nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags;
const nodeContextFlags = node.flags & NodeFlags.ContextFlags;
if (nodeContextFlags !== contextFlags) {
return undefined;
}
@@ -1922,7 +1919,7 @@ namespace ts {
&& sourceText.charCodeAt(tokenPos) === CharacterCodes._0
&& isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) {
node.flags |= NodeFlags.OctalLiteral;
node.isOctalLiteral = true;
}
return node;
@@ -2214,13 +2211,13 @@ namespace ts {
return finishNode(node);
}
function parsePropertyOrMethodSignature(): PropertySignature | MethodSignature {
const fullStart = scanner.getStartPos();
function parsePropertyOrMethodSignature(fullStart: number, modifiers: ModifiersArray): PropertySignature | MethodSignature {
const name = parsePropertyName();
const questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
const method = <MethodSignature>createNode(SyntaxKind.MethodSignature, fullStart);
setModifiers(method, modifiers);
method.name = name;
method.questionToken = questionToken;
@@ -2232,6 +2229,7 @@ namespace ts {
}
else {
const property = <PropertySignature>createNode(SyntaxKind.PropertySignature, fullStart);
setModifiers(property, modifiers);
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
@@ -2248,86 +2246,51 @@ namespace ts {
}
}
function isStartOfTypeMember(): boolean {
switch (token) {
case SyntaxKind.OpenParenToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.OpenBracketToken: // Both for indexers and computed properties
return true;
default:
if (isModifierKind(token)) {
const result = lookAhead(isStartOfIndexSignatureDeclaration);
if (result) {
return result;
}
}
return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName);
function isTypeMemberStart(): boolean {
let idToken: SyntaxKind;
// Return true if we have the start of a signature member
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
return true;
}
}
function isStartOfIndexSignatureDeclaration() {
// Eat up all modifiers, but hold on to the last one in case it is actually an identifier
while (isModifierKind(token)) {
idToken = token;
nextToken();
}
return isIndexSignature();
}
function isTypeMemberWithLiteralPropertyName() {
nextToken();
return token === SyntaxKind.OpenParenToken ||
token === SyntaxKind.LessThanToken ||
token === SyntaxKind.QuestionToken ||
token === SyntaxKind.ColonToken ||
canParseSemicolon();
// Index signatures and computed property names are type members
if (token === SyntaxKind.OpenBracketToken) {
return true;
}
// Try to get the first property-like token following all modifiers
if (isLiteralPropertyName()) {
idToken = token;
nextToken();
}
// If we were able to get any potential identifier, check that it is
// the start of a member declaration
if (idToken) {
return token === SyntaxKind.OpenParenToken ||
token === SyntaxKind.LessThanToken ||
token === SyntaxKind.QuestionToken ||
token === SyntaxKind.ColonToken ||
canParseSemicolon();
}
return false;
}
function parseTypeMember(): TypeElement {
switch (token) {
case SyntaxKind.OpenParenToken:
case SyntaxKind.LessThanToken:
return parseSignatureMember(SyntaxKind.CallSignature);
case SyntaxKind.OpenBracketToken:
// Indexer or computed property
return isIndexSignature()
? parseIndexSignatureDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined)
: parsePropertyOrMethodSignature();
case SyntaxKind.NewKeyword:
if (lookAhead(isStartOfConstructSignature)) {
return parseSignatureMember(SyntaxKind.ConstructSignature);
}
// fall through.
case SyntaxKind.StringLiteral:
case SyntaxKind.NumericLiteral:
return parsePropertyOrMethodSignature();
default:
// Index declaration as allowed as a type member. But as per the grammar,
// they also allow modifiers. So we have to check for an index declaration
// that might be following modifiers. This ensures that things work properly
// when incrementally parsing as the parser will produce the Index declaration
// if it has the same text regardless of whether it is inside a class or an
// object type.
if (isModifierKind(token)) {
const result = tryParse(parseIndexSignatureWithModifiers);
if (result) {
return result;
}
}
if (tokenIsIdentifierOrKeyword(token)) {
return parsePropertyOrMethodSignature();
}
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
return parseSignatureMember(SyntaxKind.CallSignature);
}
}
function parseIndexSignatureWithModifiers() {
const fullStart = scanner.getStartPos();
const decorators = parseDecorators();
if (token === SyntaxKind.NewKeyword && lookAhead(isStartOfConstructSignature)) {
return parseSignatureMember(SyntaxKind.ConstructSignature);
}
const fullStart = getNodePos();
const modifiers = parseModifiers();
return isIndexSignature()
? parseIndexSignatureDeclaration(fullStart, decorators, modifiers)
: undefined;
if (isIndexSignature()) {
return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers);
}
return parsePropertyOrMethodSignature(fullStart, modifiers);
}
function isStartOfConstructSignature() {
@@ -2546,7 +2509,7 @@ namespace ts {
function parseType(): TypeNode {
// The rules about 'yield' only apply to actual code/expression contexts. They don't
// apply to 'type' contexts. So we disable these parameters here before moving on.
return doOutsideOfContext(ParserContextFlags.TypeExcludesFlags, parseTypeWorker);
return doOutsideOfContext(NodeFlags.TypeExcludesFlags, parseTypeWorker);
}
function parseTypeWorker(): TypeNode {
@@ -3941,7 +3904,9 @@ namespace ts {
function parseArrayLiteralExpression(): ArrayLiteralExpression {
const node = <ArrayLiteralExpression>createNode(SyntaxKind.ArrayLiteralExpression);
parseExpected(SyntaxKind.OpenBracketToken);
if (scanner.hasPrecedingLineBreak()) node.flags |= NodeFlags.MultiLine;
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
}
node.elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement);
parseExpected(SyntaxKind.CloseBracketToken);
return finishNode(node);
@@ -4012,7 +3977,7 @@ namespace ts {
const node = <ObjectLiteralExpression>createNode(SyntaxKind.ObjectLiteralExpression);
parseExpected(SyntaxKind.OpenBraceToken);
if (scanner.hasPrecedingLineBreak()) {
node.flags |= NodeFlags.MultiLine;
node.multiLine = true;
}
node.properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true);
@@ -4051,7 +4016,7 @@ namespace ts {
setDecoratorContext(/*val*/ true);
}
return finishNode(node);
return addJSDocComment(finishNode(node));
}
function parseOptionalIdentifier() {
@@ -4335,13 +4300,13 @@ namespace ts {
const labeledStatement = <LabeledStatement>createNode(SyntaxKind.LabeledStatement, fullStart);
labeledStatement.label = <Identifier>expression;
labeledStatement.statement = parseStatement();
return finishNode(labeledStatement);
return addJSDocComment(finishNode(labeledStatement));
}
else {
const expressionStatement = <ExpressionStatement>createNode(SyntaxKind.ExpressionStatement, fullStart);
expressionStatement.expression = expression;
parseSemicolon();
return finishNode(expressionStatement);
return addJSDocComment(finishNode(expressionStatement));
}
}
@@ -4404,6 +4369,7 @@ namespace ts {
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.ReadonlyKeyword:
nextToken();
// ASI takes effect for this modifier.
if (scanner.hasPrecedingLineBreak()) {
@@ -4486,6 +4452,7 @@ namespace ts {
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ReadonlyKeyword:
// When these don't start a declaration, they may be the start of a class member if an identifier
// immediately follows. Otherwise they're an identifier in an expression statement.
return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
@@ -4567,6 +4534,7 @@ namespace ts {
case SyntaxKind.PublicKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.GlobalKeyword:
if (isStartOfDeclaration()) {
return parseDeclaration();
@@ -4778,7 +4746,7 @@ namespace ts {
parseExpected(SyntaxKind.ConstructorKeyword);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, Diagnostics.or_expected);
return finishNode(node);
return addJSDocComment(finishNode(node));
}
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
@@ -4792,7 +4760,7 @@ namespace ts {
const isAsync = !!(method.flags & NodeFlags.Async);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method);
method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage);
return finishNode(method);
return addJSDocComment(finishNode(method));
}
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, name: PropertyName, questionToken: Node): ClassElement {
@@ -4814,7 +4782,7 @@ namespace ts {
// The checker may still error in the static case to explicitly disallow the yield expression.
property.initializer = modifiers && modifiers.flags & NodeFlags.Static
? allowInAnd(parseNonParameterInitializer)
: doOutsideOfContext(ParserContextFlags.Yield | ParserContextFlags.DisallowIn, parseNonParameterInitializer);
: doOutsideOfContext(NodeFlags.YieldContext | NodeFlags.DisallowInContext, parseNonParameterInitializer);
parseSemicolon();
return finishNode(property);
@@ -4855,6 +4823,7 @@ namespace ts {
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ReadonlyKeyword:
return true;
default:
return false;
+452 -87
View File
@@ -12,7 +12,7 @@ namespace ts {
const emptyArray: any[] = [];
export const version = "1.8.0";
export const version = "1.9.0";
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
let fileName = "tsconfig.json";
@@ -36,37 +36,374 @@ namespace ts {
return normalizePath(referencedFileName);
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const moduleResolution = compilerOptions.moduleResolution !== undefined
? compilerOptions.moduleResolution
: compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void {
host.trace(formatMessage.apply(undefined, arguments));
}
function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
return compilerOptions.traceModuleResolution && host.trace !== undefined;
}
function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false;
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === CharacterCodes.asterisk) {
if (!seenAsterisk) {
seenAsterisk = true;
}
else {
// have already seen asterisk
return false;
}
}
}
return true;
}
function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations {
return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName: string): boolean {
if (isRootedDiskPath(moduleName)) {
return false;
}
const i = moduleName.lastIndexOf("./", 1);
const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot);
return !startsWithDotSlashOrDotDotSlash;
}
interface ModuleResolutionState {
host: ModuleResolutionHost;
compilerOptions: CompilerOptions;
traceEnabled: boolean;
// skip .tsx files if jsx is not enabled
skipTsx: boolean;
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
}
let moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
if (traceEnabled) {
trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]);
}
}
let result: ResolvedModuleWithFailedLookupLocations;
switch (moduleResolution) {
case ModuleResolutionKind.NodeJs: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
case ModuleResolutionKind.Classic: return classicNameResolver(moduleName, containingFile, compilerOptions, host);
case ModuleResolutionKind.NodeJs:
result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
break;
case ModuleResolutionKind.Classic:
result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
break;
}
if (traceEnabled) {
if (result.resolvedModule) {
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
}
else {
trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
}
}
return result;
}
/*
* Every module resolution kind can has its specific understanding how to load module from a specific path on disk
* I.e. for path '/a/b/c':
* - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails
* it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with
* 'typings' entry or file 'index' with some supported extension
* - Classic loader will only try to interpret '/a/b/c' as file.
*/
type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFalures: boolean, state: ModuleResolutionState) => string;
/**
* Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
* mitigate differences between design time structure of the project and its runtime counterpart so the same import name
* can be resolved successfully by TypeScript compiler and runtime module loader.
* If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
* fallback to standard resolution routine.
*
* - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
* names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then canditate location to resolve module name 'c/d' will
* be '/a/b/c/d'
* - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
* will be resolved based on the content of the module name.
* Structure of 'paths' compiler options
* 'paths': {
* pattern-1: [...substitutions],
* pattern-2: [...substitutions],
* ...
* pattern-n: [...substitutions]
* }
* Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
* all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
* If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
* <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
* If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
* After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
* from the candidate location.
* Substitiution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
* substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
* will be converted to absolute using baseUrl.
* For example:
* baseUrl: /a/b/c
* "paths": {
* // match all module names
* "*": [
* "*", // use matched name as is,
* // <matched name> will be looked as /a/b/c/<matched name>
*
* "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
* // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
* ],
* // match module names that start with 'components/'
* "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
* // it is rooted so it will be final candidate location
* }
*
* 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
* they were in the same location. For example lets say there are two files
* '/local/src/content/file1.ts'
* '/shared/components/contracts/src/content/protocols/file2.ts'
* After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
* if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
* 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
* root dirs were merged together.
* I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
* Compiler wil first convert './protocols/file2' into absolute path relative to the location of containing file:
* '/local/src/content/protocols/file2' and try to load it - failure.
* Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
* be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remainining
* entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
*/
function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string {
if (moduleHasNonRelativeName(moduleName)) {
return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
}
else {
return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
}
}
function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string {
if (!state.compilerOptions.rootDirs) {
return undefined;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
}
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let matchedRootDir: string;
let matchedNormalizedPrefix: string;
for (const rootDir of state.compilerOptions.rootDirs) {
// rootDirs are expected to be absolute
// in case of tsconfig.json this will happen automatically - compiler will expand relative names
// using locaton of tsconfig.json as base location
let normalizedRoot = normalizePath(rootDir);
if (!endsWith(normalizedRoot, directorySeparator)) {
normalizedRoot += directorySeparator;
}
const isLongestMatchingPrefix =
startsWith(candidate, normalizedRoot) &&
(matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
if (state.traceEnabled) {
trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
}
if (isLongestMatchingPrefix) {
matchedNormalizedPrefix = normalizedRoot;
matchedRootDir = rootDir;
}
}
if (matchedNormalizedPrefix) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
}
const suffix = candidate.substr(matchedNormalizedPrefix.length);
// first - try to load from a initial location
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
}
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs);
}
// then try to resolve using remaining entries in rootDirs
for (const rootDir of state.compilerOptions.rootDirs) {
if (rootDir === matchedRootDir) {
// skip the initially matched entry
continue;
}
const candidate = combinePaths(normalizePath(rootDir), suffix);
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate);
}
const baseDirectory = getDirectoryPath(candidate);
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed);
}
}
return undefined;
}
function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[],
supportedExtensions: string[], state: ModuleResolutionState): string {
if (!state.compilerOptions.baseUrl) {
return undefined;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
let longestMatchPrefixLength = -1;
let matchedPattern: string;
let matchedStar: string;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
for (const key in state.compilerOptions.paths) {
const pattern: string = key;
const indexOfStar = pattern.indexOf("*");
if (indexOfStar !== -1) {
const prefix = pattern.substr(0, indexOfStar);
const suffix = pattern.substr(indexOfStar + 1);
if (moduleName.length >= prefix.length + suffix.length &&
startsWith(moduleName, prefix) &&
endsWith(moduleName, suffix)) {
// use length of prefix as betterness criteria
if (prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = prefix.length;
matchedPattern = pattern;
matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length);
}
}
}
else if (pattern === moduleName) {
// pattern was matched as is - no need to seatch further
matchedPattern = pattern;
matchedStar = undefined;
break;
}
}
}
if (matchedPattern) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern);
}
for (const subst of state.compilerOptions.paths[matchedPattern]) {
const path = matchedStar ? subst.replace("\*", matchedStar) : subst;
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
}
return undefined;
}
else {
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
}
return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
}
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const containingDirectory = getDirectoryPath(containingFile);
const supportedExtensions = getSupportedExtensions(compilerOptions);
if (getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
const failedLookupLocations: string[] = [];
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host);
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName }, failedLookupLocations };
const failedLookupLocations: string[] = [];
const state = {compilerOptions, host, traceEnabled, skipTsx: false};
let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName,
failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
}
let isExternalLibraryImport = false;
if (moduleHasNonRelativeName(moduleName)) {
if (traceEnabled) {
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
}
resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
isExternalLibraryImport = resolvedFileName !== undefined;
}
else {
return loadModuleFromNodeModules(moduleName, containingDirectory, host);
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
}
function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[],
onlyRecordFailures: boolean, state: ModuleResolutionState): string {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
}
const resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
}
/* @internal */
@@ -77,73 +414,99 @@ namespace ts {
/**
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadNodeModuleFromFile(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, host: ModuleResolutionHost): string {
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
return forEach(extensions, tryLoad);
function tryLoad(ext: string): string {
if (ext === ".tsx" && state.skipTsx) {
return undefined;
}
const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (!onlyRecordFailures && host.fileExists(fileName)) {
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName);
}
return fileName;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
}
failedLookupLocation.push(fileName);
return undefined;
}
}
}
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, host: ModuleResolutionHost): string {
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
const packageJsonPath = combinePaths(candidate, "package.json");
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, host);
if (directoryExists && host.fileExists(packageJsonPath)) {
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
let jsonContent: { typings?: string };
try {
const jsonText = host.readFile(packageJsonPath);
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined };
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (typeof jsonContent.typings === "string") {
const path = normalizePath(combinePaths(candidate, jsonContent.typings));
const result = loadNodeModuleFromFile(extensions, path, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(path), host), host);
if (result) {
return result;
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile);
}
const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state);
if (result) {
return result;
}
}
else if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings);
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_typings_field);
}
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
}
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
}
return loadNodeModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, host);
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
}
function loadModuleFromNodeModules(moduleName: string, directory: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const failedLookupLocations: string[] = [];
function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
directory = normalizeSlashes(directory);
while (true) {
const baseName = getBaseFileName(directory);
if (baseName !== "node_modules") {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, host);
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
// Load only typescript files irrespective of allowJs option if loading from node modules
let result = loadNodeModuleFromFile(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host);
let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
return result;
}
result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host);
result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
return result;
}
}
@@ -154,56 +517,33 @@ namespace ts {
directory = parentPath;
}
return { resolvedModule: undefined, failedLookupLocations };
}
function nameStartsWithDotSlashOrDotDotSlash(name: string) {
const i = name.lastIndexOf("./", 1);
return i === 0 || (i === 1 && name.charCodeAt(0) === CharacterCodes.dot);
return undefined;
}
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx };
const failedLookupLocations: string[] = [];
const supportedExtensions = getSupportedExtensions(compilerOptions);
let containingDirectory = getDirectoryPath(containingFile);
// module names that contain '!' are used to reference resources and are not resolved to actual files on disk
if (moduleName.indexOf("!") != -1) {
return { resolvedModule: undefined, failedLookupLocations: [] };
const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
}
let searchPath = getDirectoryPath(containingFile);
let searchName: string;
const failedLookupLocations: string[] = [];
let referencedSourceFile: string;
const supportedExtensions = getSupportedExtensions(compilerOptions);
while (true) {
searchName = normalizePath(combinePaths(searchPath, moduleName));
referencedSourceFile = forEach(supportedExtensions, extension => {
if (extension === ".tsx" && !compilerOptions.jsx) {
// resolve .tsx files only if jsx support is enabled
// 'logical not' handles both undefined and None cases
return undefined;
}
const candidate = searchName + extension;
if (host.fileExists(candidate)) {
return candidate;
}
else {
failedLookupLocations.push(candidate);
}
});
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
break;
}
const parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
searchPath = parentPath;
containingDirectory = parentPath;
}
return referencedSourceFile
@@ -295,6 +635,7 @@ namespace ts {
getNewLine: () => newLine,
fileExists: fileName => sys.fileExists(fileName),
readFile: fileName => sys.readFile(fileName),
trace: (s: string) => sys.write(s + newLine),
directoryExists: directoryName => sys.directoryExists(directoryName)
};
}
@@ -382,7 +723,7 @@ namespace ts {
const filesByName = createFileMap<SourceFile>();
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
// used to track cases when two file names differ only in casing
const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined;
if (oldProgram) {
@@ -734,8 +1075,11 @@ namespace ts {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ExportAssignment:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file));
return true;
if ((<ExportAssignment>node).isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.ClassDeclaration:
let classDeclaration = <ClassDeclaration>node;
if (checkModifiers(classDeclaration.modifiers) ||
@@ -857,6 +1201,7 @@ namespace ts {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.DeclareKeyword:
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
return true;
@@ -957,7 +1302,7 @@ namespace ts {
}
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
// An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
if (!inAmbientModule || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) {
(imports || (imports = [])).push(<LiteralExpression>moduleNameExpr);
@@ -975,7 +1320,7 @@ namespace ts {
(moduleAugmentations || (moduleAugmentations = [])).push(moduleName);
}
else if (!inAmbientModule) {
// An AmbientExternalModuleDeclaration declares an external module.
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
@@ -990,7 +1335,7 @@ namespace ts {
}
function collectRequireCalls(node: Node): void {
if (isRequireCall(node)) {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) {
(imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]);
}
else {
@@ -1145,7 +1490,7 @@ namespace ts {
if (importedFile && resolution.isExternalLibraryImport) {
// Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files,
// this check is ok. Otherwise this would be never true for javascript file
if (!isExternalModule(importedFile)) {
if (!isExternalModule(importedFile) && importedFile.statements.length) {
const start = getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
}
@@ -1259,6 +1604,26 @@ namespace ts {
}
}
if (options.paths && options.baseUrl === undefined) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option));
}
if (options.paths) {
for (const key in options.paths) {
if (!hasProperty(options.paths, key)) {
continue;
}
if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
for (const subst of options.paths[key]) {
if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
}
}
if (options.inlineSources) {
if (!options.sourceMap && !options.inlineSourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
@@ -1355,11 +1720,11 @@ namespace ts {
}
if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
}
// If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
if (!options.noEmit) {
if (!options.noEmit && !options.suppressOutputPathCheck) {
const emitHost = getEmitHost();
const emitFilesSeen = createFileMap<boolean>(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined);
forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => {
+1
View File
@@ -98,6 +98,7 @@ namespace ts {
"private": SyntaxKind.PrivateKeyword,
"protected": SyntaxKind.ProtectedKeyword,
"public": SyntaxKind.PublicKeyword,
"readonly": SyntaxKind.ReadonlyKeyword,
"require": SyntaxKind.RequireKeyword,
"global": SyntaxKind.GlobalKeyword,
"return": SyntaxKind.ReturnKeyword,
+13 -9
View File
@@ -16,6 +16,14 @@ namespace ts {
}
let nullSourceMapWriter: SourceMapWriter;
// Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans
const defaultLastEncodedSourceMapSpan: SourceMapSpan = {
emittedLine: 1,
emittedColumn: 1,
sourceLine: 1,
sourceColumn: 1,
sourceIndex: 0
};
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
@@ -79,13 +87,7 @@ namespace ts {
// Last recorded and encoded spans
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = {
emittedLine: 1,
emittedColumn: 1,
sourceLine: 1,
sourceColumn: 1,
sourceIndex: 0
};
lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan;
lastEncodedNameIndex = 0;
// Initialize source map data
@@ -159,10 +161,12 @@ namespace ts {
// Pop sourceMapDecodedMappings to remove last entry
sourceMapData.sourceMapDecodedMappings.pop();
// Change the last encoded source map
// Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan
// If the list is empty which indicates that we are at the beginning of the file,
// we have to reset it to default value (same value when we first initialize sourceMapWriter)
lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ?
sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] :
undefined;
defaultLastEncodedSourceMapSpan;
// TODO: Update lastEncodedNameIndex
// Since we dont support this any more, lets not worry about it right now.
-3
View File
@@ -373,9 +373,6 @@ namespace ts {
}
}
/**
* @param watcherPath is the path from which the watcher is triggered.
*/
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: Path) {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
const filePath = typeof relativeFileName !== "string"
+4 -2
View File
@@ -376,7 +376,7 @@ namespace ts {
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
const configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName), commandLine.options);
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options);
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -740,7 +740,9 @@ namespace ts {
for (const name in options) {
if (hasProperty(options, name)) {
const value = options[name];
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
const value = <string | number | boolean>options[name];
switch (name) {
case "init":
case "watch":
+96 -95
View File
@@ -163,6 +163,7 @@ namespace ts {
IsKeyword,
ModuleKeyword,
NamespaceKeyword,
ReadonlyKeyword,
RequireKeyword,
NumberKeyword,
SetKeyword,
@@ -369,32 +370,37 @@ namespace ts {
}
export const enum NodeFlags {
None = 0,
Export = 1 << 1, // Declarations
Ambient = 1 << 2, // Declarations
Public = 1 << 3, // Property/Method
Private = 1 << 4, // Property/Method
Protected = 1 << 5, // Property/Method
Static = 1 << 6, // Property/Method
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
MultiLine = 1 << 10, // Multi-line array or object literal
Synthetic = 1 << 11, // Synthetic node (for full fidelity)
DeclarationFile = 1 << 12, // Node is a .d.ts file
Let = 1 << 13, // Variable declaration
Const = 1 << 14, // Variable declaration
OctalLiteral = 1 << 15, // Octal numeric literal
Namespace = 1 << 16, // Namespace declaration
ExportContext = 1 << 17, // Export context (initialized by binding)
ContainsThis = 1 << 18, // Interface contains references to "this"
HasImplicitReturn = 1 << 19, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 20, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 21, // Set if module declaration is an augmentation for the global scope
HasClassExtends = 1 << 22, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
HasDecorators = 1 << 23, // If the file has decorators (initialized by binding)
HasParamDecorators = 1 << 24, // If the file has parameter decorators (initialized by binding)
HasAsyncFunctions = 1 << 25, // If the file has async functions (initialized by binding)
None = 0,
Export = 1 << 0, // Declarations
Ambient = 1 << 1, // Declarations
Public = 1 << 2, // Property/Method
Private = 1 << 3, // Property/Method
Protected = 1 << 4, // Property/Method
Static = 1 << 5, // Property/Method
Readonly = 1 << 6, // Property/Method
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
Let = 1 << 10, // Variable declaration
Const = 1 << 11, // Variable declaration
Namespace = 1 << 12, // Namespace declaration
ExportContext = 1 << 13, // Export context (initialized by binding)
ContainsThis = 1 << 14, // Interface contains references to "this"
HasImplicitReturn = 1 << 15, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 16, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 17, // Set if module declaration is an augmentation for the global scope
HasClassExtends = 1 << 18, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
HasDecorators = 1 << 19, // If the file has decorators (initialized by binding)
HasParamDecorators = 1 << 20, // If the file has parameter decorators (initialized by binding)
HasAsyncFunctions = 1 << 21, // If the file has async functions (initialized by binding)
DisallowInContext = 1 << 22, // If node was parsed in a context where 'in-expressions' are not allowed
YieldContext = 1 << 23, // If node was parsed in the 'yield' context created when parsing a generator
DecoratorContext = 1 << 24, // If node was parsed as part of a decorator
AwaitContext = 1 << 25, // If node was parsed in the 'await' context created when parsing an async function
ThisNodeHasError = 1 << 26, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 27, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 28, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 29, // If we've computed data from children and cached it in this node
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async,
AccessibilityModifier = Public | Private | Protected,
@@ -402,47 +408,12 @@ namespace ts {
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions,
}
/* @internal */
export const enum ParserContextFlags {
None = 0,
// If this node was parsed in a context where 'in-expressions' are not allowed.
DisallowIn = 1 << 0,
// If this node was parsed in the 'yield' context created when parsing a generator.
Yield = 1 << 1,
// If this node was parsed as part of a decorator
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 << 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 << 5,
// Context flags set directly by the parser.
ParserGeneratedFlags = DisallowIn | Yield | Decorator | ThisNodeHasError | Await,
// Parsing context flags
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext,
// 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 << 6,
// Used to know if we've computed data from children and cached it in this node.
HasAggregatedChildData = 1 << 7
TypeExcludesFlags = YieldContext | AwaitContext,
}
export const enum JsxFlags {
@@ -470,9 +441,6 @@ namespace ts {
export interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
// Specific context the parser was in when this node was created. Normally undefined.
// Only set when the parser was in some interesting context (like async/yield).
/* @internal */ parserContextFlags?: ParserContextFlags;
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
modifiers?: ModifiersArray; // Array of modifiers
/* @internal */ id?: number; // Unique id (used to look up NodeLinks)
@@ -936,6 +904,8 @@ namespace ts {
text: string;
isUnterminated?: boolean;
hasExtendedUnicodeEscape?: boolean;
/* @internal */
isOctalLiteral?: boolean;
}
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
@@ -977,6 +947,8 @@ namespace ts {
// @kind(SyntaxKind.ArrayLiteralExpression)
export interface ArrayLiteralExpression extends PrimaryExpression {
elements: NodeArray<Expression>;
/* @internal */
multiLine?: boolean;
}
// @kind(SyntaxKind.SpreadElementExpression)
@@ -988,6 +960,8 @@ namespace ts {
// @kind(SyntaxKind.ObjectLiteralExpression)
export interface ObjectLiteralExpression extends PrimaryExpression, Declaration {
properties: NodeArray<ObjectLiteralElement>;
/* @internal */
multiLine?: boolean;
}
// @kind(SyntaxKind.PropertyAccessExpression)
@@ -1544,6 +1518,7 @@ namespace ts {
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
// this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
/* @internal */
@@ -1901,8 +1876,8 @@ namespace ts {
hasGlobalName(name: string): boolean;
getReferencedExportContainer(node: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration;
getReferencedImportDeclaration(node: Identifier): Declaration;
getReferencedNestedRedeclaration(node: Identifier): Declaration;
isNestedRedeclaration(node: Declaration): boolean;
getReferencedDeclarationWithCollidingName(node: Identifier): Declaration;
isDeclarationWithCollidingName(node: Declaration): boolean;
isValueAliasDeclaration(node: Node): boolean;
isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean;
isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean;
@@ -2038,7 +2013,7 @@ namespace ts {
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
isDeclaratonWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // true if module exports some value (not just types)
}
@@ -2052,20 +2027,23 @@ namespace ts {
/* @internal */
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
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 = 0x00002000,
BlockScopedBindingInLoop = 0x00004000,
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
LoopWithBlockScopedBindingCapturedInFunction = 0x00010000, // Loop that contains block scoped variable captured in closure
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
SuperInstance = 0x00000100, // Instance 'super' reference
SuperStatic = 0x00000200, // Static 'super' reference
ContextChecked = 0x00000400, // Contextual types have been assigned
AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'.
AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'.
CaptureArguments = 0x00002000, // Lexical 'arguments' used in body (for async functions)
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function
BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement
HasSeenSuperCall = 0x00080000, // Set during the binding when encounter 'super'
ClassWithBodyScopedClassBinding = 0x00100000, // Decorated class that contains a binding to itself inside of the class body.
BodyScopedClassBinding = 0x00200000, // Binding to a decorated class inside of the class's body.
}
/* @internal */
@@ -2074,6 +2052,7 @@ namespace ts {
resolvedAwaitedType?: Type; // Cached awaited type of type node
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
flags?: NodeCheckFlags; // Set of flags specific to Node
enumMemberValue?: number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
@@ -2181,8 +2160,8 @@ namespace ts {
declaredProperties: Symbol[]; // Declared members
declaredCallSignatures: Signature[]; // Declared call signatures
declaredConstructSignatures: Signature[]; // Declared construct signatures
declaredStringIndexType: Type; // Declared string index type
declaredNumberIndexType: Type; // Declared numeric index type
declaredStringIndexInfo: IndexInfo; // Declared string indexing info
declaredNumberIndexInfo: IndexInfo; // Declared numeric indexing info
}
// Type references (TypeFlags.Reference). When a class or interface has type parameters or
@@ -2234,8 +2213,8 @@ namespace ts {
properties: Symbol[]; // Properties
callSignatures: Signature[]; // Call signatures of type
constructSignatures: Signature[]; // Construct signatures of type
stringIndexType?: Type; // String index type
numberIndexType?: Type; // Numeric index type
stringIndexInfo?: IndexInfo; // String indexing info
numberIndexInfo?: IndexInfo; // Numeric indexing info
}
/* @internal */
@@ -2298,6 +2277,12 @@ namespace ts {
Number,
}
export interface IndexInfo {
type: Type;
isReadonly: boolean;
declaration?: SignatureDeclaration;
}
/* @internal */
export interface TypeMapper {
(t: TypeParameter): Type;
@@ -2374,11 +2359,15 @@ namespace ts {
Message,
}
export const enum ModuleResolutionKind {
export enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2
NodeJs = 2
}
export type RootPaths = string[];
export type PathSubstitutions = Map<string[]>;
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
export interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
@@ -2427,17 +2416,23 @@ namespace ts {
noImplicitReturns?: boolean;
noFallthroughCasesInSwitch?: boolean;
forceConsistentCasingInFileNames?: boolean;
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
/* @internal */ stripInternal?: boolean;
// Skip checking lib.d.ts to help speed up tests.
/* @internal */ skipDefaultLibCheck?: boolean;
// Do not perform validation of output file name in transpile scenarios
/* @internal */ suppressOutputPathCheck?: boolean;
[option: string]: string | number | boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
}
export const enum ModuleKind {
export enum ModuleKind {
None = 0,
CommonJS = 1,
AMD = 2,
@@ -2494,12 +2489,13 @@ namespace ts {
/* @internal */
export interface CommandLineOptionBase {
name: string;
type: "string" | "number" | "boolean" | Map<number>; // a value of a primitive type, or an object literal mapping named values to actual values
type: "string" | "number" | "boolean" | "object" | Map<number>; // a value of a primitive type, or an object literal mapping named values to actual values
isFilePath?: boolean; // True if option value is a path or fileName
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does
paramType?: DiagnosticMessage; // The name to be used for a non-boolean option's parameter
experimental?: boolean;
isTSConfigOnly?: boolean; // True if option can only be specified via tsconfig.json file
}
/* @internal */
@@ -2514,7 +2510,12 @@ namespace ts {
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType;
export interface TsConfigOnlyOption extends CommandLineOptionBase {
type: "object";
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption;
/* @internal */
export const enum CharacterCodes {
@@ -2658,7 +2659,7 @@ namespace ts {
// readFile function is used to read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json'
// to determine location of bundled typings for node module
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
}
+60 -16
View File
@@ -121,26 +121,26 @@ namespace ts {
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0;
return (node.flags & NodeFlags.ThisNodeOrAnySubNodesHasError) !== 0;
}
function aggregateChildData(node: Node): void {
if (!(node.parserContextFlags & ParserContextFlags.HasAggregatedChildData)) {
if (!(node.flags & NodeFlags.HasAggregatedChildData)) {
// A node is considered to contain a parse error if:
// a) the parser explicitly marked that it had an error
// b) any of it's children reported that it had an error.
const thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) ||
const thisNodeOrAnySubNodesHasError = ((node.flags & NodeFlags.ThisNodeHasError) !== 0) ||
forEachChild(node, containsParseError);
// If so, mark ourselves accordingly.
if (thisNodeOrAnySubNodesHasError) {
node.parserContextFlags |= ParserContextFlags.ThisNodeOrAnySubNodesHasError;
node.flags |= NodeFlags.ThisNodeOrAnySubNodesHasError;
}
// Also mark that we've propogated the child information to this node. This way we can
// always consult the bit directly on this node without needing to check its children
// again.
node.parserContextFlags |= ParserContextFlags.HasAggregatedChildData;
node.flags |= NodeFlags.HasAggregatedChildData;
}
}
@@ -151,6 +151,18 @@ namespace ts {
return <SourceFile>node;
}
export function isStatementWithLocals(node: Node) {
switch (node.kind) {
case SyntaxKind.Block:
case SyntaxKind.CaseBlock:
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
return true;
}
return false;
}
export function getStartPositionOfLine(line: number, sourceFile: SourceFile): number {
Debug.assert(line >= 0);
return getLineStarts(sourceFile)[line];
@@ -256,6 +268,13 @@ namespace ts {
((<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral || isGlobalScopeAugmentation(<ModuleDeclaration>node));
}
export function isBlockScopedContainerTopLevel(node: Node): boolean {
return node.kind === SyntaxKind.SourceFile ||
node.kind === SyntaxKind.ModuleDeclaration ||
isFunctionLike(node) ||
isFunctionBlock(node);
}
export function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean {
return !!(module.flags & NodeFlags.GlobalAugmentation);
}
@@ -395,7 +414,7 @@ namespace ts {
}
export function isDeclarationFile(file: SourceFile): boolean {
return (file.flags & NodeFlags.DeclarationFile) !== 0;
return file.isDeclarationFile;
}
export function isConstEnumDeclaration(node: Node): boolean {
@@ -850,6 +869,16 @@ namespace ts {
}
}
/**
* Determines whether a node is a property or element access expression for super.
*/
export function isSuperPropertyOrElementAccess(node: Node) {
return (node.kind === SyntaxKind.PropertyAccessExpression
|| node.kind === SyntaxKind.ElementAccessExpression)
&& (<PropertyAccessExpression | ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword;
}
export function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression {
if (node) {
switch (node.kind) {
@@ -1049,7 +1078,7 @@ namespace ts {
}
export function isInJavaScriptFile(node: Node): boolean {
return node && !!(node.parserContextFlags & ParserContextFlags.JavaScriptFile);
return node && !!(node.flags & NodeFlags.JavaScriptFile);
}
/**
@@ -1057,12 +1086,14 @@ namespace ts {
* exactly one argument.
* This function does not test if the node is in a JavaScript file or not.
*/
export function isRequireCall(expression: Node): expression is CallExpression {
export function isRequireCall(expression: Node, checkArgumentIsStringLiteral: boolean): expression is CallExpression {
// of the form 'require("name")'
return expression.kind === SyntaxKind.CallExpression &&
(<CallExpression>expression).expression.kind === SyntaxKind.Identifier &&
(<Identifier>(<CallExpression>expression).expression).text === "require" &&
(<CallExpression>expression).arguments.length === 1;
const isRequire = expression.kind === SyntaxKind.CallExpression &&
(<CallExpression>expression).expression.kind === SyntaxKind.Identifier &&
(<Identifier>(<CallExpression>expression).expression).text === "require" &&
(<CallExpression>expression).arguments.length === 1;
return isRequire && (!checkArgumentIsStringLiteral || (<CallExpression>expression).arguments[0].kind === SyntaxKind.StringLiteral);
}
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
@@ -1176,7 +1207,19 @@ namespace ts {
node.parent.parent.parent.kind === SyntaxKind.VariableStatement;
const variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined;
return variableStatementNode && variableStatementNode.jsDocComment;
if (variableStatementNode) {
return variableStatementNode.jsDocComment;
}
// Also recognize when the node is the RHS of an assignment expression
const isSourceOfAssignmentExpressionStatement =
node.parent && node.parent.parent &&
node.parent.kind === SyntaxKind.BinaryExpression &&
(node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken &&
node.parent.parent.kind === SyntaxKind.ExpressionStatement;
if (isSourceOfAssignmentExpressionStatement) {
return node.parent.parent.jsDocComment;
}
}
return undefined;
@@ -1223,7 +1266,7 @@ namespace ts {
export function isRestParameter(node: ParameterDeclaration) {
if (node) {
if (node.parserContextFlags & ParserContextFlags.JavaScriptFile) {
if (node.flags & NodeFlags.JavaScriptFile) {
if (node.type && node.type.kind === SyntaxKind.JSDocVariadicType) {
return true;
}
@@ -1266,10 +1309,9 @@ namespace ts {
export function isInAmbientContext(node: Node): boolean {
while (node) {
if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) {
if (node.flags & NodeFlags.Ambient || (node.kind === SyntaxKind.SourceFile && (node as SourceFile).isDeclarationFile)) {
return true;
}
node = node.parent;
}
return false;
@@ -1582,6 +1624,7 @@ namespace ts {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.StaticKeyword:
return true;
}
@@ -2313,6 +2356,7 @@ namespace ts {
case SyntaxKind.ConstKeyword: return NodeFlags.Const;
case SyntaxKind.DefaultKeyword: return NodeFlags.Default;
case SyntaxKind.AsyncKeyword: return NodeFlags.Async;
case SyntaxKind.ReadonlyKeyword: return NodeFlags.Readonly;
}
return 0;
}
+25 -4
View File
@@ -49,7 +49,6 @@ class CompilerBaselineRunner extends RunnerBase {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let justName: string;
let lastUnit: Harness.TestCaseParser.TestUnitData;
let harnessSettings: Harness.TestCaseParser.CompilerSettings;
let hasNonDtsFiles: boolean;
@@ -64,17 +63,31 @@ class CompilerBaselineRunner extends RunnerBase {
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ""); // strips the fileName from the path.
const content = Harness.IO.readFile(fileName);
const testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
const rootDir = fileName.indexOf("conformance") === -1 ? "tests/cases/compiler/" : ts.getDirectoryPath(fileName) + "/";
const testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName, rootDir);
const units = testCaseContent.testUnitData;
harnessSettings = testCaseContent.settings;
let tsConfigOptions: ts.CompilerOptions;
if (testCaseContent.tsConfig) {
assert.equal(testCaseContent.tsConfig.fileNames.length, 0, `list of files in tsconfig is not currently supported`);
tsConfigOptions = ts.clone(testCaseContent.tsConfig.options);
}
else {
const baseUrl = harnessSettings["baseUrl"];
if (baseUrl !== undefined && !ts.isRootedDiskPath(baseUrl)) {
harnessSettings["baseUrl"] = ts.getNormalizedAbsolutePath(baseUrl, rootDir);
}
}
lastUnit = units[units.length - 1];
hasNonDtsFiles = ts.forEach(units, unit => !ts.fileExtensionIs(unit.name, ".d.ts"));
const rootDir = lastUnit.originalFilePath.indexOf("conformance") === -1 ? "tests/cases/compiler/" : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf("/")) + "/";
// We need to assemble the list of input files for the compiler and other related files on the 'filesystem' (ie in a multi-file test)
// If the last file in a test uses require or a triple slash reference we'll assume all other files will be brought in via references,
// otherwise, assume all files are just meant to be in the same compilation session without explicit references to one another.
toBeCompiled = [];
otherFiles = [];
if (/require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content });
units.forEach(unit => {
@@ -90,7 +103,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
const output = Harness.Compiler.compileFiles(
toBeCompiled, otherFiles, harnessSettings, /* options */ undefined, /* currentDirectory */ undefined);
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ undefined);
options = output.options;
result = output.result;
@@ -126,6 +139,14 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it (`Correct module resolution tracing for ${fileName}`, () => {
if (options.traceModuleResolution) {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".trace.json"), () => {
return JSON.stringify(result.traceResults || [], undefined, 4);
});
}
});
// Source maps?
it("Correct sourcemap content for " + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
+44 -20
View File
@@ -245,7 +245,6 @@ namespace Utils {
}
function getNodeFlagName(f: number) { return getFlagName((<any>ts).NodeFlags, f); }
function getParserContextFlagName(f: number) { return getFlagName((<any>ts).ParserContextFlags, f); }
function serializeNode(n: ts.Node): any {
const o: any = { kind: getKindName(n.kind) };
@@ -274,19 +273,12 @@ namespace Utils {
break;
case "flags":
// Print out flags with their enum names.
if (n.flags) {
o[propertyName] = getNodeFlagName(n.flags);
}
break;
case "parserContextFlags":
// Clear the flag that are produced by aggregating child values.. That is ephemeral
// data we don't care about in the dump. We only care what the parser set directly
// on the ast.
let value = n.parserContextFlags & ts.ParserContextFlags.ParserGeneratedFlags;
if (value) {
o[propertyName] = getParserContextFlagName(value);
// Clear the flags that are produced by aggregating child values. That is ephemeral
// data we don't care about in the dump. We only care what the parser set directly
// on the AST.
const flags = n.flags & ~(ts.NodeFlags.JavaScriptFile | ts.NodeFlags.HasAggregatedChildData);
if (flags) {
o[propertyName] = getNodeFlagName(flags);
}
break;
@@ -353,12 +345,11 @@ namespace Utils {
assert.equal(node1.pos, node2.pos, "node1.pos !== node2.pos");
assert.equal(node1.end, node2.end, "node1.end !== node2.end");
assert.equal(node1.kind, node2.kind, "node1.kind !== node2.kind");
assert.equal(node1.flags, node2.flags, "node1.flags !== node2.flags");
// call this on both nodes to ensure all propagated flags have been set (and thus can be
// compared).
assert.equal(ts.containsParseError(node1), ts.containsParseError(node2));
assert.equal(node1.parserContextFlags, node2.parserContextFlags, "node1.parserContextFlags !== node2.parserContextFlags");
assert.equal(node1.flags, node2.flags, "node1.flags !== node2.flags");
ts.forEachChild(node1,
child1 => {
@@ -985,6 +976,9 @@ namespace Harness {
if (harnessSettings) {
setCompilerOptionsFromHarnessSetting(harnessSettings, options);
}
if (options.rootDirs) {
options.rootDirs = ts.map(options.rootDirs, d => ts.getNormalizedAbsolutePath(d, currentDirectory));
}
const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
const programFiles: TestFile[] = inputFiles.slice();
@@ -1019,13 +1013,19 @@ namespace Harness {
useCaseSensitiveFileNames,
currentDirectory,
options.newLine);
let traceResults: string[];
if (options.traceModuleResolution) {
traceResults = [];
compilerHost.trace = text => traceResults.push(text);
}
const program = ts.createProgram(programFileNames, options, compilerHost);
const emitResult = program.emit();
const errors = ts.getPreEmitDiagnostics(program);
const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps);
const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps, traceResults);
return { result, options };
}
@@ -1306,7 +1306,7 @@ namespace Harness {
/** @param fileResults an array of strings for the fileName and an ITextWriter with its code */
constructor(fileResults: GeneratedFile[], errors: ts.Diagnostic[], public program: ts.Program,
public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[]) {
public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[], public traceResults: string[]) {
for (const emittedFile of fileResults) {
if (isDTS(emittedFile.fileName)) {
@@ -1366,7 +1366,7 @@ namespace Harness {
}
/** Given a test file containing // @FileName directives, return an array of named units of code to be added to an existing compiler instance */
export function makeUnitsFromTest(code: string, fileName: string): { settings: CompilerSettings; testUnitData: TestUnitData[]; } {
export function makeUnitsFromTest(code: string, fileName: string, rootDir?: string): { settings: CompilerSettings; testUnitData: TestUnitData[]; tsConfig: ts.ParsedCommandLine } {
const settings = extractCompilerSettings(code);
// List of all the subfiles we've parsed out
@@ -1444,7 +1444,31 @@ namespace Harness {
};
testUnitData.push(newTestFile2);
return { settings, testUnitData };
// unit tests always list files explicitly
const parseConfigHost: ts.ParseConfigHost = {
readDirectory: (name) => []
};
// check if project has tsconfig.json in the list of files
let tsConfig: ts.ParsedCommandLine;
for (let i = 0; i < testUnitData.length; i++) {
const data = testUnitData[i];
if (ts.getBaseFileName(data.name).toLowerCase() === "tsconfig.json") {
const configJson = ts.parseConfigFileTextToJson(data.name, data.content);
assert.isTrue(configJson.config !== undefined);
let baseDir = ts.normalizePath(ts.getDirectoryPath(data.name));
if (rootDir) {
baseDir = ts.getNormalizedAbsolutePath(baseDir, rootDir);
}
tsConfig = ts.parseJsonConfigFileContent(configJson.config, parseConfigHost, baseDir);
// delete entry from the list
testUnitData.splice(i, 1);
break;
}
}
return { settings, testUnitData, tsConfig };
}
}
+2 -1
View File
@@ -547,7 +547,8 @@ namespace Harness.LanguageService {
}
directoryExists(path: string): boolean {
return false;
// for tests assume that directory exists
return true;
}
getExecutingFilePath(): string {
+238 -150
View File
File diff suppressed because it is too large Load Diff
+12 -6
View File
@@ -378,6 +378,8 @@ interface AudioNode extends EventTarget {
numberOfOutputs: number;
connect(destination: AudioNode, output?: number, input?: number): void;
disconnect(output?: number): void;
disconnect(destination: AudioNode, output?: number, input?: number): void;
disconnect(destination: AudioParam, output?: number): void;
}
declare var AudioNode: {
@@ -6894,7 +6896,7 @@ interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
source: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
delete(): IDBRequest;
@@ -6932,7 +6934,7 @@ interface IDBDatabase extends EventTarget {
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -6990,9 +6992,10 @@ declare var IDBKeyRange: {
interface IDBObjectStore {
indexNames: DOMStringList;
keyPath: string;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
@@ -7031,7 +7034,7 @@ interface IDBRequest extends EventTarget {
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
source: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -10218,11 +10221,14 @@ declare var SVGViewElement: {
}
interface SVGZoomAndPan {
zoomAndPan: number;
}
declare var SVGZoomAndPan: {
SVG_ZOOMANDPAN_DISABLE: number;
SVG_ZOOMANDPAN_MAGNIFY: number;
SVG_ZOOMANDPAN_UNKNOWN: number;
}
declare var SVGZoomAndPan: SVGZoomAndPan;
interface SVGZoomEvent extends UIEvent {
newScale: number;
@@ -12685,7 +12691,7 @@ interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(): void;
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
+50 -48
View File
@@ -7,14 +7,14 @@ interface Symbol {
/** Returns the primitive value of the specified object. */
valueOf(): Object;
[Symbol.toStringTag]: "Symbol";
readonly [Symbol.toStringTag]: "Symbol";
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
prototype: Symbol;
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
@@ -42,67 +42,67 @@ interface SymbolConstructor {
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
hasInstance: symbol;
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
isConcatSpreadable: symbol;
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
iterator: symbol;
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
match: symbol;
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
replace: symbol;
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
search: symbol;
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
species: symbol;
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
split: symbol;
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
toPrimitive: symbol;
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
toStringTag: symbol;
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
unscopables: symbol;
readonly unscopables: symbol;
}
declare var Symbol: SymbolConstructor;
@@ -200,7 +200,7 @@ interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
name: string;
readonly name: string;
/**
* Determines whether the given value inherits from this function if this function was used
@@ -218,7 +218,7 @@ interface NumberConstructor {
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
EPSILON: number;
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
@@ -253,14 +253,14 @@ interface NumberConstructor {
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
MAX_SAFE_INTEGER: number;
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
MIN_SAFE_INTEGER: number;
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
@@ -565,7 +565,7 @@ interface IterableIterator<T> extends Iterator<T> {
}
interface GeneratorFunction extends Function {
[Symbol.toStringTag]: "GeneratorFunction";
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface GeneratorFunctionConstructor {
@@ -575,7 +575,7 @@ interface GeneratorFunctionConstructor {
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
prototype: GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;
@@ -690,7 +690,7 @@ interface Math {
*/
cbrt(x: number): number;
[Symbol.toStringTag]: "Math";
readonly [Symbol.toStringTag]: "Math";
}
interface Date {
@@ -776,19 +776,19 @@ interface RegExp {
*
* If no flags are set, the value is the empty string.
*/
flags: string;
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
sticky: boolean;
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
unicode: boolean;
readonly unicode: boolean;
}
interface RegExpConstructor {
@@ -804,33 +804,34 @@ interface Map<K, V> {
has(key: K): boolean;
keys(): IterableIterator<K>;
set(key: K, value?: V): Map<K, V>;
size: number;
readonly size: number;
values(): IterableIterator<V>;
[Symbol.iterator]():IterableIterator<[K,V]>;
[Symbol.toStringTag]: "Map";
readonly [Symbol.toStringTag]: "Map";
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
prototype: Map<any, any>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
[Symbol.toStringTag]: "WeakMap";
readonly [Symbol.toStringTag]: "WeakMap";
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
prototype: WeakMap<any, any>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
@@ -842,37 +843,38 @@ interface Set<T> {
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
size: number;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
[Symbol.toStringTag]: "Set";
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
prototype: Set<any>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
[Symbol.toStringTag]: "WeakSet";
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
prototype: WeakSet<any>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
interface JSON {
[Symbol.toStringTag]: "JSON";
readonly [Symbol.toStringTag]: "JSON";
}
/**
@@ -882,11 +884,11 @@ interface JSON {
* buffer as needed.
*/
interface ArrayBuffer {
[Symbol.toStringTag]: "ArrayBuffer";
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
[Symbol.toStringTag]: "DataView";
readonly [Symbol.toStringTag]: "DataView";
}
/**
@@ -907,7 +909,7 @@ interface Int8Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Int8Array";
readonly [Symbol.toStringTag]: "Int8Array";
}
interface Int8ArrayConstructor {
@@ -940,7 +942,7 @@ interface Uint8Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "UInt8Array";
readonly [Symbol.toStringTag]: "UInt8Array";
}
interface Uint8ArrayConstructor {
@@ -976,7 +978,7 @@ interface Uint8ClampedArray {
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Uint8ClampedArray";
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
interface Uint8ClampedArrayConstructor {
@@ -1014,7 +1016,7 @@ interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Int16Array";
readonly [Symbol.toStringTag]: "Int16Array";
}
interface Int16ArrayConstructor {
@@ -1047,7 +1049,7 @@ interface Uint16Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Uint16Array";
readonly [Symbol.toStringTag]: "Uint16Array";
}
interface Uint16ArrayConstructor {
@@ -1080,7 +1082,7 @@ interface Int32Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Int32Array";
readonly [Symbol.toStringTag]: "Int32Array";
}
interface Int32ArrayConstructor {
@@ -1113,7 +1115,7 @@ interface Uint32Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Uint32Array";
readonly [Symbol.toStringTag]: "Uint32Array";
}
interface Uint32ArrayConstructor {
@@ -1146,7 +1148,7 @@ interface Float32Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Float32Array";
readonly [Symbol.toStringTag]: "Float32Array";
}
interface Float32ArrayConstructor {
@@ -1179,7 +1181,7 @@ interface Float64Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
[Symbol.toStringTag]: "Float64Array";
readonly [Symbol.toStringTag]: "Float64Array";
}
interface Float64ArrayConstructor {
@@ -1256,14 +1258,14 @@ interface Promise<T> {
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
[Symbol.toStringTag]: "Promise";
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
prototype: Promise<any>;
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
@@ -1325,7 +1327,7 @@ interface PromiseConstructor {
*/
resolve(): Promise<void>;
[Symbol.species]: Function;
readonly [Symbol.species]: Function;
}
declare var Promise: PromiseConstructor;
+6 -5
View File
@@ -275,7 +275,7 @@ interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
source: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
delete(): IDBRequest;
@@ -313,7 +313,7 @@ interface IDBDatabase extends EventTarget {
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -371,9 +371,10 @@ declare var IDBKeyRange: {
interface IDBObjectStore {
indexNames: DOMStringList;
keyPath: string;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
@@ -412,7 +413,7 @@ interface IDBRequest extends EventTarget {
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
source: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -959,7 +960,7 @@ interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(): void;
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
+1 -1
View File
@@ -10,7 +10,7 @@ namespace ts.BreakpointResolver {
*/
export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number) {
// Cannot set breakpoint in dts file
if (sourceFile.flags & NodeFlags.DeclarationFile) {
if (sourceFile.isDeclarationFile) {
return undefined;
}
+67 -45
View File
@@ -62,7 +62,7 @@ namespace ts {
export interface SourceFile {
/* @internal */ version: string;
/* @internal */ scriptSnapshot: IScriptSnapshot;
/* @internal */ nameTable: Map<string>;
/* @internal */ nameTable: Map<number>;
/* @internal */ getNamedDeclarations(): Map<Declaration[]>;
@@ -237,14 +237,14 @@ namespace ts {
while (pos < end) {
const token = scanner.scan();
const textPos = scanner.getTextPos();
nodes.push(createNode(token, pos, textPos, NodeFlags.Synthetic, this));
nodes.push(createNode(token, pos, textPos, 0, this));
pos = textPos;
}
return pos;
}
private createSyntaxList(nodes: NodeArray<Node>): Node {
const list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, NodeFlags.Synthetic, this);
const list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, 0, this);
list._children = [];
let pos = nodes.pos;
@@ -797,6 +797,7 @@ namespace ts {
public parseDiagnostics: Diagnostic[];
public bindDiagnostics: Diagnostic[];
public isDeclarationFile: boolean;
public isDefaultLib: boolean;
public hasNoDefaultLib: boolean;
public externalModuleIndicator: Node; // The first node that causes this file to be an external module
@@ -808,7 +809,7 @@ namespace ts {
public languageVersion: ScriptTarget;
public languageVariant: LanguageVariant;
public identifiers: Map<string>;
public nameTable: Map<string>;
public nameTable: Map<number>;
public resolvedModules: Map<ResolvedModule>;
public imports: LiteralExpression[];
public moduleAugmentations: LiteralExpression[];
@@ -1875,6 +1876,9 @@ namespace ts {
options.isolatedModules = true;
// transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
options.suppressOutputPathCheck = true;
// Filename can be non-ts file.
options.allowNonTsExtensions = true;
@@ -1954,8 +1958,6 @@ namespace ts {
const text = scriptSnapshot.getText(0, scriptSnapshot.getLength());
const sourceFile = createSourceFile(fileName, text, scriptTarget, setNodeParents);
setSourceFileFields(sourceFile, scriptSnapshot, version);
// after full parsing we can use table with interned strings as name table
sourceFile.nameTable = sourceFile.identifiers;
return sourceFile;
}
@@ -2777,6 +2779,9 @@ namespace ts {
return directoryProbablyExists(directoryName, host);
}
};
if (host.trace) {
compilerHost.trace = message => host.trace(message);
}
if (host.resolveModuleNames) {
compilerHost.resolveModuleNames = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile);
@@ -3831,7 +3836,7 @@ namespace ts {
if (isRightOfDot && isSourceFileJavaScript(sourceFile)) {
const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries);
addRange(entries, getJavaScriptCompletionEntries(sourceFile, uniqueNames));
addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames));
}
else {
if (!symbols || symbols.length === 0) {
@@ -3864,12 +3869,17 @@ namespace ts {
return { isMemberCompletion, isNewIdentifierLocation, entries };
function getJavaScriptCompletionEntries(sourceFile: SourceFile, uniqueNames: Map<string>): CompletionEntry[] {
function getJavaScriptCompletionEntries(sourceFile: SourceFile, position: number, uniqueNames: Map<string>): CompletionEntry[] {
const entries: CompletionEntry[] = [];
const target = program.getCompilerOptions().target;
const nameTable = getNameTable(sourceFile);
for (const name in nameTable) {
// Skip identifiers produced only from the current location
if (nameTable[name] === position) {
continue;
}
if (!uniqueNames[name]) {
uniqueNames[name] = name;
const displayName = getCompletionEntryDisplayName(name, target, /*performCharacterChecks*/ true);
@@ -5484,7 +5494,7 @@ namespace ts {
const nameTable = getNameTable(sourceFile);
if (lookUp(nameTable, internedName)) {
if (lookUp(nameTable, internedName) !== undefined) {
result = result || [];
getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex);
}
@@ -6853,21 +6863,58 @@ namespace ts {
}
}
function classifyTokenOrJsxText(token: Node): void {
if (nodeIsMissing(token)) {
return;
/**
* Returns true if node should be treated as classified and no further processing is required.
* False will mean that node is not classified and traverse routine should recurse into node contents.
*/
function tryClassifyNode(node: Node): boolean {
if (nodeIsMissing(node)) {
return true;
}
const tokenStart = token.kind === SyntaxKind.JsxText ? token.pos : classifyLeadingTriviaAndGetTokenStart(token);
const classifiedElementName = tryClassifyJsxElementName(node);
if (!isToken(node) && node.kind !== SyntaxKind.JsxText && classifiedElementName === undefined) {
return false;
}
const tokenWidth = token.end - tokenStart;
const tokenStart = node.kind === SyntaxKind.JsxText ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
const tokenWidth = node.end - tokenStart;
Debug.assert(tokenWidth >= 0);
if (tokenWidth > 0) {
const type = classifyTokenType(token.kind, token);
const type = classifiedElementName || classifyTokenType(node.kind, node);
if (type) {
pushClassification(tokenStart, tokenWidth, type);
}
}
return true;
}
function tryClassifyJsxElementName(token: Node): ClassificationType {
switch (token.parent && token.parent.kind) {
case SyntaxKind.JsxOpeningElement:
if ((<JsxOpeningElement>token.parent).tagName === token) {
return ClassificationType.jsxOpenTagName;
}
break;
case SyntaxKind.JsxClosingElement:
if ((<JsxClosingElement>token.parent).tagName === token) {
return ClassificationType.jsxCloseTagName;
}
break;
case SyntaxKind.JsxSelfClosingElement:
if ((<JsxSelfClosingElement>token.parent).tagName === token) {
return ClassificationType.jsxSelfClosingTagName;
}
break;
case SyntaxKind.JsxAttribute:
if ((<JsxAttribute>token.parent).name === token) {
return ClassificationType.jsxAttribute;
}
break;
}
return undefined;
}
// for accurate classification, the actual token should be passed in. however, for
@@ -6960,28 +7007,6 @@ namespace ts {
return ClassificationType.parameterName;
}
return;
case SyntaxKind.JsxOpeningElement:
if ((<JsxOpeningElement>token.parent).tagName === token) {
return ClassificationType.jsxOpenTagName;
}
return;
case SyntaxKind.JsxClosingElement:
if ((<JsxClosingElement>token.parent).tagName === token) {
return ClassificationType.jsxCloseTagName;
}
return;
case SyntaxKind.JsxSelfClosingElement:
if ((<JsxSelfClosingElement>token.parent).tagName === token) {
return ClassificationType.jsxSelfClosingTagName;
}
return;
case SyntaxKind.JsxAttribute:
if ((<JsxAttribute>token.parent).name === token) {
return ClassificationType.jsxAttribute;
}
}
}
return ClassificationType.identifier;
@@ -7000,10 +7025,7 @@ namespace ts {
const children = element.getChildren(sourceFile);
for (let i = 0, n = children.length; i < n; i++) {
const child = children[i];
if (isToken(child) || child.kind === SyntaxKind.JsxText) {
classifyTokenOrJsxText(child);
}
else {
if (!tryClassifyNode(child)) {
// Recurse into our child nodes.
processElement(child);
}
@@ -7510,7 +7532,7 @@ namespace ts {
}
/* @internal */
export function getNameTable(sourceFile: SourceFile): Map<string> {
export function getNameTable(sourceFile: SourceFile): Map<number> {
if (!sourceFile.nameTable) {
initializeNameTable(sourceFile);
}
@@ -7519,7 +7541,7 @@ namespace ts {
}
function initializeNameTable(sourceFile: SourceFile): void {
const nameTable: Map<string> = {};
const nameTable: Map<number> = {};
walk(sourceFile);
sourceFile.nameTable = nameTable;
@@ -7527,7 +7549,7 @@ namespace ts {
function walk(node: Node) {
switch (node.kind) {
case SyntaxKind.Identifier:
nameTable[(<Identifier>node).text] = (<Identifier>node).text;
nameTable[(<Identifier>node).text] = nameTable[(<Identifier>node).text] === undefined ? node.pos : -1;
break;
case SyntaxKind.StringLiteral:
case SyntaxKind.NumericLiteral:
@@ -7539,7 +7561,7 @@ namespace ts {
node.parent.kind === SyntaxKind.ExternalModuleReference ||
isArgumentOfElementAccessExpression(node)) {
nameTable[(<LiteralExpression>node).text] = (<LiteralExpression>node).text;
nameTable[(<LiteralExpression>node).text] = nameTable[(<LiteralExpression>node).text] === undefined ? node.pos : -1;
}
break;
default:
+3 -1
View File
@@ -78,6 +78,8 @@ namespace ts {
* when enumerating the directory.
*/
readDirectory(rootDir: string, extension: string, exclude?: string): string;
trace(s: string): void;
}
///
@@ -1057,6 +1059,6 @@ namespace TypeScript.Services {
// TODO: it should be moved into a namespace though.
/* @internal */
const toolsVersion = "1.8";
const toolsVersion = "1.9";
/* tslint:enable:no-unused-variable */
@@ -21,8 +21,8 @@ class D {
}
var x = {
>x : { a: number; }
>{ get a() { return 1 }} : { a: number; }
>x : { readonly a: number; }
>{ get a() { return 1 }} : { readonly a: number; }
get a() { return 1 }
>a : number
@@ -17,8 +17,9 @@ module M {
//// [aliasesInSystemModule1.js]
System.register(['foo'], function(exports_1) {
System.register(['foo'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var alias;
var cls, cls2, x, y, z, M;
return {
@@ -16,8 +16,9 @@ module M {
}
//// [aliasesInSystemModule2.js]
System.register(["foo"], function(exports_1) {
System.register(["foo"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var foo_1;
var cls, cls2, x, y, z, M;
return {
@@ -10,8 +10,9 @@ export class Foo {
}
//// [b.js]
System.register([], function(exports_1) {
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Foo;
return {
setters:[],
@@ -26,8 +27,9 @@ System.register([], function(exports_1) {
}
});
//// [a.js]
System.register(["./b"], function(exports_1) {
System.register(["./b"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
var x;
return {
@@ -11,8 +11,9 @@ export class Foo {
//// [b.js]
System.register([], function(exports_1) {
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Foo;
return {
setters:[],
@@ -27,8 +28,9 @@ System.register([], function(exports_1) {
}
});
//// [a.js]
System.register(["./b"], function(exports_1) {
System.register(["./b"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
var x;
return {
@@ -12,8 +12,9 @@ export var x = new Foo();
//// [a.js]
System.register(["./b"], function(exports_1) {
System.register(["./b"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
var x;
return {
@@ -12,8 +12,9 @@ export var x = new Foo();
//// [a.js]
System.register(["./b"], function(exports_1) {
System.register(["./b"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
var x;
return {
@@ -1,5 +1,4 @@
tests/cases/conformance/ambient/ambientErrors.ts(2,15): error TS1039: Initializers are not allowed in ambient contexts.
tests/cases/conformance/ambient/ambientErrors.ts(6,18): error TS2382: Specialized overload signature is not assignable to any non-specialized signature.
tests/cases/conformance/ambient/ambientErrors.ts(17,22): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
tests/cases/conformance/ambient/ambientErrors.ts(20,24): error TS1183: An implementation cannot be declared in ambient contexts.
tests/cases/conformance/ambient/ambientErrors.ts(29,9): error TS1066: In ambient enum declarations member initializer must be constant expression.
@@ -15,7 +14,7 @@ tests/cases/conformance/ambient/ambientErrors.ts(51,16): error TS2436: Ambient m
tests/cases/conformance/ambient/ambientErrors.ts(57,5): error TS2309: An export assignment cannot be used in a module with other exported elements.
==== tests/cases/conformance/ambient/ambientErrors.ts (15 errors) ====
==== tests/cases/conformance/ambient/ambientErrors.ts (14 errors) ====
// Ambient variable with an initializer
declare var x = 4;
~
@@ -24,8 +23,6 @@ tests/cases/conformance/ambient/ambientErrors.ts(57,5): error TS2309: An export
// Ambient functions with invalid overloads
declare function fn(x: number): string;
declare function fn(x: 'foo'): number;
~~
!!! error TS2382: Specialized overload signature is not assignable to any non-specialized signature.
// Ambient functions with duplicate signatures
declare function fn1(x: number): string;
@@ -7,8 +7,9 @@ export default class {}
export default function() {}
//// [a.js]
System.register([], function(exports_1) {
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var default_1;
return {
setters:[],
@@ -20,8 +21,9 @@ System.register([], function(exports_1) {
}
});
//// [b.js]
System.register([], function(exports_1) {
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function default_1() { }
exports_1("default", default_1);
return {
@@ -1,7 +1,7 @@
tests/cases/compiler/assignToEnum.ts(2,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/compiler/assignToEnum.ts(3,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/compiler/assignToEnum.ts(4,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/compiler/assignToEnum.ts(5,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/compiler/assignToEnum.ts(4,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
tests/cases/compiler/assignToEnum.ts(5,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
==== tests/cases/compiler/assignToEnum.ts (4 errors) ====
@@ -14,9 +14,9 @@ tests/cases/compiler/assignToEnum.ts(5,1): error TS2364: Invalid left-hand side
!!! error TS2364: Invalid left-hand side of assignment expression.
A.foo = 1; // invalid LHS
~~~~~
!!! error TS2364: Invalid left-hand side of assignment expression.
!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
A.foo = A.bar; // invalid LHS
~~~~~
!!! error TS2364: Invalid left-hand side of assignment expression.
!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
@@ -1,7 +1,7 @@
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(11,1): error TS2304: Cannot find name 'M'.
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(14,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(17,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(21,1): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): error TS2304: Cannot find name 'I'.
@@ -32,7 +32,7 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): er
!!! error TS2364: Invalid left-hand side of assignment expression.
E.A = null; // OK per spec, Error per implementation (509581)
~~~
!!! error TS2364: Invalid left-hand side of assignment expression.
!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
function fn() { }
fn = null; // Should be error
@@ -1,10 +0,0 @@
tests/cases/conformance/async/es6/asyncAliasReturnType_es6.ts(3,16): error TS1055: Type 'PromiseAlias' is not a valid async function return type.
==== tests/cases/conformance/async/es6/asyncAliasReturnType_es6.ts (1 errors) ====
type PromiseAlias<T> = Promise<T>;
async function f(): PromiseAlias<void> {
~
!!! error TS1055: Type 'PromiseAlias' is not a valid async function return type.
}
@@ -6,6 +6,6 @@ async function f(): PromiseAlias<void> {
//// [asyncAliasReturnType_es6.js]
function f() {
return __awaiter(this, void 0, PromiseAlias, function* () {
return __awaiter(this, void 0, void 0, function* () {
});
}
@@ -0,0 +1,11 @@
=== tests/cases/conformance/async/es6/asyncAliasReturnType_es6.ts ===
type PromiseAlias<T> = Promise<T>;
>PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es6.ts, 0, 0))
>T : Symbol(T, Decl(asyncAliasReturnType_es6.ts, 0, 18))
>Promise : Symbol(Promise, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>T : Symbol(T, Decl(asyncAliasReturnType_es6.ts, 0, 18))
async function f(): PromiseAlias<void> {
>f : Symbol(f, Decl(asyncAliasReturnType_es6.ts, 0, 34))
>PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es6.ts, 0, 0))
}
@@ -0,0 +1,11 @@
=== tests/cases/conformance/async/es6/asyncAliasReturnType_es6.ts ===
type PromiseAlias<T> = Promise<T>;
>PromiseAlias : Promise<T>
>T : T
>Promise : Promise<T>
>T : T
async function f(): PromiseAlias<void> {
>f : () => Promise<void>
>PromiseAlias : Promise<T>
}
@@ -4,5 +4,5 @@ var foo = async (): Promise<void> => {
};
//// [asyncArrowFunction1_es6.js]
var foo = () => __awaiter(this, void 0, Promise, function* () {
var foo = () => __awaiter(this, void 0, void 0, function* () {
});
@@ -4,5 +4,5 @@ var foo = async (a = await): Promise<void> => {
}
//// [asyncArrowFunction6_es6.js]
var foo = (a = yield ) => __awaiter(this, void 0, Promise, function* () {
var foo = (a = yield ) => __awaiter(this, void 0, void 0, function* () {
});
@@ -7,8 +7,8 @@ var bar = async (): Promise<void> => {
}
//// [asyncArrowFunction7_es6.js]
var bar = () => __awaiter(this, void 0, Promise, function* () {
var bar = () => __awaiter(this, void 0, void 0, function* () {
// 'await' here is an identifier, and not an await expression.
var foo = (a = yield ) => __awaiter(this, void 0, Promise, function* () {
var foo = (a = yield ) => __awaiter(this, void 0, void 0, function* () {
});
});
@@ -5,6 +5,6 @@ var foo = async (): Promise<void> => {
}
//// [asyncArrowFunction8_es6.js]
var foo = () => __awaiter(this, void 0, Promise, function* () {
var foo = () => __awaiter(this, void 0, void 0, function* () {
var v = { [yield ]: foo };
});
@@ -11,6 +11,6 @@ class C {
class C {
method() {
function other() { }
var fn = () => __awaiter(this, arguments, Promise, function* (_arguments) { return yield other.apply(this, _arguments); });
var fn = () => __awaiter(this, arguments, void 0, function* () { return yield other.apply(this, arguments); });
}
}
@@ -9,6 +9,6 @@ class C {
//// [asyncArrowFunctionCapturesThis_es6.js]
class C {
method() {
var fn = () => __awaiter(this, void 0, Promise, function* () { return yield this; });
var fn = () => __awaiter(this, void 0, void 0, function* () { return yield this; });
}
}
@@ -41,73 +41,73 @@ module M {
//// [asyncAwaitIsolatedModules_es6.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
function f0() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
function f3() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
let f4 = function () {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
};
let f5 = function () {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
};
let f6 = function () {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, 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 f7 = () => __awaiter(this, void 0, void 0, function* () { });
let f8 = () => __awaiter(this, void 0, void 0, function* () { });
let f9 = () => __awaiter(this, void 0, void 0, function* () { });
let f10 = () => __awaiter(this, void 0, void 0, function* () { return p; });
let f11 = () => __awaiter(this, void 0, void 0, function* () { return mp; });
let f12 = () => __awaiter(this, void 0, void 0, function* () { return mp; });
let f13 = () => __awaiter(this, void 0, void 0, function* () { return p; });
let o = {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
},
m2() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
},
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
};
class C {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
m2() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
static m4() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
static m5() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
static m6() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
}
var M;
(function (M) {
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
M.f1 = f1;
})(M || (M = {}));
+25 -25
View File
@@ -41,73 +41,73 @@ module M {
//// [asyncAwait_es6.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
function f0() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
function f3() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
let f4 = function () {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
};
let f5 = function () {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
};
let f6 = function () {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, 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 f7 = () => __awaiter(this, void 0, void 0, function* () { });
let f8 = () => __awaiter(this, void 0, void 0, function* () { });
let f9 = () => __awaiter(this, void 0, void 0, function* () { });
let f10 = () => __awaiter(this, void 0, void 0, function* () { return p; });
let f11 = () => __awaiter(this, void 0, void 0, function* () { return mp; });
let f12 = () => __awaiter(this, void 0, void 0, function* () { return mp; });
let f13 = () => __awaiter(this, void 0, void 0, function* () { return p; });
let o = {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
},
m2() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
},
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
};
class C {
m1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
m2() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
m3() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
static m4() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
static m5() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
static m6() {
return __awaiter(this, void 0, MyPromise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
}
var M;
(function (M) {
function f1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
M.f1 = f1;
})(M || (M = {}));
@@ -4,6 +4,6 @@ async function await(): Promise<void> {
//// [asyncFunctionDeclaration11_es6.js]
function await() {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
});
}
@@ -7,7 +7,7 @@ async function foo(): Promise<void> {
//// [asyncFunctionDeclaration13_es6.js]
function foo() {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
// Legal to use 'await' in a type context.
var v;
});
@@ -5,7 +5,7 @@ async function foo(): Promise<void> {
//// [asyncFunctionDeclaration14_es6.js]
function foo() {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
return;
});
}
@@ -1,12 +1,8 @@
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(6,16): error TS1055: Type '{}' is not a valid async function return type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(7,16): error TS1055: Type 'any' is not a valid async function return type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(8,16): error TS1055: Type 'number' is not a valid async function return type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(9,16): error TS1055: Type 'PromiseLike' is not a valid async function return type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(10,16): error TS1055: Type 'typeof Thenable' is not a valid async function return type.
Type 'Thenable' is not assignable to type 'PromiseLike<any>'.
Types of property 'then' are incompatible.
Type '() => void' is not assignable to type '{ <TResult>(onfulfilled?: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>; <TResult>(onfulfilled?: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>; }'.
Type 'void' is not assignable to type 'PromiseLike<any>'.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(6,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(7,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(8,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(9,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(10,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(17,16): error TS1059: Return expression in async function does not have a valid callable 'then' member.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(23,25): error TS1058: Operand for 'await' does not have a valid callable 'then' member.
@@ -18,24 +14,20 @@ tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration1
declare let thenable: Thenable;
async function fn1() { } // valid: Promise<void>
async function fn2(): { } { } // error
~~~
!!! error TS1055: Type '{}' is not a valid async function return type.
~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
async function fn3(): any { } // error
~~~
!!! error TS1055: Type 'any' is not a valid async function return type.
~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
async function fn4(): number { } // error
~~~
!!! error TS1055: Type 'number' is not a valid async function return type.
~~~~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
async function fn5(): PromiseLike<void> { } // error
~~~
!!! error TS1055: Type 'PromiseLike' is not a valid async function return type.
~~~~~~~~~~~~~~~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
async function fn6(): Thenable { } // error
~~~
!!! error TS1055: Type 'typeof Thenable' is not a valid async function return type.
!!! error TS1055: Type 'Thenable' is not assignable to type 'PromiseLike<any>'.
!!! error TS1055: Types of property 'then' are incompatible.
!!! error TS1055: Type '() => void' is not assignable to type '{ <TResult>(onfulfilled?: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>; <TResult>(onfulfilled?: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>; }'.
!!! error TS1055: Type 'void' is not assignable to type 'PromiseLike<any>'.
~~~~~~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
async function fn7() { return; } // valid: Promise<void>
async function fn8() { return 1; } // valid: Promise<number>
async function fn9() { return null; } // valid: Promise<any>
@@ -26,59 +26,59 @@ async function fn19() { await thenable; } // error
//// [asyncFunctionDeclaration15_es6.js]
function fn1() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
} // valid: Promise<void>
function fn2() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
} // error
function fn3() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
} // error
function fn4() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
} // error
function fn5() {
return __awaiter(this, void 0, PromiseLike, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
} // error
function fn6() {
return __awaiter(this, void 0, Thenable, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
} // error
function fn7() {
return __awaiter(this, void 0, Promise, function* () { return; });
return __awaiter(this, void 0, void 0, function* () { return; });
} // valid: Promise<void>
function fn8() {
return __awaiter(this, void 0, Promise, function* () { return 1; });
return __awaiter(this, void 0, void 0, function* () { return 1; });
} // valid: Promise<number>
function fn9() {
return __awaiter(this, void 0, Promise, function* () { return null; });
return __awaiter(this, void 0, void 0, function* () { return null; });
} // valid: Promise<any>
function fn10() {
return __awaiter(this, void 0, Promise, function* () { return undefined; });
return __awaiter(this, void 0, void 0, function* () { return undefined; });
} // valid: Promise<any>
function fn11() {
return __awaiter(this, void 0, Promise, function* () { return a; });
return __awaiter(this, void 0, void 0, function* () { return a; });
} // valid: Promise<any>
function fn12() {
return __awaiter(this, void 0, Promise, function* () { return obj; });
return __awaiter(this, void 0, void 0, function* () { return obj; });
} // valid: Promise<{ then: string; }>
function fn13() {
return __awaiter(this, void 0, Promise, function* () { return thenable; });
return __awaiter(this, void 0, void 0, function* () { return thenable; });
} // error
function fn14() {
return __awaiter(this, void 0, Promise, function* () { yield 1; });
return __awaiter(this, void 0, void 0, function* () { yield 1; });
} // valid: Promise<void>
function fn15() {
return __awaiter(this, void 0, Promise, function* () { yield null; });
return __awaiter(this, void 0, void 0, function* () { yield null; });
} // valid: Promise<void>
function fn16() {
return __awaiter(this, void 0, Promise, function* () { yield undefined; });
return __awaiter(this, void 0, void 0, function* () { yield undefined; });
} // valid: Promise<void>
function fn17() {
return __awaiter(this, void 0, Promise, function* () { yield a; });
return __awaiter(this, void 0, void 0, function* () { yield a; });
} // valid: Promise<void>
function fn18() {
return __awaiter(this, void 0, Promise, function* () { yield obj; });
return __awaiter(this, void 0, void 0, function* () { yield obj; });
} // valid: Promise<void>
function fn19() {
return __awaiter(this, void 0, Promise, function* () { yield thenable; });
return __awaiter(this, void 0, void 0, function* () { yield thenable; });
} // error
@@ -4,6 +4,6 @@ async function foo(): Promise<void> {
//// [asyncFunctionDeclaration1_es6.js]
function foo() {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
});
}
@@ -4,6 +4,6 @@ async function foo(a = await): Promise<void> {
//// [asyncFunctionDeclaration6_es6.js]
function foo(a = yield ) {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
});
}
@@ -7,10 +7,10 @@ async function bar(): Promise<void> {
//// [asyncFunctionDeclaration7_es6.js]
function bar() {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
// 'await' here is an identifier, and not a yield expression.
function foo(a = yield ) {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
});
}
});
@@ -5,7 +5,7 @@ async function foo(): Promise<void> {
//// [asyncFunctionDeclaration9_es6.js]
function foo() {
return __awaiter(this, void 0, Promise, function* () {
return __awaiter(this, void 0, void 0, function* () {
var v = { [yield ]: foo };
});
}
@@ -17,31 +17,31 @@ export const b = {
//// [b.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
import { a } from './a';
export const b = {
f: () => __awaiter(this, void 0, Promise, function* () {
f: () => __awaiter(this, void 0, void 0, function* () {
yield a.f();
})
};
//// [a.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
import { b } from './b';
export const a = {
f: () => __awaiter(this, void 0, Promise, function* () {
f: () => __awaiter(this, void 0, void 0, function* () {
yield b.f();
})
};
@@ -0,0 +1,13 @@
tests/cases/conformance/async/es6/test.ts(3,25): error TS1064: The return type of an async function or method must be the global Promise<T> type.
==== tests/cases/conformance/async/es6/task.ts (0 errors) ====
export class Task<T> extends Promise<T> { }
==== tests/cases/conformance/async/es6/test.ts (1 errors) ====
import { Task } from "./task";
class Test {
async example<T>(): Task<T> { return; }
~~~~~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
}
@@ -17,16 +17,15 @@ exports.Task = Task;
//// [test.js]
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
var task_1 = require("./task");
class Test {
example() {
return __awaiter(this, void 0, task_1.Task, function* () { return; });
return __awaiter(this, void 0, void 0, function* () { return; });
}
}
@@ -1,20 +0,0 @@
=== tests/cases/conformance/async/es6/task.ts ===
export class Task<T> extends Promise<T> { }
>Task : Symbol(Task, Decl(task.ts, 0, 0))
>T : Symbol(T, Decl(task.ts, 0, 18))
>Promise : Symbol(Promise, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>T : Symbol(T, Decl(task.ts, 0, 18))
=== tests/cases/conformance/async/es6/test.ts ===
import { Task } from "./task";
>Task : Symbol(Task, Decl(test.ts, 0, 8))
class Test {
>Test : Symbol(Test, Decl(test.ts, 0, 30))
async example<T>(): Task<T> { return; }
>example : Symbol(example, Decl(test.ts, 1, 12))
>T : Symbol(T, Decl(test.ts, 2, 18))
>Task : Symbol(Task, Decl(test.ts, 0, 8))
>T : Symbol(T, Decl(test.ts, 2, 18))
}
@@ -1,20 +0,0 @@
=== tests/cases/conformance/async/es6/task.ts ===
export class Task<T> extends Promise<T> { }
>Task : Task<T>
>T : T
>Promise : Promise<T>
>T : T
=== tests/cases/conformance/async/es6/test.ts ===
import { Task } from "./task";
>Task : typeof Task
class Test {
>Test : Test
async example<T>(): Task<T> { return; }
>example : <T>() => Task<T>
>T : T
>Task : Task<T>
>T : T
}
@@ -0,0 +1,99 @@
//// [asyncMethodWithSuper_es6.ts]
class A {
x() {
}
}
class B extends A {
// async method with only call/get on 'super' does not require a binding
async simple() {
// call with property access
super.x();
// call with element access
super["x"]();
// property access (read)
const a = super.x;
// element access (read)
const b = super["x"];
}
// async method with assignment/destructuring on 'super' requires a binding
async advanced() {
const f = () => {};
// call with property access
super.x();
// call with element access
super["x"]();
// property access (read)
const a = super.x;
// element access (read)
const b = super["x"];
// property access (assign)
super.x = f;
// element access (assign)
super["x"] = f;
// destructuring assign with property access
({ f: super.x } = { f });
// destructuring assign with element access
({ f: super["x"] } = { f });
}
}
//// [asyncMethodWithSuper_es6.js]
class A {
x() {
}
}
class B extends A {
// async method with only call/get on 'super' does not require a binding
simple() {
const _super = name => super[name];
return __awaiter(this, void 0, void 0, function* () {
// call with property access
_super("x").call(this);
// call with element access
_super("x").call(this);
// property access (read)
const a = _super("x");
// element access (read)
const b = _super("x");
});
}
// async method with assignment/destructuring on 'super' requires a binding
advanced() {
const _super = (function (geti, seti) {
const cache = Object.create(null);
return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });
})(name => super[name], (name, value) => super[name] = value);
return __awaiter(this, void 0, void 0, function* () {
const f = () => { };
// call with property access
_super("x").value.call(this);
// call with element access
_super("x").value.call(this);
// property access (read)
const a = _super("x").value;
// element access (read)
const b = _super("x").value;
// property access (assign)
_super("x").value = f;
// element access (assign)
_super("x").value = f;
// destructuring assign with property access
({ f: _super("x").value } = { f });
// destructuring assign with element access
({ f: _super("x").value } = { f });
});
}
}
@@ -0,0 +1,102 @@
=== tests/cases/conformance/async/es6/asyncMethodWithSuper_es6.ts ===
class A {
>A : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
x() {
>x : Symbol(x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
}
}
class B extends A {
>B : Symbol(B, Decl(asyncMethodWithSuper_es6.ts, 3, 1))
>A : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
// async method with only call/get on 'super' does not require a binding
async simple() {
>simple : Symbol(simple, Decl(asyncMethodWithSuper_es6.ts, 5, 19))
// call with property access
super.x();
>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// call with element access
super["x"]();
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// property access (read)
const a = super.x;
>a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 15, 13))
>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// element access (read)
const b = super["x"];
>b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 18, 13))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
}
// async method with assignment/destructuring on 'super' requires a binding
async advanced() {
>advanced : Symbol(advanced, Decl(asyncMethodWithSuper_es6.ts, 19, 5))
const f = () => {};
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13))
// call with property access
super.x();
>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// call with element access
super["x"]();
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// property access (read)
const a = super.x;
>a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 32, 13))
>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// element access (read)
const b = super["x"];
>b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 35, 13))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
// property access (assign)
super.x = f;
>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13))
// element access (assign)
super["x"] = f;
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13))
// destructuring assign with property access
({ f: super.x } = { f });
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 44, 10))
>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 44, 27))
// destructuring assign with element access
({ f: super["x"] } = { f });
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 47, 10))
>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0))
>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9))
>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 47, 30))
}
}
@@ -0,0 +1,123 @@
=== tests/cases/conformance/async/es6/asyncMethodWithSuper_es6.ts ===
class A {
>A : A
x() {
>x : () => void
}
}
class B extends A {
>B : B
>A : A
// async method with only call/get on 'super' does not require a binding
async simple() {
>simple : () => Promise<void>
// call with property access
super.x();
>super.x() : void
>super.x : () => void
>super : A
>x : () => void
// call with element access
super["x"]();
>super["x"]() : void
>super["x"] : () => void
>super : A
>"x" : string
// property access (read)
const a = super.x;
>a : () => void
>super.x : () => void
>super : A
>x : () => void
// element access (read)
const b = super["x"];
>b : () => void
>super["x"] : () => void
>super : A
>"x" : string
}
// async method with assignment/destructuring on 'super' requires a binding
async advanced() {
>advanced : () => Promise<void>
const f = () => {};
>f : () => void
>() => {} : () => void
// call with property access
super.x();
>super.x() : void
>super.x : () => void
>super : A
>x : () => void
// call with element access
super["x"]();
>super["x"]() : void
>super["x"] : () => void
>super : A
>"x" : string
// property access (read)
const a = super.x;
>a : () => void
>super.x : () => void
>super : A
>x : () => void
// element access (read)
const b = super["x"];
>b : () => void
>super["x"] : () => void
>super : A
>"x" : string
// property access (assign)
super.x = f;
>super.x = f : () => void
>super.x : () => void
>super : A
>x : () => void
>f : () => void
// element access (assign)
super["x"] = f;
>super["x"] = f : () => void
>super["x"] : () => void
>super : A
>"x" : string
>f : () => void
// destructuring assign with property access
({ f: super.x } = { f });
>({ f: super.x } = { f }) : { f: () => void; }
>{ f: super.x } = { f } : { f: () => void; }
>{ f: super.x } : { f: () => void; }
>f : () => void
>super.x : () => void
>super : A
>x : () => void
>{ f } : { f: () => void; }
>f : () => void
// destructuring assign with element access
({ f: super["x"] } = { f });
>({ f: super["x"] } = { f }) : { f: () => void; }
>{ f: super["x"] } = { f } : { f: () => void; }
>{ f: super["x"] } : { f: () => void; }
>f : () => void
>super["x"] : () => void
>super : A
>"x" : string
>{ f } : { f: () => void; }
>f : () => void
}
}
+3 -3
View File
@@ -7,15 +7,15 @@ function g() { }
//// [a.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new P(function (resolve, reject) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.call(thisArg, _arguments)).next());
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
function f() {
return __awaiter(this, void 0, Promise, function* () { });
return __awaiter(this, void 0, void 0, function* () { });
}
//// [b.js]
function g() { }
@@ -0,0 +1,13 @@
tests/cases/conformance/async/es6/asyncQualifiedReturnType_es6.ts(6,21): error TS1064: The return type of an async function or method must be the global Promise<T> type.
==== tests/cases/conformance/async/es6/asyncQualifiedReturnType_es6.ts (1 errors) ====
namespace X {
export class MyPromise<T> extends Promise<T> {
}
}
async function f(): X.MyPromise<void> {
~~~~~~~~~~~~~~~~~
!!! error TS1064: The return type of an async function or method must be the global Promise<T> type.
}
@@ -15,6 +15,6 @@ var X;
X.MyPromise = MyPromise;
})(X || (X = {}));
function f() {
return __awaiter(this, void 0, X.MyPromise, function* () {
return __awaiter(this, void 0, void 0, function* () {
});
}
@@ -1,17 +0,0 @@
=== tests/cases/conformance/async/es6/asyncQualifiedReturnType_es6.ts ===
namespace X {
>X : Symbol(X, Decl(asyncQualifiedReturnType_es6.ts, 0, 0))
export class MyPromise<T> extends Promise<T> {
>MyPromise : Symbol(MyPromise, Decl(asyncQualifiedReturnType_es6.ts, 0, 13))
>T : Symbol(T, Decl(asyncQualifiedReturnType_es6.ts, 1, 27))
>Promise : Symbol(Promise, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>T : Symbol(T, Decl(asyncQualifiedReturnType_es6.ts, 1, 27))
}
}
async function f(): X.MyPromise<void> {
>f : Symbol(f, Decl(asyncQualifiedReturnType_es6.ts, 3, 1))
>X : Symbol(X, Decl(asyncQualifiedReturnType_es6.ts, 0, 0))
>MyPromise : Symbol(X.MyPromise, Decl(asyncQualifiedReturnType_es6.ts, 0, 13))
}
@@ -1,17 +0,0 @@
=== tests/cases/conformance/async/es6/asyncQualifiedReturnType_es6.ts ===
namespace X {
>X : typeof X
export class MyPromise<T> extends Promise<T> {
>MyPromise : MyPromise<T>
>T : T
>Promise : Promise<T>
>T : T
}
}
async function f(): X.MyPromise<void> {
>f : () => X.MyPromise<void>
>X : any
>MyPromise : X.MyPromise<T>
}
@@ -0,0 +1,26 @@
tests/cases/compiler/file2.ts(6,16): error TS2671: Cannot augment module './file1' because it resolves to a non-module entity.
tests/cases/compiler/file3.ts(3,8): error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file3.ts (1 errors) ====
import x = require("./file1");
import "./file2";
let a: x.A; // should not work
~
!!! error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file1.ts (0 errors) ====
var x = 1;
export = x;
==== tests/cases/compiler/file2.ts (1 errors) ====
import x = require("./file1");
// augmentation for './file1'
// should error since './file1' does not have namespace meaning
declare module "./file1" {
~~~~~~~~~
!!! error TS2671: Cannot augment module './file1' because it resolves to a non-module entity.
interface A { a }
}
@@ -0,0 +1,36 @@
//// [tests/cases/compiler/augmentExportEquals1.ts] ////
//// [file1.ts]
var x = 1;
export = x;
//// [file2.ts]
import x = require("./file1");
// augmentation for './file1'
// should error since './file1' does not have namespace meaning
declare module "./file1" {
interface A { a }
}
//// [file3.ts]
import x = require("./file1");
import "./file2";
let a: x.A; // should not work
//// [file1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
var x = 1;
return x;
});
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
});
//// [file3.js]
define(["require", "exports", "./file2"], function (require, exports) {
"use strict";
var a; // should not work
});
@@ -0,0 +1,29 @@
tests/cases/compiler/file2.ts(6,16): error TS2671: Cannot augment module 'file1' because it resolves to a non-module entity.
tests/cases/compiler/file3.ts(3,8): error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file3.ts (1 errors) ====
import x = require("file1");
import "file2";
let a: x.A; // should not work
~
!!! error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file1.d.ts (0 errors) ====
declare module "file1" {
var x: number;
export = x;
}
==== tests/cases/compiler/file2.ts (1 errors) ====
/// <reference path="file1.d.ts"/>
import x = require("file1");
// augmentation for 'file1'
// should error since 'file1' does not have namespace meaning
declare module "file1" {
~~~~~~~
!!! error TS2671: Cannot augment module 'file1' because it resolves to a non-module entity.
interface A { a }
}
@@ -0,0 +1,33 @@
//// [tests/cases/compiler/augmentExportEquals1_1.ts] ////
//// [file1.d.ts]
declare module "file1" {
var x: number;
export = x;
}
//// [file2.ts]
/// <reference path="file1.d.ts"/>
import x = require("file1");
// augmentation for 'file1'
// should error since 'file1' does not have namespace meaning
declare module "file1" {
interface A { a }
}
//// [file3.ts]
import x = require("file1");
import "file2";
let a: x.A; // should not work
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
});
//// [file3.js]
define(["require", "exports", "file2"], function (require, exports) {
"use strict";
var a; // should not work
});
@@ -0,0 +1,25 @@
tests/cases/compiler/file2.ts(4,16): error TS2671: Cannot augment module './file1' because it resolves to a non-module entity.
tests/cases/compiler/file3.ts(3,8): error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file3.ts (1 errors) ====
import x = require("./file1");
import "./file2";
let a: x.A; // should not work
~
!!! error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file1.ts (0 errors) ====
function foo() {}
export = foo;
==== tests/cases/compiler/file2.ts (1 errors) ====
import x = require("./file1");
// should error since './file1' does not have namespace meaning
declare module "./file1" {
~~~~~~~~~
!!! error TS2671: Cannot augment module './file1' because it resolves to a non-module entity.
interface A { a }
}
@@ -0,0 +1,35 @@
//// [tests/cases/compiler/augmentExportEquals2.ts] ////
//// [file1.ts]
function foo() {}
export = foo;
//// [file2.ts]
import x = require("./file1");
// should error since './file1' does not have namespace meaning
declare module "./file1" {
interface A { a }
}
//// [file3.ts]
import x = require("./file1");
import "./file2";
let a: x.A; // should not work
//// [file1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
function foo() { }
return foo;
});
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
});
//// [file3.js]
define(["require", "exports", "./file2"], function (require, exports) {
"use strict";
var a; // should not work
});
@@ -0,0 +1,29 @@
tests/cases/compiler/file2.ts(6,16): error TS2671: Cannot augment module 'file1' because it resolves to a non-module entity.
tests/cases/compiler/file3.ts(3,8): error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file3.ts (1 errors) ====
import x = require("file1");
import "file2";
let a: x.A; // should not work
~
!!! error TS2503: Cannot find namespace 'x'.
==== tests/cases/compiler/file1.d.ts (0 errors) ====
declare module "file1" {
function foo(): void;
export = foo;
}
==== tests/cases/compiler/file2.ts (1 errors) ====
/// <reference path="file1.d.ts"/>
import x = require("file1");
// should error since './file1' does not have namespace meaning
declare module "file1" {
~~~~~~~
!!! error TS2671: Cannot augment module 'file1' because it resolves to a non-module entity.
interface A { a }
}
@@ -0,0 +1,33 @@
//// [tests/cases/compiler/augmentExportEquals2_1.ts] ////
//// [file1.d.ts]
declare module "file1" {
function foo(): void;
export = foo;
}
//// [file2.ts]
/// <reference path="file1.d.ts"/>
import x = require("file1");
// should error since './file1' does not have namespace meaning
declare module "file1" {
interface A { a }
}
//// [file3.ts]
import x = require("file1");
import "file2";
let a: x.A; // should not work
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
});
//// [file3.js]
define(["require", "exports", "file2"], function (require, exports) {
"use strict";
var a; // should not work
});
@@ -0,0 +1,31 @@
tests/cases/compiler/file2.ts(6,15): error TS2665: Module augmentation cannot introduce new names in the top level scope.
tests/cases/compiler/file2.ts(7,9): error TS2665: Module augmentation cannot introduce new names in the top level scope.
==== tests/cases/compiler/file1.ts (0 errors) ====
function foo() {}
namespace foo {
export var v = 1;
}
export = foo;
==== tests/cases/compiler/file2.ts (2 errors) ====
import x = require("./file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a }
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
let b: number;
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
}
==== tests/cases/compiler/file3.ts (0 errors) ====
import * as x from "./file1";
import "./file2";
let a: x.A;
let b = x.b;
@@ -0,0 +1,47 @@
//// [tests/cases/compiler/augmentExportEquals3.ts] ////
//// [file1.ts]
function foo() {}
namespace foo {
export var v = 1;
}
export = foo;
//// [file2.ts]
import x = require("./file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a }
let b: number;
}
//// [file3.ts]
import * as x from "./file1";
import "./file2";
let a: x.A;
let b = x.b;
//// [file1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
function foo() { }
var foo;
(function (foo) {
foo.v = 1;
})(foo || (foo = {}));
return foo;
});
//// [file2.js]
define(["require", "exports", "./file1"], function (require, exports, x) {
"use strict";
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "./file1", "./file2"], function (require, exports, x) {
"use strict";
var a;
var b = x.b;
});
@@ -0,0 +1,34 @@
tests/cases/compiler/file2.ts(7,15): error TS2665: Module augmentation cannot introduce new names in the top level scope.
tests/cases/compiler/file2.ts(8,9): error TS2665: Module augmentation cannot introduce new names in the top level scope.
==== tests/cases/compiler/file1.d.ts (0 errors) ====
declare module "file1" {
function foo(): void;
namespace foo {
export var v: number;
}
export = foo;
}
==== tests/cases/compiler/file2.ts (2 errors) ====
/// <reference path="file1.d.ts"/>
import x = require("file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "file1" {
interface A { a }
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
let b: number;
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
}
==== tests/cases/compiler/file3.ts (0 errors) ====
import * as x from "file1";
import "file2";
let a: x.A;
let b = x.b;
@@ -0,0 +1,40 @@
//// [tests/cases/compiler/augmentExportEquals3_1.ts] ////
//// [file1.d.ts]
declare module "file1" {
function foo(): void;
namespace foo {
export var v: number;
}
export = foo;
}
//// [file2.ts]
/// <reference path="file1.d.ts"/>
import x = require("file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "file1" {
interface A { a }
let b: number;
}
//// [file3.ts]
import * as x from "file1";
import "file2";
let a: x.A;
let b = x.b;
//// [file2.js]
define(["require", "exports", "file1"], function (require, exports, x) {
"use strict";
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "file1", "file2"], function (require, exports, x) {
"use strict";
var a;
var b = x.b;
});
@@ -0,0 +1,31 @@
tests/cases/compiler/file2.ts(6,15): error TS2665: Module augmentation cannot introduce new names in the top level scope.
tests/cases/compiler/file2.ts(7,9): error TS2665: Module augmentation cannot introduce new names in the top level scope.
==== tests/cases/compiler/file1.ts (0 errors) ====
class foo {}
namespace foo {
export var v = 1;
}
export = foo;
==== tests/cases/compiler/file2.ts (2 errors) ====
import x = require("./file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a }
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
let b: number;
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
}
==== tests/cases/compiler/file3.ts (0 errors) ====
import * as x from "./file1";
import "./file2";
let a: x.A;
let b = x.b;
@@ -0,0 +1,51 @@
//// [tests/cases/compiler/augmentExportEquals4.ts] ////
//// [file1.ts]
class foo {}
namespace foo {
export var v = 1;
}
export = foo;
//// [file2.ts]
import x = require("./file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a }
let b: number;
}
//// [file3.ts]
import * as x from "./file1";
import "./file2";
let a: x.A;
let b = x.b;
//// [file1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
var foo = (function () {
function foo() {
}
return foo;
}());
var foo;
(function (foo) {
foo.v = 1;
})(foo || (foo = {}));
return foo;
});
//// [file2.js]
define(["require", "exports", "./file1"], function (require, exports, x) {
"use strict";
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "./file1", "./file2"], function (require, exports, x) {
"use strict";
var a;
var b = x.b;
});
@@ -0,0 +1,35 @@
tests/cases/compiler/file2.ts(7,15): error TS2665: Module augmentation cannot introduce new names in the top level scope.
tests/cases/compiler/file2.ts(8,9): error TS2665: Module augmentation cannot introduce new names in the top level scope.
==== tests/cases/compiler/file1.d.ts (0 errors) ====
declare module "file1" {
class foo {}
namespace foo {
export var v: number;
}
export = foo;
}
==== tests/cases/compiler/file2.ts (2 errors) ====
/// <reference path="file1.d.ts"/>
import x = require("file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "file1" {
interface A { a }
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
let b: number;
~
!!! error TS2665: Module augmentation cannot introduce new names in the top level scope.
}
==== tests/cases/compiler/file3.ts (0 errors) ====
import * as x from "file1";
import "file2";
let a: x.A;
let b = x.b;
@@ -0,0 +1,41 @@
//// [tests/cases/compiler/augmentExportEquals4_1.ts] ////
//// [file1.d.ts]
declare module "file1" {
class foo {}
namespace foo {
export var v: number;
}
export = foo;
}
//// [file2.ts]
/// <reference path="file1.d.ts"/>
import x = require("file1");
x.b = 1;
// OK - './file1' is a namespace
declare module "file1" {
interface A { a }
let b: number;
}
//// [file3.ts]
import * as x from "file1";
import "file2";
let a: x.A;
let b = x.b;
//// [file2.js]
define(["require", "exports", "file1"], function (require, exports, x) {
"use strict";
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "file1", "file2"], function (require, exports, x) {
"use strict";
var a;
var b = x.b;
});
@@ -0,0 +1,94 @@
//// [tests/cases/compiler/augmentExportEquals5.ts] ////
//// [express.d.ts]
declare module Express {
export interface Request { }
export interface Response { }
export interface Application { }
}
declare module "express" {
function e(): e.Express;
namespace e {
interface IRoute {
all(...handler: RequestHandler[]): IRoute;
}
interface IRouterMatcher<T> {
(name: string|RegExp, ...handlers: RequestHandler[]): T;
}
interface IRouter<T> extends RequestHandler {
route(path: string): IRoute;
}
export function Router(options?: any): Router;
export interface Router extends IRouter<Router> {}
interface Errback { (err: Error): void; }
interface Request extends Express.Request {
get (name: string): string;
}
interface Response extends Express.Response {
charset: string;
}
interface ErrorRequestHandler {
(err: any, req: Request, res: Response, next: Function): any;
}
interface RequestHandler {
(req: Request, res: Response, next: Function): any;
}
interface Handler extends RequestHandler {}
interface RequestParamHandler {
(req: Request, res: Response, next: Function, param: any): any;
}
interface Application extends IRouter<Application>, Express.Application {
routes: any;
}
interface Express extends Application {
createApplication(): Application;
}
var static: any;
}
export = e;
}
//// [augmentation.ts]
/// <reference path="express.d.ts"/>
import * as e from "express";
declare module "express" {
interface Request {
id: number;
}
}
//// [consumer.ts]
import { Request } from "express";
import "./augmentation";
let x: Request;
const y = x.id;
//// [augmentation.js]
define(["require", "exports"], function (require, exports) {
"use strict";
});
//// [consumer.js]
define(["require", "exports", "./augmentation"], function (require, exports) {
"use strict";
var x;
var y = x.id;
});
@@ -0,0 +1,194 @@
=== tests/cases/compiler/express.d.ts ===
declare module Express {
>Express : Symbol(Express, Decl(express.d.ts, 0, 0))
export interface Request { }
>Request : Symbol(Request, Decl(express.d.ts, 2, 24))
export interface Response { }
>Response : Symbol(Response, Decl(express.d.ts, 3, 32))
export interface Application { }
>Application : Symbol(Application, Decl(express.d.ts, 4, 33))
}
declare module "express" {
function e(): e.Express;
>e : Symbol(, Decl(express.d.ts, 8, 26), Decl(express.d.ts, 9, 28), Decl(augmentation.ts, 1, 29))
>e : Symbol(e, Decl(express.d.ts, 8, 26), Decl(express.d.ts, 9, 28))
>Express : Symbol(Express, Decl(express.d.ts, 54, 9))
namespace e {
>e : Symbol(, Decl(express.d.ts, 8, 26), Decl(express.d.ts, 9, 28), Decl(augmentation.ts, 1, 29))
interface IRoute {
>IRoute : Symbol(IRoute, Decl(express.d.ts, 10, 17))
all(...handler: RequestHandler[]): IRoute;
>all : Symbol(all, Decl(express.d.ts, 11, 26))
>handler : Symbol(handler, Decl(express.d.ts, 12, 16))
>RequestHandler : Symbol(RequestHandler, Decl(express.d.ts, 40, 9))
>IRoute : Symbol(IRoute, Decl(express.d.ts, 10, 17))
}
interface IRouterMatcher<T> {
>IRouterMatcher : Symbol(IRouterMatcher, Decl(express.d.ts, 13, 9))
>T : Symbol(T, Decl(express.d.ts, 15, 33))
(name: string|RegExp, ...handlers: RequestHandler[]): T;
>name : Symbol(name, Decl(express.d.ts, 16, 13))
>RegExp : Symbol(RegExp, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>handlers : Symbol(handlers, Decl(express.d.ts, 16, 33))
>RequestHandler : Symbol(RequestHandler, Decl(express.d.ts, 40, 9))
>T : Symbol(T, Decl(express.d.ts, 15, 33))
}
interface IRouter<T> extends RequestHandler {
>IRouter : Symbol(IRouter, Decl(express.d.ts, 17, 9))
>T : Symbol(T, Decl(express.d.ts, 19, 26))
>RequestHandler : Symbol(RequestHandler, Decl(express.d.ts, 40, 9))
route(path: string): IRoute;
>route : Symbol(route, Decl(express.d.ts, 19, 53))
>path : Symbol(path, Decl(express.d.ts, 20, 18))
>IRoute : Symbol(IRoute, Decl(express.d.ts, 10, 17))
}
export function Router(options?: any): Router;
>Router : Symbol(Router, Decl(express.d.ts, 21, 9), Decl(express.d.ts, 23, 54))
>options : Symbol(options, Decl(express.d.ts, 23, 31))
>Router : Symbol(Router, Decl(express.d.ts, 21, 9), Decl(express.d.ts, 23, 54))
export interface Router extends IRouter<Router> {}
>Router : Symbol(Router, Decl(express.d.ts, 21, 9), Decl(express.d.ts, 23, 54))
>IRouter : Symbol(IRouter, Decl(express.d.ts, 17, 9))
>Router : Symbol(Router, Decl(express.d.ts, 21, 9), Decl(express.d.ts, 23, 54))
interface Errback { (err: Error): void; }
>Errback : Symbol(Errback, Decl(express.d.ts, 25, 58))
>err : Symbol(err, Decl(express.d.ts, 27, 29))
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
interface Request extends Express.Request {
>Request : Symbol(Request, Decl(express.d.ts, 27, 49), Decl(augmentation.ts, 2, 26))
>Express.Request : Symbol(Express.Request, Decl(express.d.ts, 2, 24))
>Express : Symbol(Express, Decl(express.d.ts, 0, 0))
>Request : Symbol(Express.Request, Decl(express.d.ts, 2, 24))
get (name: string): string;
>get : Symbol(get, Decl(express.d.ts, 29, 51))
>name : Symbol(name, Decl(express.d.ts, 31, 17))
}
interface Response extends Express.Response {
>Response : Symbol(Response, Decl(express.d.ts, 32, 9))
>Express.Response : Symbol(Express.Response, Decl(express.d.ts, 3, 32))
>Express : Symbol(Express, Decl(express.d.ts, 0, 0))
>Response : Symbol(Express.Response, Decl(express.d.ts, 3, 32))
charset: string;
>charset : Symbol(charset, Decl(express.d.ts, 34, 53))
}
interface ErrorRequestHandler {
>ErrorRequestHandler : Symbol(ErrorRequestHandler, Decl(express.d.ts, 36, 9))
(err: any, req: Request, res: Response, next: Function): any;
>err : Symbol(err, Decl(express.d.ts, 39, 13))
>req : Symbol(req, Decl(express.d.ts, 39, 22))
>Request : Symbol(Request, Decl(express.d.ts, 27, 49), Decl(augmentation.ts, 2, 26))
>res : Symbol(res, Decl(express.d.ts, 39, 36))
>Response : Symbol(Response, Decl(express.d.ts, 32, 9))
>next : Symbol(next, Decl(express.d.ts, 39, 51))
>Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
interface RequestHandler {
>RequestHandler : Symbol(RequestHandler, Decl(express.d.ts, 40, 9))
(req: Request, res: Response, next: Function): any;
>req : Symbol(req, Decl(express.d.ts, 43, 13))
>Request : Symbol(Request, Decl(express.d.ts, 27, 49), Decl(augmentation.ts, 2, 26))
>res : Symbol(res, Decl(express.d.ts, 43, 26))
>Response : Symbol(Response, Decl(express.d.ts, 32, 9))
>next : Symbol(next, Decl(express.d.ts, 43, 41))
>Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
interface Handler extends RequestHandler {}
>Handler : Symbol(Handler, Decl(express.d.ts, 44, 9))
>RequestHandler : Symbol(RequestHandler, Decl(express.d.ts, 40, 9))
interface RequestParamHandler {
>RequestParamHandler : Symbol(RequestParamHandler, Decl(express.d.ts, 46, 51))
(req: Request, res: Response, next: Function, param: any): any;
>req : Symbol(req, Decl(express.d.ts, 49, 13))
>Request : Symbol(Request, Decl(express.d.ts, 27, 49), Decl(augmentation.ts, 2, 26))
>res : Symbol(res, Decl(express.d.ts, 49, 26))
>Response : Symbol(Response, Decl(express.d.ts, 32, 9))
>next : Symbol(next, Decl(express.d.ts, 49, 41))
>Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>param : Symbol(param, Decl(express.d.ts, 49, 57))
}
interface Application extends IRouter<Application>, Express.Application {
>Application : Symbol(Application, Decl(express.d.ts, 50, 9))
>IRouter : Symbol(IRouter, Decl(express.d.ts, 17, 9))
>Application : Symbol(Application, Decl(express.d.ts, 50, 9))
>Express.Application : Symbol(Express.Application, Decl(express.d.ts, 4, 33))
>Express : Symbol(Express, Decl(express.d.ts, 0, 0))
>Application : Symbol(Express.Application, Decl(express.d.ts, 4, 33))
routes: any;
>routes : Symbol(routes, Decl(express.d.ts, 52, 81))
}
interface Express extends Application {
>Express : Symbol(Express, Decl(express.d.ts, 54, 9))
>Application : Symbol(Application, Decl(express.d.ts, 50, 9))
createApplication(): Application;
>createApplication : Symbol(createApplication, Decl(express.d.ts, 56, 47))
>Application : Symbol(Application, Decl(express.d.ts, 50, 9))
}
var static: any;
>static : Symbol(static, Decl(express.d.ts, 60, 11))
}
export = e;
>e : Symbol(e, Decl(express.d.ts, 8, 26), Decl(express.d.ts, 9, 28))
}
=== tests/cases/compiler/augmentation.ts ===
/// <reference path="express.d.ts"/>
import * as e from "express";
>e : Symbol(e, Decl(augmentation.ts, 1, 6))
declare module "express" {
interface Request {
>Request : Symbol(Request, Decl(express.d.ts, 27, 49), Decl(augmentation.ts, 2, 26))
id: number;
>id : Symbol(id, Decl(augmentation.ts, 3, 23))
}
}
=== tests/cases/compiler/consumer.ts ===
import { Request } from "express";
>Request : Symbol(Request, Decl(consumer.ts, 0, 8))
import "./augmentation";
let x: Request;
>x : Symbol(x, Decl(consumer.ts, 2, 3))
>Request : Symbol(Request, Decl(consumer.ts, 0, 8))
const y = x.id;
>y : Symbol(y, Decl(consumer.ts, 3, 5))
>x.id : Symbol(Request.id, Decl(augmentation.ts, 3, 23))
>x : Symbol(x, Decl(consumer.ts, 2, 3))
>id : Symbol(Request.id, Decl(augmentation.ts, 3, 23))
@@ -0,0 +1,194 @@
=== tests/cases/compiler/express.d.ts ===
declare module Express {
>Express : any
export interface Request { }
>Request : Request
export interface Response { }
>Response : Response
export interface Application { }
>Application : Application
}
declare module "express" {
function e(): e.Express;
>e : typeof
>e : any
>Express : Express
namespace e {
>e : typeof
interface IRoute {
>IRoute : IRoute
all(...handler: RequestHandler[]): IRoute;
>all : (...handler: RequestHandler[]) => IRoute
>handler : RequestHandler[]
>RequestHandler : RequestHandler
>IRoute : IRoute
}
interface IRouterMatcher<T> {
>IRouterMatcher : IRouterMatcher<T>
>T : T
(name: string|RegExp, ...handlers: RequestHandler[]): T;
>name : string | RegExp
>RegExp : RegExp
>handlers : RequestHandler[]
>RequestHandler : RequestHandler
>T : T
}
interface IRouter<T> extends RequestHandler {
>IRouter : IRouter<T>
>T : T
>RequestHandler : RequestHandler
route(path: string): IRoute;
>route : (path: string) => IRoute
>path : string
>IRoute : IRoute
}
export function Router(options?: any): Router;
>Router : (options?: any) => Router
>options : any
>Router : Router
export interface Router extends IRouter<Router> {}
>Router : Router
>IRouter : IRouter<T>
>Router : Router
interface Errback { (err: Error): void; }
>Errback : Errback
>err : Error
>Error : Error
interface Request extends Express.Request {
>Request : Request
>Express.Request : any
>Express : any
>Request : Express.Request
get (name: string): string;
>get : (name: string) => string
>name : string
}
interface Response extends Express.Response {
>Response : Response
>Express.Response : any
>Express : any
>Response : Express.Response
charset: string;
>charset : string
}
interface ErrorRequestHandler {
>ErrorRequestHandler : ErrorRequestHandler
(err: any, req: Request, res: Response, next: Function): any;
>err : any
>req : Request
>Request : Request
>res : Response
>Response : Response
>next : Function
>Function : Function
}
interface RequestHandler {
>RequestHandler : RequestHandler
(req: Request, res: Response, next: Function): any;
>req : Request
>Request : Request
>res : Response
>Response : Response
>next : Function
>Function : Function
}
interface Handler extends RequestHandler {}
>Handler : Handler
>RequestHandler : RequestHandler
interface RequestParamHandler {
>RequestParamHandler : RequestParamHandler
(req: Request, res: Response, next: Function, param: any): any;
>req : Request
>Request : Request
>res : Response
>Response : Response
>next : Function
>Function : Function
>param : any
}
interface Application extends IRouter<Application>, Express.Application {
>Application : Application
>IRouter : IRouter<T>
>Application : Application
>Express.Application : any
>Express : any
>Application : Express.Application
routes: any;
>routes : any
}
interface Express extends Application {
>Express : Express
>Application : Application
createApplication(): Application;
>createApplication : () => Application
>Application : Application
}
var static: any;
>static : any
}
export = e;
>e : typeof e
}
=== tests/cases/compiler/augmentation.ts ===
/// <reference path="express.d.ts"/>
import * as e from "express";
>e : typeof e
declare module "express" {
interface Request {
>Request : Request
id: number;
>id : number
}
}
=== tests/cases/compiler/consumer.ts ===
import { Request } from "express";
>Request : any
import "./augmentation";
let x: Request;
>x : Request
>Request : Request
const y = x.id;
>y : number
>x.id : number
>x : Request
>id : number
@@ -0,0 +1,64 @@
//// [tests/cases/compiler/augmentExportEquals6.ts] ////
//// [file1.ts]
class foo {}
namespace foo {
export class A {}
export namespace B { export let a; }
}
export = foo;
//// [file2.ts]
import x = require("./file1");
x.B.b = 1;
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a: number }
namespace B {
export let b: number;
}
}
//// [file3.ts]
import * as x from "./file1";
import "./file2";
let a: x.A;
let b = a.a;
let c = x.B.b;
//// [file1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
var foo = (function () {
function foo() {
}
return foo;
}());
var foo;
(function (foo) {
var A = (function () {
function A() {
}
return A;
}());
foo.A = A;
var B;
(function (B) {
})(B = foo.B || (foo.B = {}));
})(foo || (foo = {}));
return foo;
});
//// [file2.js]
define(["require", "exports", "./file1"], function (require, exports, x) {
"use strict";
x.B.b = 1;
});
//// [file3.js]
define(["require", "exports", "./file1", "./file2"], function (require, exports, x) {
"use strict";
var a;
var b = a.a;
var c = x.B.b;
});
@@ -0,0 +1,67 @@
=== tests/cases/compiler/file1.ts ===
class foo {}
>foo : Symbol(, Decl(file1.ts, 0, 0), Decl(file1.ts, 1, 12), Decl(file2.ts, 1, 10))
namespace foo {
>foo : Symbol(, Decl(file1.ts, 0, 0), Decl(file1.ts, 1, 12), Decl(file2.ts, 1, 10))
export class A {}
>A : Symbol(A, Decl(file1.ts, 2, 15), Decl(file2.ts, 4, 26))
export namespace B { export let a; }
>B : Symbol(B, Decl(file1.ts, 3, 21), Decl(file2.ts, 5, 29))
>a : Symbol(a, Decl(file1.ts, 4, 35))
}
export = foo;
>foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 1, 12))
=== tests/cases/compiler/file2.ts ===
import x = require("./file1");
>x : Symbol(x, Decl(file2.ts, 0, 0))
x.B.b = 1;
>x.B.b : Symbol(x.B.b, Decl(file2.ts, 7, 18))
>x.B : Symbol(x.B, Decl(file1.ts, 3, 21), Decl(file2.ts, 5, 29))
>x : Symbol(x, Decl(file2.ts, 0, 0))
>B : Symbol(x.B, Decl(file1.ts, 3, 21), Decl(file2.ts, 5, 29))
>b : Symbol(x.B.b, Decl(file2.ts, 7, 18))
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a: number }
>A : Symbol(A, Decl(file1.ts, 2, 15), Decl(file2.ts, 4, 26))
>a : Symbol(a, Decl(file2.ts, 5, 17))
namespace B {
>B : Symbol(B, Decl(file1.ts, 3, 21), Decl(file2.ts, 5, 29))
export let b: number;
>b : Symbol(b, Decl(file2.ts, 7, 18))
}
}
=== tests/cases/compiler/file3.ts ===
import * as x from "./file1";
>x : Symbol(x, Decl(file3.ts, 0, 6))
import "./file2";
let a: x.A;
>a : Symbol(a, Decl(file3.ts, 2, 3))
>x : Symbol(x, Decl(file3.ts, 0, 6))
>A : Symbol(x.A, Decl(file1.ts, 2, 15), Decl(file2.ts, 4, 26))
let b = a.a;
>b : Symbol(b, Decl(file3.ts, 3, 3))
>a.a : Symbol(x.A.a, Decl(file2.ts, 5, 17))
>a : Symbol(a, Decl(file3.ts, 2, 3))
>a : Symbol(x.A.a, Decl(file2.ts, 5, 17))
let c = x.B.b;
>c : Symbol(c, Decl(file3.ts, 4, 3))
>x.B.b : Symbol(x.B.b, Decl(file2.ts, 7, 18))
>x.B : Symbol(x.B, Decl(file1.ts, 3, 21), Decl(file2.ts, 5, 29))
>x : Symbol(x, Decl(file3.ts, 0, 6))
>B : Symbol(x.B, Decl(file1.ts, 3, 21), Decl(file2.ts, 5, 29))
>b : Symbol(x.B.b, Decl(file2.ts, 7, 18))
@@ -0,0 +1,69 @@
=== tests/cases/compiler/file1.ts ===
class foo {}
>foo :
namespace foo {
>foo : typeof
export class A {}
>A : A
export namespace B { export let a; }
>B : typeof B
>a : any
}
export = foo;
>foo : foo
=== tests/cases/compiler/file2.ts ===
import x = require("./file1");
>x : typeof x
x.B.b = 1;
>x.B.b = 1 : number
>x.B.b : number
>x.B : typeof x.B
>x : typeof x
>B : typeof x.B
>b : number
>1 : number
// OK - './file1' is a namespace
declare module "./file1" {
interface A { a: number }
>A : A
>a : number
namespace B {
>B : typeof B
export let b: number;
>b : number
}
}
=== tests/cases/compiler/file3.ts ===
import * as x from "./file1";
>x : typeof x
import "./file2";
let a: x.A;
>a : x.A
>x : any
>A : x.A
let b = a.a;
>b : number
>a.a : number
>a : x.A
>a : number
let c = x.B.b;
>c : number
>x.B.b : number
>x.B : typeof x.B
>x : typeof x
>B : typeof x.B
>b : number
@@ -0,0 +1,38 @@
//// [tests/cases/compiler/augmentExportEquals6_1.ts] ////
//// [file1.d.ts]
declare module "file1" {
class foo {}
namespace foo {
class A {}
}
export = foo;
}
//// [file2.ts]
/// <reference path="file1.d.ts"/>
import x = require("file1");
// OK - './file1' is a namespace
declare module "file1" {
interface A { a: number }
}
//// [file3.ts]
import * as x from "file1";
import "file2";
let a: x.A;
let b = a.a;
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
});
//// [file3.js]
define(["require", "exports", "file2"], function (require, exports) {
"use strict";
var a;
var b = a.a;
});
@@ -0,0 +1,45 @@
=== tests/cases/compiler/file1.d.ts ===
declare module "file1" {
class foo {}
>foo : Symbol(, Decl(file1.d.ts, 1, 24), Decl(file1.d.ts, 2, 16), Decl(file2.ts, 1, 28))
namespace foo {
>foo : Symbol(, Decl(file1.d.ts, 1, 24), Decl(file1.d.ts, 2, 16), Decl(file2.ts, 1, 28))
class A {}
>A : Symbol(A, Decl(file1.d.ts, 3, 19), Decl(file2.ts, 4, 24))
}
export = foo;
>foo : Symbol(foo, Decl(file1.d.ts, 1, 24), Decl(file1.d.ts, 2, 16))
}
=== tests/cases/compiler/file2.ts ===
/// <reference path="file1.d.ts"/>
import x = require("file1");
>x : Symbol(x, Decl(file2.ts, 0, 0))
// OK - './file1' is a namespace
declare module "file1" {
interface A { a: number }
>A : Symbol(A, Decl(file1.d.ts, 3, 19), Decl(file2.ts, 4, 24))
>a : Symbol(a, Decl(file2.ts, 5, 17))
}
=== tests/cases/compiler/file3.ts ===
import * as x from "file1";
>x : Symbol(x, Decl(file3.ts, 0, 6))
import "file2";
let a: x.A;
>a : Symbol(a, Decl(file3.ts, 2, 3))
>x : Symbol(x, Decl(file3.ts, 0, 6))
>A : Symbol(x.A, Decl(file1.d.ts, 3, 19), Decl(file2.ts, 4, 24))
let b = a.a;
>b : Symbol(b, Decl(file3.ts, 3, 3))
>a.a : Symbol(x.A.a, Decl(file2.ts, 5, 17))
>a : Symbol(a, Decl(file3.ts, 2, 3))
>a : Symbol(x.A.a, Decl(file2.ts, 5, 17))
@@ -0,0 +1,45 @@
=== tests/cases/compiler/file1.d.ts ===
declare module "file1" {
class foo {}
>foo :
namespace foo {
>foo : typeof
class A {}
>A : A
}
export = foo;
>foo : foo
}
=== tests/cases/compiler/file2.ts ===
/// <reference path="file1.d.ts"/>
import x = require("file1");
>x : typeof x
// OK - './file1' is a namespace
declare module "file1" {
interface A { a: number }
>A : A
>a : number
}
=== tests/cases/compiler/file3.ts ===
import * as x from "file1";
>x : typeof x
import "file2";
let a: x.A;
>a : x.A
>x : any
>A : x.A
let b = a.a;
>b : number
>a.a : number
>a : x.A
>a : number

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