diff --git a/.gitignore b/.gitignore
index c027f5873c8..05f981a0ace 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,5 @@
node_modules/
built/*
-tests/cases/*.js
-tests/cases/*/*.js
-tests/cases/*/*/*.js
-tests/cases/*/*/*/*.js
-tests/cases/*/*/*/*/*.js
-tests/cases/*.js.map
-tests/cases/*/*.js.map
-tests/cases/*/*/*.js.map
-tests/cases/*/*/*/*.js.map
-tests/cases/*/*/*/*/*.js.map
tests/cases/rwc/*
tests/cases/test262/*
tests/cases/perf/*
diff --git a/AUTHORS.md b/AUTHORS.md
index 0ade4c31221..486a15bf47f 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -8,6 +8,7 @@ TypeScript is authored by:
* Basarat Ali Syed
* Ben Duffield
* Bill Ticehurst
+* Brett Mayen
* Bryan Forbes
* Caitlin Potter
* Chris Bubernak
@@ -17,11 +18,14 @@ TypeScript is authored by:
* Dan Quirk
* Daniel Rosenwasser
* David Li
-* Dick van den Brink
-* Dirk Bäumer
+* Denis Nedelyaev
+* Dick van den Brink
+* Dirk Bäumer
+* Eyas Sharaiha
* Frank Wallis
* Gabriel Isenberg
* Gilad Peleg
+* Graeme Wicksted
* Guillaume Salles
* Harald Niesche
* Ingvar Stepanyan
@@ -31,30 +35,39 @@ TypeScript is authored by:
* Jason Ramsay
* Jed Mao
* Johannes Rieken
+* John Vilk
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Turner
* Josh Kalderimis
+* Julian Williams
* Kagami Sascha Rosylight
* Keith Mashinter
+* Ken Howard
* Kenji Imamula
* Lorant Pinter
+* Martin VÅ¡etiÄka
* Masahiro Wakame
* Max Deepfield
* Micah Zoltu
* Mohamed Hegazy
+* Nathan Shively-Sanders
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Paul van Brenk
* Pedro Maltez
* Philip Bulley
* piloopin
+* @progre
+* Punya Biswal
* Ron Buckton
* Ryan Cavanaugh
+* Ryohei Ikegami
+* Sébastien Arod
* Sheetal Nandi
* Shengping Zhong
* Shyyko Serhiy
-* Simon Hürlimann
+* Simon Hürlimann
* Solal Pirelli
* Stan Thomas
* Steve Lucco
@@ -63,8 +76,10 @@ TypeScript is authored by:
* togru
* Tomas Grubliauskas
* TruongSinh Tran-Nguyen
+* Viliv Vane
* Vladimir Matveev
* Wesley Wigham
+* York Yao
* Yui Tanglertsampan
* Zev Spitz
-* Zhengbo Li
\ No newline at end of file
+* Zhengbo Li
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 68d88854849..3a712b5619a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -36,11 +36,13 @@ Your pull request should:
The library sources are in: [src/lib](https://github.com/Microsoft/TypeScript/tree/master/src/lib)
-To build the library files, run
+Library files in `built/local/` are updated by running
```Shell
-jake lib
+jake
```
+The files in `lib/` are used to bootstrap compilation and usually do not need to be updated.
+
#### `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts`
These two files represent the DOM typings and are auto-generated. To make any modifications to them, please submit a PR to https://github.com/Microsoft/TSJS-lib-generator
diff --git a/Jakefile.js b/Jakefile.js
index 5dfbcc26d74..398b897097d 100644
--- a/Jakefile.js
+++ b/Jakefile.js
@@ -40,6 +40,7 @@ var compilerSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
+ "sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -59,6 +60,7 @@ var servicesSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
+ "sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -106,6 +108,17 @@ var serverCoreSources = [
return path.join(serverDirectory, f);
});
+var scriptSources = [
+ "tslint/booleanTriviaRule.ts",
+ "tslint/nextLineRule.ts",
+ "tslint/noNullRule.ts",
+ "tslint/preferConstRule.ts",
+ "tslint/typeOperatorSpacingRule.ts",
+ "tslint/noInOperatorRule.ts"
+].map(function (f) {
+ return path.join(scriptsDirectory, f);
+});
+
var serverSources = serverCoreSources.concat(servicesSources);
var languageServiceLibrarySources = [
@@ -365,7 +378,6 @@ file(builtGeneratedDiagnosticMessagesJSON,[generatedDiagnosticMessagesJSON], fun
desc("Generates a diagnostic file in TypeScript based on an input JSON file");
task("generate-diagnostics", [diagnosticInfoMapTs]);
-
// Publish nightly
var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js");
var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts");
@@ -466,7 +478,7 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
var nodeDefinitionsFileContents = definitionFileContents + "\r\nexport = ts;";
fs.writeFileSync(nodeDefinitionsFile, nodeDefinitionsFileContents);
- // Node package definition file to be distributed without the package. Created by replacing
+ // Node package definition file to be distributed without the package. Created by replacing
// 'ts' namespace with '"typescript"' as a module.
var nodeStandaloneDefinitionsFileContents = definitionFileContents.replace(/declare (namespace|module) ts/g, 'declare module "typescript"');
fs.writeFileSync(nodeStandaloneDefinitionsFile, nodeStandaloneDefinitionsFileContents);
@@ -864,7 +876,8 @@ var tslintRules = ([
"noNullRule",
"preferConstRule",
"booleanTriviaRule",
- "typeOperatorSpacingRule"
+ "typeOperatorSpacingRule",
+ "noInOperatorRule"
]);
var tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
@@ -875,7 +888,7 @@ var tslintRulesOutFiles = tslintRules.map(function(p) {
desc("Compiles tslint rules to js");
task("build-rules", tslintRulesOutFiles);
tslintRulesFiles.forEach(function(ruleFile, i) {
- compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
+ compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
});
function getLinterOptions() {
@@ -909,18 +922,23 @@ function lintFileAsync(options, path, cb) {
var lintTargets = compilerSources
.concat(harnessCoreSources)
- .concat(serverCoreSources);
+ .concat(serverCoreSources)
+ .concat(scriptSources);
desc("Runs tslint on the compiler sources");
task("lint", ["build-rules"], function() {
var lintOptions = getLinterOptions();
+ var failed = 0;
for (var i in lintTargets) {
var result = lintFile(lintOptions, lintTargets[i]);
if (result.failureCount > 0) {
console.log(result.output);
- fail('Linter errors.', result.failureCount);
+ failed += result.failureCount;
}
}
+ if (failed > 0) {
+ fail('Linter errors.', failed);
+ }
});
/**
@@ -937,7 +955,7 @@ function lintWatchFile(filename) {
if (event !== "change") {
return;
}
-
+
if (!lintSemaphores[filename]) {
lintSemaphores[filename] = true;
lintFileAsync(getLinterOptions(), filename, function(err, result) {
diff --git a/README.md b/README.md
index e27e7a99fa7..13e1f3e4786 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
[](https://travis-ci.org/Microsoft/TypeScript)
-[](http://badge.fury.io/js/typescript)
-[](https://npmjs.org/package/typescript)
+[](https://www.npmjs.com/package/typescript)
+[](https://www.npmjs.com/package/typescript)
# TypeScript
diff --git a/doc/TypeScript Language Specification (Change Markup).docx b/doc/TypeScript Language Specification (Change Markup).docx
index 893f2e7ed22..24e7d1b623a 100644
Binary files a/doc/TypeScript Language Specification (Change Markup).docx and b/doc/TypeScript Language Specification (Change Markup).docx differ
diff --git a/doc/TypeScript Language Specification.docx b/doc/TypeScript Language Specification.docx
index 4aaa3bf92fe..4eb94908b57 100644
Binary files a/doc/TypeScript Language Specification.docx and b/doc/TypeScript Language Specification.docx differ
diff --git a/doc/spec.md b/doc/spec.md
index fe2147be477..a7947b19926 100644
--- a/doc/spec.md
+++ b/doc/spec.md
@@ -1323,7 +1323,7 @@ x = "hello"; // Ok
x = 42; // Ok
x = test; // Error, boolean not assignable
x = test ? 5 : "five"; // Ok
-x = test ? 0 : false; // Error, number | boolean not asssignable
+x = test ? 0 : false; // Error, number | boolean not assignable
```
it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`:
diff --git a/lib/README.md b/lib/README.md
index b2837989505..583ddf91156 100644
--- a/lib/README.md
+++ b/lib/README.md
@@ -1,4 +1,4 @@
# Read this!
These files are not meant to be edited by hand.
-If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
\ No newline at end of file
+If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. Running `jake LKG` will then appropriately update the files in this directory.
diff --git a/lib/tsc.js b/lib/tsc.js
index bbbcedf0f47..87a413af729 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -665,7 +665,7 @@ var ts;
}
ts.fileExtensionIs = fileExtensionIs;
ts.supportedExtensions = [".ts", ".tsx", ".d.ts"];
- ts.moduleFileExtensions = ts.supportedExtensions;
+ ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx");
function isSupportedSourceFileName(fileName) {
if (!fileName) {
return false;
@@ -716,17 +716,16 @@ var ts;
}
function Signature(checker) {
}
+ function Node(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0;
+ this.parent = undefined;
+ }
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0;
- this.parent = undefined;
- }
- Node.prototype = { kind: kind };
- return Node;
- },
+ getNodeConstructor: function () { return Node; },
+ getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
getSignatureConstructor: function () { return Signature; }
@@ -1003,7 +1002,16 @@ var ts;
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
- _fs.writeFileSync(fileName, data, "utf8");
+ var fd;
+ try {
+ fd = _fs.openSync(fileName, "w");
+ _fs.writeSync(fd, data, undefined, "utf8");
+ }
+ finally {
+ if (fd !== undefined) {
+ _fs.closeSync(fd);
+ }
+ }
}
function getCanonicalPath(path) {
return useCaseSensitiveFileNames ? path.toLowerCase() : path;
@@ -1688,6 +1696,7 @@ var ts;
Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." },
+ Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -2148,7 +2157,7 @@ var ts;
function getCommentRanges(text, pos, trailing) {
var result;
var collecting = trailing || pos === 0;
- while (true) {
+ while (pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
case 13:
@@ -2217,6 +2226,7 @@ var ts;
}
return result;
}
+ return result;
}
function getLeadingCommentRanges(text, pos) {
return getCommentRanges(text, pos, false);
@@ -2312,7 +2322,7 @@ var ts;
error(ts.Diagnostics.Digit_expected);
}
}
- return +(text.substring(start, end));
+ return "" + +(text.substring(start, end));
}
function scanOctalDigits() {
var start = pos;
@@ -2704,7 +2714,7 @@ var ts;
return pos++, token = 36;
case 46:
if (isDigit(text.charCodeAt(pos + 1))) {
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8;
}
if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) {
@@ -2801,7 +2811,7 @@ var ts;
case 55:
case 56:
case 57:
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8;
case 58:
return pos++, token = 54;
@@ -3093,1034 +3103,6 @@ var ts;
ts.createScanner = createScanner;
})(ts || (ts = {}));
var ts;
-(function (ts) {
- ts.bindTime = 0;
- function or(state1, state2) {
- return (state1 | state2) & 2
- ? 2
- : (state1 & state2) & 8
- ? 8
- : 4;
- }
- function getModuleInstanceState(node) {
- if (node.kind === 215 || node.kind === 216) {
- return 0;
- }
- else if (ts.isConstEnumDeclaration(node)) {
- return 2;
- }
- else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) {
- return 0;
- }
- else if (node.kind === 219) {
- var state = 0;
- ts.forEachChild(node, function (n) {
- switch (getModuleInstanceState(n)) {
- case 0:
- return false;
- case 2:
- state = 2;
- return false;
- case 1:
- state = 1;
- return true;
- }
- });
- return state;
- }
- else if (node.kind === 218) {
- return getModuleInstanceState(node.body);
- }
- else {
- return 1;
- }
- }
- ts.getModuleInstanceState = getModuleInstanceState;
- var binder = createBinder();
- function bindSourceFile(file, options) {
- var start = new Date().getTime();
- binder(file, options);
- ts.bindTime += new Date().getTime() - start;
- }
- ts.bindSourceFile = bindSourceFile;
- function createBinder() {
- var file;
- var options;
- var parent;
- var container;
- var blockScopeContainer;
- var lastContainer;
- var seenThisKeyword;
- var hasExplicitReturn;
- var currentReachabilityState;
- var labelStack;
- var labelIndexMap;
- var implicitLabels;
- var inStrictMode;
- var symbolCount = 0;
- var Symbol;
- var classifiableNames;
- function bindSourceFile(f, opts) {
- file = f;
- options = opts;
- inStrictMode = !!file.externalModuleIndicator;
- classifiableNames = {};
- Symbol = ts.objectAllocator.getSymbolConstructor();
- if (!file.locals) {
- bind(file);
- file.symbolCount = symbolCount;
- file.classifiableNames = classifiableNames;
- }
- parent = undefined;
- container = undefined;
- blockScopeContainer = undefined;
- lastContainer = undefined;
- seenThisKeyword = false;
- hasExplicitReturn = false;
- labelStack = undefined;
- labelIndexMap = undefined;
- implicitLabels = undefined;
- }
- return bindSourceFile;
- function createSymbol(flags, name) {
- symbolCount++;
- return new Symbol(flags, name);
- }
- function addDeclarationToSymbol(symbol, node, symbolFlags) {
- symbol.flags |= symbolFlags;
- node.symbol = symbol;
- if (!symbol.declarations) {
- symbol.declarations = [];
- }
- symbol.declarations.push(node);
- if (symbolFlags & 1952 && !symbol.exports) {
- symbol.exports = {};
- }
- if (symbolFlags & 6240 && !symbol.members) {
- symbol.members = {};
- }
- if (symbolFlags & 107455 && !symbol.valueDeclaration) {
- symbol.valueDeclaration = node;
- }
- }
- function getDeclarationName(node) {
- if (node.name) {
- if (node.kind === 218 && node.name.kind === 9) {
- return "\"" + node.name.text + "\"";
- }
- if (node.name.kind === 136) {
- var nameExpression = node.name.expression;
- ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
- return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
- }
- return node.name.text;
- }
- switch (node.kind) {
- case 144:
- return "__constructor";
- case 152:
- case 147:
- return "__call";
- case 153:
- case 148:
- return "__new";
- case 149:
- return "__index";
- case 228:
- return "__export";
- case 227:
- return node.isExportEquals ? "export=" : "default";
- case 213:
- case 214:
- return node.flags & 512 ? "default" : undefined;
- }
- }
- function getDisplayName(node) {
- return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node);
- }
- function declareSymbol(symbolTable, parent, node, includes, excludes) {
- ts.Debug.assert(!ts.hasDynamicName(node));
- var isDefaultExport = node.flags & 512;
- var name = isDefaultExport && parent ? "default" : getDeclarationName(node);
- var symbol;
- if (name !== undefined) {
- symbol = ts.hasProperty(symbolTable, name)
- ? symbolTable[name]
- : (symbolTable[name] = createSymbol(0, name));
- if (name && (includes & 788448)) {
- classifiableNames[name] = name;
- }
- if (symbol.flags & excludes) {
- if (node.name) {
- node.name.parent = node;
- }
- var message = symbol.flags & 2
- ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
- : ts.Diagnostics.Duplicate_identifier_0;
- ts.forEach(symbol.declarations, function (declaration) {
- if (declaration.flags & 512) {
- message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
- }
- });
- ts.forEach(symbol.declarations, function (declaration) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
- });
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
- symbol = createSymbol(0, name);
- }
- }
- else {
- symbol = createSymbol(0, "__missing");
- }
- addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
- return symbol;
- }
- function declareModuleMember(node, symbolFlags, symbolExcludes) {
- var hasExportModifier = ts.getCombinedNodeFlags(node) & 2;
- if (symbolFlags & 8388608) {
- if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) {
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- }
- else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- else {
- if (hasExportModifier || container.flags & 131072) {
- var exportKind = (symbolFlags & 107455 ? 1048576 : 0) |
- (symbolFlags & 793056 ? 2097152 : 0) |
- (symbolFlags & 1536 ? 4194304 : 0);
- var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
- local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- node.localSymbol = local;
- return local;
- }
- else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- }
- function bindChildren(node) {
- var saveParent = parent;
- var saveContainer = container;
- var savedBlockScopeContainer = blockScopeContainer;
- parent = node;
- var containerFlags = getContainerFlags(node);
- if (containerFlags & 1) {
- container = blockScopeContainer = node;
- if (containerFlags & 4) {
- container.locals = {};
- }
- addToContainerChain(container);
- }
- else if (containerFlags & 2) {
- blockScopeContainer = node;
- blockScopeContainer.locals = undefined;
- }
- var savedReachabilityState;
- var savedLabelStack;
- var savedLabels;
- var savedImplicitLabels;
- var savedHasExplicitReturn;
- var kind = node.kind;
- var flags = node.flags;
- flags &= ~1572864;
- if (kind === 215) {
- seenThisKeyword = false;
- }
- var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind);
- if (saveState) {
- savedReachabilityState = currentReachabilityState;
- savedLabelStack = labelStack;
- savedLabels = labelIndexMap;
- savedImplicitLabels = implicitLabels;
- savedHasExplicitReturn = hasExplicitReturn;
- currentReachabilityState = 2;
- hasExplicitReturn = false;
- labelStack = labelIndexMap = implicitLabels = undefined;
- }
- bindReachableStatement(node);
- if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) {
- flags |= 524288;
- if (hasExplicitReturn) {
- flags |= 1048576;
- }
- }
- if (kind === 215) {
- flags = seenThisKeyword ? flags | 262144 : flags & ~262144;
- }
- node.flags = flags;
- if (saveState) {
- hasExplicitReturn = savedHasExplicitReturn;
- currentReachabilityState = savedReachabilityState;
- labelStack = savedLabelStack;
- labelIndexMap = savedLabels;
- implicitLabels = savedImplicitLabels;
- }
- container = saveContainer;
- parent = saveParent;
- blockScopeContainer = savedBlockScopeContainer;
- }
- function bindReachableStatement(node) {
- if (checkUnreachable(node)) {
- ts.forEachChild(node, bind);
- return;
- }
- switch (node.kind) {
- case 198:
- bindWhileStatement(node);
- break;
- case 197:
- bindDoStatement(node);
- break;
- case 199:
- bindForStatement(node);
- break;
- case 200:
- case 201:
- bindForInOrForOfStatement(node);
- break;
- case 196:
- bindIfStatement(node);
- break;
- case 204:
- case 208:
- bindReturnOrThrow(node);
- break;
- case 203:
- case 202:
- bindBreakOrContinueStatement(node);
- break;
- case 209:
- bindTryStatement(node);
- break;
- case 206:
- bindSwitchStatement(node);
- break;
- case 220:
- bindCaseBlock(node);
- break;
- case 207:
- bindLabeledStatement(node);
- break;
- default:
- ts.forEachChild(node, bind);
- break;
- }
- }
- function bindWhileStatement(n) {
- var preWhileState = n.expression.kind === 84 ? 4 : currentReachabilityState;
- var postWhileState = n.expression.kind === 99 ? 4 : currentReachabilityState;
- bind(n.expression);
- currentReachabilityState = preWhileState;
- var postWhileLabel = pushImplicitLabel();
- bind(n.statement);
- popImplicitLabel(postWhileLabel, postWhileState);
- }
- function bindDoStatement(n) {
- var preDoState = currentReachabilityState;
- var postDoLabel = pushImplicitLabel();
- bind(n.statement);
- var postDoState = n.expression.kind === 99 ? 4 : preDoState;
- popImplicitLabel(postDoLabel, postDoState);
- bind(n.expression);
- }
- function bindForStatement(n) {
- var preForState = currentReachabilityState;
- var postForLabel = pushImplicitLabel();
- bind(n.initializer);
- bind(n.condition);
- bind(n.incrementor);
- bind(n.statement);
- var isInfiniteLoop = (!n.condition || n.condition.kind === 99);
- var postForState = isInfiniteLoop ? 4 : preForState;
- popImplicitLabel(postForLabel, postForState);
- }
- function bindForInOrForOfStatement(n) {
- var preStatementState = currentReachabilityState;
- var postStatementLabel = pushImplicitLabel();
- bind(n.initializer);
- bind(n.expression);
- bind(n.statement);
- popImplicitLabel(postStatementLabel, preStatementState);
- }
- function bindIfStatement(n) {
- var ifTrueState = n.expression.kind === 84 ? 4 : currentReachabilityState;
- var ifFalseState = n.expression.kind === 99 ? 4 : currentReachabilityState;
- currentReachabilityState = ifTrueState;
- bind(n.expression);
- bind(n.thenStatement);
- if (n.elseStatement) {
- var preElseState = currentReachabilityState;
- currentReachabilityState = ifFalseState;
- bind(n.elseStatement);
- currentReachabilityState = or(currentReachabilityState, preElseState);
- }
- else {
- currentReachabilityState = or(currentReachabilityState, ifFalseState);
- }
- }
- function bindReturnOrThrow(n) {
- bind(n.expression);
- if (n.kind === 204) {
- hasExplicitReturn = true;
- }
- currentReachabilityState = 4;
- }
- function bindBreakOrContinueStatement(n) {
- bind(n.label);
- var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4);
- if (isValidJump) {
- currentReachabilityState = 4;
- }
- }
- function bindTryStatement(n) {
- var preTryState = currentReachabilityState;
- bind(n.tryBlock);
- var postTryState = currentReachabilityState;
- currentReachabilityState = preTryState;
- bind(n.catchClause);
- var postCatchState = currentReachabilityState;
- currentReachabilityState = preTryState;
- bind(n.finallyBlock);
- currentReachabilityState = or(postTryState, postCatchState);
- }
- function bindSwitchStatement(n) {
- var preSwitchState = currentReachabilityState;
- var postSwitchLabel = pushImplicitLabel();
- bind(n.expression);
- bind(n.caseBlock);
- var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; });
- var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState;
- popImplicitLabel(postSwitchLabel, postSwitchState);
- }
- function bindCaseBlock(n) {
- var startState = currentReachabilityState;
- for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) {
- var clause = _a[_i];
- currentReachabilityState = startState;
- bind(clause);
- if (clause.statements.length && currentReachabilityState === 2 && options.noFallthroughCasesInSwitch) {
- errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
- }
- }
- }
- function bindLabeledStatement(n) {
- bind(n.label);
- var ok = pushNamedLabel(n.label);
- bind(n.statement);
- if (ok) {
- popNamedLabel(n.label, currentReachabilityState);
- }
- }
- function getContainerFlags(node) {
- switch (node.kind) {
- case 186:
- case 214:
- case 215:
- case 217:
- case 155:
- case 165:
- return 1;
- case 147:
- case 148:
- case 149:
- case 143:
- case 142:
- case 213:
- case 144:
- case 145:
- case 146:
- case 152:
- case 153:
- case 173:
- case 174:
- case 218:
- case 248:
- case 216:
- return 5;
- case 244:
- case 199:
- case 200:
- case 201:
- case 220:
- return 2;
- case 192:
- return ts.isFunctionLike(node.parent) ? 0 : 2;
- }
- return 0;
- }
- function addToContainerChain(next) {
- if (lastContainer) {
- lastContainer.nextContainer = next;
- }
- lastContainer = next;
- }
- function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
- declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes);
- }
- function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) {
- switch (container.kind) {
- case 218:
- return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 248:
- return declareSourceFileMember(node, symbolFlags, symbolExcludes);
- case 186:
- case 214:
- return declareClassMember(node, symbolFlags, symbolExcludes);
- case 217:
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- case 155:
- case 165:
- case 215:
- return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- case 152:
- case 153:
- case 147:
- case 148:
- case 149:
- case 143:
- case 142:
- case 144:
- case 145:
- case 146:
- case 213:
- case 173:
- case 174:
- case 216:
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- function declareClassMember(node, symbolFlags, symbolExcludes) {
- return node.flags & 64
- ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
- : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- }
- function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
- return ts.isExternalModule(file)
- ? declareModuleMember(node, symbolFlags, symbolExcludes)
- : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- function hasExportDeclarations(node) {
- var body = node.kind === 248 ? node : node.body;
- if (body.kind === 248 || body.kind === 219) {
- for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
- var stat = _a[_i];
- if (stat.kind === 228 || stat.kind === 227) {
- return true;
- }
- }
- }
- return false;
- }
- function setExportContextFlag(node) {
- if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) {
- node.flags |= 131072;
- }
- else {
- node.flags &= ~131072;
- }
- }
- function bindModuleDeclaration(node) {
- setExportContextFlag(node);
- if (node.name.kind === 9) {
- declareSymbolAndAddToSymbolTable(node, 512, 106639);
- }
- else {
- var state = getModuleInstanceState(node);
- if (state === 0) {
- declareSymbolAndAddToSymbolTable(node, 1024, 0);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 512, 106639);
- if (node.symbol.flags & (16 | 32 | 256)) {
- node.symbol.constEnumOnlyModule = false;
- }
- else {
- var currentModuleIsConstEnumOnly = state === 2;
- if (node.symbol.constEnumOnlyModule === undefined) {
- node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
- }
- else {
- node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
- }
- }
- }
- }
- }
- function bindFunctionOrConstructorType(node) {
- var symbol = createSymbol(131072, getDeclarationName(node));
- addDeclarationToSymbol(symbol, node, 131072);
- var typeLiteralSymbol = createSymbol(2048, "__type");
- addDeclarationToSymbol(typeLiteralSymbol, node, 2048);
- typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a);
- var _a;
- }
- function bindObjectLiteralExpression(node) {
- if (inStrictMode) {
- var seen = {};
- for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
- var prop = _a[_i];
- if (prop.name.kind !== 69) {
- continue;
- }
- var identifier = prop.name;
- var currentKind = prop.kind === 245 || prop.kind === 246 || prop.kind === 143
- ? 1
- : 2;
- var existingKind = seen[identifier.text];
- if (!existingKind) {
- seen[identifier.text] = currentKind;
- continue;
- }
- if (currentKind === 1 && existingKind === 1) {
- var span = ts.getErrorSpanForNode(file, identifier);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
- }
- }
- }
- return bindAnonymousDeclaration(node, 4096, "__object");
- }
- function bindAnonymousDeclaration(node, symbolFlags, name) {
- var symbol = createSymbol(symbolFlags, name);
- addDeclarationToSymbol(symbol, node, symbolFlags);
- }
- function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
- switch (blockScopeContainer.kind) {
- case 218:
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- case 248:
- if (ts.isExternalModule(container)) {
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- }
- default:
- if (!blockScopeContainer.locals) {
- blockScopeContainer.locals = {};
- addToContainerChain(blockScopeContainer);
- }
- declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- function bindBlockScopedVariableDeclaration(node) {
- bindBlockScopedDeclaration(node, 2, 107455);
- }
- function checkStrictModeIdentifier(node) {
- if (inStrictMode &&
- node.originalKeywordKind >= 106 &&
- node.originalKeywordKind <= 114 &&
- !ts.isIdentifierName(node)) {
- if (!file.parseDiagnostics.length) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
- }
- }
- }
- function getStrictModeIdentifierMessage(node) {
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
- }
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
- }
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
- }
- function checkStrictModeBinaryExpression(node) {
- if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
- checkStrictModeEvalOrArguments(node, node.left);
- }
- }
- function checkStrictModeCatchClause(node) {
- if (inStrictMode && node.variableDeclaration) {
- checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
- }
- }
- function checkStrictModeDeleteExpression(node) {
- if (inStrictMode && node.expression.kind === 69) {
- var span = ts.getErrorSpanForNode(file, node.expression);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
- }
- }
- function isEvalOrArgumentsIdentifier(node) {
- return node.kind === 69 &&
- (node.text === "eval" || node.text === "arguments");
- }
- function checkStrictModeEvalOrArguments(contextNode, name) {
- if (name && name.kind === 69) {
- var identifier = name;
- if (isEvalOrArgumentsIdentifier(identifier)) {
- var span = ts.getErrorSpanForNode(file, name);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));
- }
- }
- }
- function getStrictModeEvalOrArgumentsMessage(node) {
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
- }
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
- }
- return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
- }
- function checkStrictModeFunctionName(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.name);
- }
- }
- function checkStrictModeNumericLiteral(node) {
- if (inStrictMode && node.flags & 32768) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
- }
- }
- function checkStrictModePostfixUnaryExpression(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.operand);
- }
- }
- function checkStrictModePrefixUnaryExpression(node) {
- if (inStrictMode) {
- if (node.operator === 41 || node.operator === 42) {
- checkStrictModeEvalOrArguments(node, node.operand);
- }
- }
- }
- function checkStrictModeWithStatement(node) {
- if (inStrictMode) {
- errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
- }
- }
- function errorOnFirstToken(node, message, arg0, arg1, arg2) {
- var span = ts.getSpanOfTokenAtPosition(file, node.pos);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
- }
- function getDestructuringParameterName(node) {
- return "__" + ts.indexOf(node.parent.parameters, node);
- }
- function bind(node) {
- if (!node) {
- return;
- }
- node.parent = parent;
- var savedInStrictMode = inStrictMode;
- if (!savedInStrictMode) {
- updateStrictMode(node);
- }
- bindWorker(node);
- bindChildren(node);
- inStrictMode = savedInStrictMode;
- }
- function updateStrictMode(node) {
- switch (node.kind) {
- case 248:
- case 219:
- updateStrictModeStatementList(node.statements);
- return;
- case 192:
- if (ts.isFunctionLike(node.parent)) {
- updateStrictModeStatementList(node.statements);
- }
- return;
- case 214:
- case 186:
- inStrictMode = true;
- return;
- }
- }
- function updateStrictModeStatementList(statements) {
- for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
- var statement = statements_1[_i];
- if (!ts.isPrologueDirective(statement)) {
- return;
- }
- if (isUseStrictPrologueDirective(statement)) {
- inStrictMode = true;
- return;
- }
- }
- }
- function isUseStrictPrologueDirective(node) {
- var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression);
- return nodeText === "\"use strict\"" || nodeText === "'use strict'";
- }
- function bindWorker(node) {
- switch (node.kind) {
- case 69:
- return checkStrictModeIdentifier(node);
- case 181:
- return checkStrictModeBinaryExpression(node);
- case 244:
- return checkStrictModeCatchClause(node);
- case 175:
- return checkStrictModeDeleteExpression(node);
- case 8:
- return checkStrictModeNumericLiteral(node);
- case 180:
- return checkStrictModePostfixUnaryExpression(node);
- case 179:
- return checkStrictModePrefixUnaryExpression(node);
- case 205:
- return checkStrictModeWithStatement(node);
- case 97:
- seenThisKeyword = true;
- return;
- case 137:
- return declareSymbolAndAddToSymbolTable(node, 262144, 530912);
- case 138:
- return bindParameter(node);
- case 211:
- case 163:
- return bindVariableDeclarationOrBindingElement(node);
- case 141:
- case 140:
- return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455);
- case 245:
- case 246:
- return bindPropertyOrMethodOrAccessor(node, 4, 107455);
- case 247:
- return bindPropertyOrMethodOrAccessor(node, 8, 107455);
- case 147:
- case 148:
- case 149:
- return declareSymbolAndAddToSymbolTable(node, 131072, 0);
- case 143:
- case 142:
- return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263);
- case 213:
- checkStrictModeFunctionName(node);
- return declareSymbolAndAddToSymbolTable(node, 16, 106927);
- case 144:
- return declareSymbolAndAddToSymbolTable(node, 16384, 0);
- case 145:
- return bindPropertyOrMethodOrAccessor(node, 32768, 41919);
- case 146:
- return bindPropertyOrMethodOrAccessor(node, 65536, 74687);
- case 152:
- case 153:
- return bindFunctionOrConstructorType(node);
- case 155:
- return bindAnonymousDeclaration(node, 2048, "__type");
- case 165:
- return bindObjectLiteralExpression(node);
- case 173:
- case 174:
- checkStrictModeFunctionName(node);
- var bindingName = node.name ? node.name.text : "__function";
- return bindAnonymousDeclaration(node, 16, bindingName);
- case 186:
- case 214:
- return bindClassLikeDeclaration(node);
- case 215:
- return bindBlockScopedDeclaration(node, 64, 792960);
- case 216:
- return bindBlockScopedDeclaration(node, 524288, 793056);
- case 217:
- return bindEnumDeclaration(node);
- case 218:
- return bindModuleDeclaration(node);
- case 221:
- case 224:
- case 226:
- case 230:
- return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608);
- case 223:
- return bindImportClause(node);
- case 228:
- return bindExportDeclaration(node);
- case 227:
- return bindExportAssignment(node);
- case 248:
- return bindSourceFileIfExternalModule();
- }
- }
- function bindSourceFileIfExternalModule() {
- setExportContextFlag(file);
- if (ts.isExternalModule(file)) {
- bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\"");
- }
- }
- function bindExportAssignment(node) {
- if (!container.symbol || !container.symbol.exports) {
- bindAnonymousDeclaration(node, 8388608, getDeclarationName(node));
- }
- else if (node.expression.kind === 69) {
- declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608);
- }
- else {
- declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608);
- }
- }
- function bindExportDeclaration(node) {
- if (!container.symbol || !container.symbol.exports) {
- bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node));
- }
- else if (!node.exportClause) {
- declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0);
- }
- }
- function bindImportClause(node) {
- if (node.name) {
- declareSymbolAndAddToSymbolTable(node, 8388608, 8388608);
- }
- }
- function bindClassLikeDeclaration(node) {
- if (node.kind === 214) {
- bindBlockScopedDeclaration(node, 32, 899519);
- }
- else {
- var bindingName = node.name ? node.name.text : "__class";
- bindAnonymousDeclaration(node, 32, bindingName);
- if (node.name) {
- classifiableNames[node.name.text] = node.name.text;
- }
- }
- var symbol = node.symbol;
- var prototypeSymbol = createSymbol(4 | 134217728, "prototype");
- if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) {
- if (node.name) {
- node.name.parent = node;
- }
- file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
- }
- symbol.exports[prototypeSymbol.name] = prototypeSymbol;
- prototypeSymbol.parent = symbol;
- }
- function bindEnumDeclaration(node) {
- return ts.isConst(node)
- ? bindBlockScopedDeclaration(node, 128, 899967)
- : bindBlockScopedDeclaration(node, 256, 899327);
- }
- function bindVariableDeclarationOrBindingElement(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.name);
- }
- if (!ts.isBindingPattern(node.name)) {
- if (ts.isBlockOrCatchScoped(node)) {
- bindBlockScopedVariableDeclaration(node);
- }
- else if (ts.isParameterDeclaration(node)) {
- declareSymbolAndAddToSymbolTable(node, 1, 107455);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1, 107454);
- }
- }
- }
- function bindParameter(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.name);
- }
- if (ts.isBindingPattern(node.name)) {
- bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node));
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1, 107455);
- }
- if (node.flags & 56 &&
- node.parent.kind === 144 &&
- ts.isClassLike(node.parent.parent)) {
- var classDeclaration = node.parent.parent;
- declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455);
- }
- }
- function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
- return ts.hasDynamicName(node)
- ? bindAnonymousDeclaration(node, symbolFlags, "__computed")
- : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
- }
- function pushNamedLabel(name) {
- initializeReachabilityStateIfNecessary();
- if (ts.hasProperty(labelIndexMap, name.text)) {
- return false;
- }
- labelIndexMap[name.text] = labelStack.push(1) - 1;
- return true;
- }
- function pushImplicitLabel() {
- initializeReachabilityStateIfNecessary();
- var index = labelStack.push(1) - 1;
- implicitLabels.push(index);
- return index;
- }
- function popNamedLabel(label, outerState) {
- var index = labelIndexMap[label.text];
- ts.Debug.assert(index !== undefined);
- ts.Debug.assert(labelStack.length == index + 1);
- labelIndexMap[label.text] = undefined;
- setCurrentStateAtLabel(labelStack.pop(), outerState, label);
- }
- function popImplicitLabel(implicitLabelIndex, outerState) {
- if (labelStack.length !== implicitLabelIndex + 1) {
- ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex);
- }
- var i = implicitLabels.pop();
- if (implicitLabelIndex !== i) {
- ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex);
- }
- setCurrentStateAtLabel(labelStack.pop(), outerState, undefined);
- }
- function setCurrentStateAtLabel(innerMergedState, outerState, label) {
- if (innerMergedState === 1) {
- if (label && !options.allowUnusedLabels) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label));
- }
- currentReachabilityState = outerState;
- }
- else {
- currentReachabilityState = or(innerMergedState, outerState);
- }
- }
- function jumpToLabel(label, outerState) {
- initializeReachabilityStateIfNecessary();
- var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels);
- if (index === undefined) {
- return false;
- }
- var stateAtLabel = labelStack[index];
- labelStack[index] = stateAtLabel === 1 ? outerState : or(stateAtLabel, outerState);
- return true;
- }
- function checkUnreachable(node) {
- switch (currentReachabilityState) {
- case 4:
- var reportError = ts.isStatement(node) ||
- node.kind === 214 ||
- (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) ||
- (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
- if (reportError) {
- currentReachabilityState = 8;
- var reportUnreachableCode = !options.allowUnreachableCode &&
- !ts.isInAmbientContext(node) &&
- (node.kind !== 193 ||
- ts.getCombinedNodeFlags(node.declarationList) & 24576 ||
- ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
- if (reportUnreachableCode) {
- errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected);
- }
- }
- case 8:
- return true;
- default:
- return false;
- }
- function shouldReportErrorOnModuleDeclaration(node) {
- var instanceState = getModuleInstanceState(node);
- return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums);
- }
- }
- function initializeReachabilityStateIfNecessary() {
- if (labelIndexMap) {
- return;
- }
- currentReachabilityState = 2;
- labelIndexMap = {};
- labelStack = [];
- implicitLabels = [];
- }
- }
-})(ts || (ts = {}));
-var ts;
(function (ts) {
function getDeclarationOfKind(symbol, kind) {
var declarations = symbol.declarations;
@@ -4396,6 +3378,10 @@ var ts;
return file.externalModuleIndicator !== undefined;
}
ts.isExternalModule = isExternalModule;
+ function isExternalOrCommonJsModule(file) {
+ return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
+ }
+ ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
function isDeclarationFile(file) {
return (file.flags & 4096) !== 0;
}
@@ -4442,18 +3428,26 @@ var ts;
return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
+ function getLeadingCommentRangesOfNodeFromText(node, text) {
+ return ts.getLeadingCommentRanges(text, node.pos);
+ }
+ ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText;
function getJsDocComments(node, sourceFileOfNode) {
- var commentRanges = (node.kind === 138 || node.kind === 137) ?
- ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
- getLeadingCommentRangesOfNode(node, sourceFileOfNode);
- return ts.filter(commentRanges, isJsDocComment);
- function isJsDocComment(comment) {
- return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47;
- }
+ return getJsDocCommentsFromText(node, sourceFileOfNode.text);
}
ts.getJsDocComments = getJsDocComments;
+ function getJsDocCommentsFromText(node, text) {
+ var commentRanges = (node.kind === 138 || node.kind === 137) ?
+ ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
+ getLeadingCommentRangesOfNodeFromText(node, text);
+ return ts.filter(commentRanges, isJsDocComment);
+ function isJsDocComment(comment) {
+ return text.charCodeAt(comment.pos + 1) === 42 &&
+ text.charCodeAt(comment.pos + 2) === 42 &&
+ text.charCodeAt(comment.pos + 3) !== 47;
+ }
+ }
+ ts.getJsDocCommentsFromText = getJsDocCommentsFromText;
ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/;
ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
function isTypeNode(node) {
@@ -4982,6 +3976,41 @@ var ts;
return node.kind === 221 && node.moduleReference.kind !== 232;
}
ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
+ function isSourceFileJavaScript(file) {
+ return isInJavaScriptFile(file);
+ }
+ ts.isSourceFileJavaScript = isSourceFileJavaScript;
+ function isInJavaScriptFile(node) {
+ return node && !!(node.parserContextFlags & 32);
+ }
+ ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isRequireCall(expression) {
+ return expression.kind === 168 &&
+ expression.expression.kind === 69 &&
+ expression.expression.text === "require" &&
+ expression.arguments.length === 1 &&
+ expression.arguments[0].kind === 9;
+ }
+ ts.isRequireCall = isRequireCall;
+ function isExportsPropertyAssignment(expression) {
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181) &&
+ (expression.operatorToken.kind === 56) &&
+ (expression.left.kind === 166) &&
+ (expression.left.expression.kind === 69) &&
+ ((expression.left.expression).text === "exports");
+ }
+ ts.isExportsPropertyAssignment = isExportsPropertyAssignment;
+ function isModuleExportsAssignment(expression) {
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181) &&
+ (expression.operatorToken.kind === 56) &&
+ (expression.left.kind === 166) &&
+ (expression.left.expression.kind === 69) &&
+ ((expression.left.expression).text === "module") &&
+ (expression.left.name.text === "exports");
+ }
+ ts.isModuleExportsAssignment = isModuleExportsAssignment;
function getExternalModuleName(node) {
if (node.kind === 222) {
return node.moduleSpecifier;
@@ -5293,8 +4322,8 @@ var ts;
function getFileReferenceFromReferencePath(comment, commentRange) {
var simpleReferenceRegEx = /^\/\/\/\s*/gim;
- if (simpleReferenceRegEx.exec(comment)) {
- if (isNoDefaultLibRegEx.exec(comment)) {
+ if (simpleReferenceRegEx.test(comment)) {
+ if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
@@ -5336,12 +4365,20 @@ var ts;
return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node);
}
ts.isAsyncFunctionLike = isAsyncFunctionLike;
+ function isStringOrNumericLiteral(kind) {
+ return kind === 9 || kind === 8;
+ }
+ ts.isStringOrNumericLiteral = isStringOrNumericLiteral;
function hasDynamicName(declaration) {
- return declaration.name &&
- declaration.name.kind === 136 &&
- !isWellKnownSymbolSyntactically(declaration.name.expression);
+ return declaration.name && isDynamicName(declaration.name);
}
ts.hasDynamicName = hasDynamicName;
+ function isDynamicName(name) {
+ return name.kind === 136 &&
+ !isStringOrNumericLiteral(name.expression.kind) &&
+ !isWellKnownSymbolSyntactically(name.expression);
+ }
+ ts.isDynamicName = isDynamicName;
function isWellKnownSymbolSyntactically(node) {
return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
}
@@ -5562,11 +4599,11 @@ var ts;
}
ts.getIndentSize = getIndentSize;
function createTextWriter(newLine) {
- var output = "";
- var indent = 0;
- var lineStart = true;
- var lineCount = 0;
- var linePos = 0;
+ var output;
+ var indent;
+ var lineStart;
+ var lineCount;
+ var linePos;
function write(s) {
if (s && s.length) {
if (lineStart) {
@@ -5576,6 +4613,13 @@ var ts;
output += s;
}
}
+ function reset() {
+ output = "";
+ indent = 0;
+ lineStart = true;
+ lineCount = 0;
+ linePos = 0;
+ }
function rawWrite(s) {
if (s !== undefined) {
if (lineStart) {
@@ -5602,9 +4646,10 @@ var ts;
lineStart = true;
}
}
- function writeTextOfNode(sourceFile, node) {
- write(getSourceTextOfNodeFromSourceFile(sourceFile, node));
+ function writeTextOfNode(text, node) {
+ write(getTextOfNodeFromSourceText(text, node));
}
+ reset();
return {
write: write,
rawWrite: rawWrite,
@@ -5617,10 +4662,17 @@ var ts;
getTextPos: function () { return output.length; },
getLine: function () { return lineCount + 1; },
getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; },
- getText: function () { return output; }
+ getText: function () { return output; },
+ reset: reset
};
}
ts.createTextWriter = createTextWriter;
+ function getExternalModuleNameFromPath(host, fileName) {
+ var dir = host.getCurrentDirectory();
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, false);
+ return ts.removeFileExtension(relativePath);
+ }
+ ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
var compilerOptions = host.getCompilerOptions();
var emitOutputFilePathWithoutExtension;
@@ -5649,6 +4701,10 @@ var ts;
return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
ts.getLineOfLocalPosition = getLineOfLocalPosition;
+ function getLineOfLocalPositionFromLineMap(lineMap, pos) {
+ return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
+ }
+ ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
function getFirstConstructorWithBody(node) {
return ts.forEach(node.members, function (member) {
if (member.kind === 144 && nodeIsPresent(member.body)) {
@@ -5719,21 +4775,21 @@ var ts;
};
}
ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
- function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) {
+ function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
- getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) {
+ getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
}
}
ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
- function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) {
+ function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) {
var emitLeadingSpace = !trailingSeparator;
ts.forEach(comments, function (comment) {
if (emitLeadingSpace) {
writer.write(" ");
emitLeadingSpace = false;
}
- writeComment(currentSourceFile, writer, comment, newLine);
+ writeComment(text, lineMap, writer, comment, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
@@ -5746,16 +4802,16 @@ var ts;
});
}
ts.emitComments = emitComments;
- function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) {
+ function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
var leadingComments;
var currentDetachedCommentInfo;
if (removeComments) {
if (node.pos === 0) {
- leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment);
+ leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment);
}
}
else {
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ leadingComments = ts.getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
var detachedComments = [];
@@ -5763,8 +4819,8 @@ var ts;
for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
var comment = leadingComments_1[_i];
if (lastComment) {
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end);
- var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos);
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
+ var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
if (commentLine >= lastCommentLine + 2) {
break;
}
@@ -5773,37 +4829,37 @@ var ts;
lastComment = comment;
}
if (detachedComments.length) {
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end);
- var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end);
+ var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
- emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
- emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment);
+ emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
+ emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end };
}
}
}
return currentDetachedCommentInfo;
function isPinnedComment(comment) {
- return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 33;
+ return text.charCodeAt(comment.pos + 1) === 42 &&
+ text.charCodeAt(comment.pos + 2) === 33;
}
}
ts.emitDetachedComments = emitDetachedComments;
- function writeCommentRange(currentSourceFile, writer, comment, newLine) {
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42) {
- var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
- var lineCount = ts.getLineStarts(currentSourceFile).length;
+ function writeCommentRange(text, lineMap, writer, comment, newLine) {
+ if (text.charCodeAt(comment.pos + 1) === 42) {
+ var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos);
+ var lineCount = lineMap.length;
var firstCommentLineIndent;
for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
var nextLineStart = (currentLine + 1) === lineCount
- ? currentSourceFile.text.length + 1
- : getStartPositionOfLine(currentLine + 1, currentSourceFile);
+ ? text.length + 1
+ : lineMap[currentLine + 1];
if (pos !== comment.pos) {
if (firstCommentLineIndent === undefined) {
- firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
+ firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos);
}
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
- var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
+ var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
@@ -5817,40 +4873,40 @@ var ts;
writer.rawWrite("");
}
}
- writeTrimmedCurrentLine(pos, nextLineStart);
+ writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
- writer.write(currentSourceFile.text.substring(comment.pos, comment.end));
- }
- function writeTrimmedCurrentLine(pos, nextLineStart) {
- var end = Math.min(comment.end, nextLineStart - 1);
- var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
- if (currentLineText) {
- writer.write(currentLineText);
- if (end !== comment.end) {
- writer.writeLine();
- }
- }
- else {
- writer.writeLiteral(newLine);
- }
- }
- function calculateIndent(pos, end) {
- var currentLineIndent = 0;
- for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
- if (currentSourceFile.text.charCodeAt(pos) === 9) {
- currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
- }
- else {
- currentLineIndent++;
- }
- }
- return currentLineIndent;
+ writer.write(text.substring(comment.pos, comment.end));
}
}
ts.writeCommentRange = writeCommentRange;
+ function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) {
+ var end = Math.min(comment.end, nextLineStart - 1);
+ var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
+ if (currentLineText) {
+ writer.write(currentLineText);
+ if (end !== comment.end) {
+ writer.writeLine();
+ }
+ }
+ else {
+ writer.writeLiteral(newLine);
+ }
+ }
+ function calculateIndent(text, pos, end) {
+ var currentLineIndent = 0;
+ for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) {
+ if (text.charCodeAt(pos) === 9) {
+ currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
+ }
+ else {
+ currentLineIndent++;
+ }
+ }
+ return currentLineIndent;
+ }
function modifierToFlag(token) {
switch (token) {
case 113: return 64;
@@ -5944,14 +5000,14 @@ var ts;
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
- function isJavaScript(fileName) {
- return ts.fileExtensionIs(fileName, ".js");
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isJavaScript = isJavaScript;
- function isTsx(fileName) {
- return ts.fileExtensionIs(fileName, ".tsx");
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function allowsJsxExpressions(fileName) {
+ return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isTsx = isTsx;
+ ts.allowsJsxExpressions = allowsJsxExpressions;
function getExpandedCharCodes(input) {
var output = [];
var length = input.length;
@@ -6161,14 +5217,16 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var nodeConstructors = new Array(272);
ts.parseTime = 0;
- function getNodeConstructor(kind) {
- return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind));
- }
- ts.getNodeConstructor = getNodeConstructor;
+ var NodeConstructor;
+ var SourceFileConstructor;
function createNode(kind, pos, end) {
- return new (getNodeConstructor(kind))(pos, end);
+ if (kind === 248) {
+ return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
+ }
+ else {
+ return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
+ }
}
ts.createNode = createNode;
function visitNode(cbNode, node) {
@@ -6567,6 +5625,8 @@ var ts;
(function (Parser) {
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 1 | 4;
+ var NodeConstructor;
+ var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
var syntaxCursor;
@@ -6579,13 +5639,16 @@ var ts;
var contextFlags;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) {
- initializeState(fileName, _sourceText, languageVersion, _syntaxCursor);
+ var isJavaScriptFile = ts.hasJavaScriptFileExtension(fileName) || _sourceText.lastIndexOf("// @language=javascript", 0) === 0;
+ initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes);
clearState();
return result;
}
Parser.parseSourceFile = parseSourceFile;
- function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) {
+ function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) {
+ NodeConstructor = ts.objectAllocator.getNodeConstructor();
+ SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
parseDiagnostics = [];
@@ -6593,12 +5656,12 @@ var ts;
identifiers = {};
identifierCount = 0;
nodeCount = 0;
- contextFlags = ts.isJavaScript(fileName) ? 32 : 0;
+ contextFlags = isJavaScriptFile ? 32 : 0;
parseErrorBeforeNextFinishedNode = false;
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
- scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 : 0);
+ scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 : 0);
}
function clearState() {
scanner.setText("");
@@ -6611,6 +5674,9 @@ var ts;
}
function parseSourceFileWorker(fileName, languageVersion, setParentNodes) {
sourceFile = createSourceFile(fileName, languageVersion);
+ if (contextFlags & 32) {
+ sourceFile.parserContextFlags = 32;
+ }
token = nextToken();
processReferenceComments(sourceFile);
sourceFile.statements = parseList(0, parseStatement);
@@ -6624,7 +5690,7 @@ var ts;
if (setParentNodes) {
fixupParentReferences(sourceFile);
}
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
addJSDocComments();
}
return sourceFile;
@@ -6670,15 +5736,14 @@ var ts;
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion) {
- var sourceFile = createNode(248, 0);
- sourceFile.pos = 0;
- sourceFile.end = sourceText.length;
+ var sourceFile = new SourceFileConstructor(248, 0, sourceText.length);
+ nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = ts.normalizePath(fileName);
sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0;
- sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 : 0;
+ sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 : 0;
return sourceFile;
}
function setContextFlag(val, flag) {
@@ -6900,7 +5965,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
- return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos);
+ return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -7038,7 +6103,7 @@ var ts;
case 12:
return token === 19 || token === 37 || isLiteralPropertyName();
case 9:
- return isLiteralPropertyName();
+ return token === 19 || isLiteralPropertyName();
case 7:
if (token === 15) {
return lookAhead(isValidHeritageClauseObjectLiteral);
@@ -7559,9 +6624,7 @@ var ts;
}
function parseParameterType() {
if (parseOptional(54)) {
- return token === 9
- ? parseLiteralNode(true)
- : parseType();
+ return parseType();
}
return undefined;
}
@@ -7818,6 +6881,8 @@ var ts;
case 131:
var node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
+ case 9:
+ return parseLiteralNode(true);
case 103:
case 97:
return parseTokenNode();
@@ -7847,6 +6912,7 @@ var ts;
case 19:
case 25:
case 92:
+ case 9:
return true;
case 17:
return lookAhead(isStartOfParenthesizedOrFunctionType);
@@ -8360,7 +7426,6 @@ var ts;
var unaryOperator = token;
var simpleUnaryExpression = parseSimpleUnaryExpression();
if (token === 38) {
- var diagnostic;
var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
if (simpleUnaryExpression.kind === 171) {
parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
@@ -10024,7 +9089,7 @@ var ts;
}
JSDocParser.isJSDocType = isJSDocType;
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState("file.js", content, 2, undefined);
+ initializeState("file.js", content, 2, true, undefined);
var jsDocTypeExpression = parseJSDocTypeExpression(start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -10275,7 +9340,7 @@ var ts;
}
}
function parseIsolatedJSDocComment(content, start, length) {
- initializeState("file.js", content, 2, undefined);
+ initializeState("file.js", content, 2, true, undefined);
var jsDocComment = parseJSDocComment(undefined, start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -10794,6 +9859,1075 @@ var ts;
})(IncrementalParser || (IncrementalParser = {}));
})(ts || (ts = {}));
var ts;
+(function (ts) {
+ ts.bindTime = 0;
+ function or(state1, state2) {
+ return (state1 | state2) & 2
+ ? 2
+ : (state1 & state2) & 8
+ ? 8
+ : 4;
+ }
+ function getModuleInstanceState(node) {
+ if (node.kind === 215 || node.kind === 216) {
+ return 0;
+ }
+ else if (ts.isConstEnumDeclaration(node)) {
+ return 2;
+ }
+ else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) {
+ return 0;
+ }
+ else if (node.kind === 219) {
+ var state = 0;
+ ts.forEachChild(node, function (n) {
+ switch (getModuleInstanceState(n)) {
+ case 0:
+ return false;
+ case 2:
+ state = 2;
+ return false;
+ case 1:
+ state = 1;
+ return true;
+ }
+ });
+ return state;
+ }
+ else if (node.kind === 218) {
+ return getModuleInstanceState(node.body);
+ }
+ else {
+ return 1;
+ }
+ }
+ ts.getModuleInstanceState = getModuleInstanceState;
+ var binder = createBinder();
+ function bindSourceFile(file, options) {
+ var start = new Date().getTime();
+ binder(file, options);
+ ts.bindTime += new Date().getTime() - start;
+ }
+ ts.bindSourceFile = bindSourceFile;
+ function createBinder() {
+ var file;
+ var options;
+ var parent;
+ var container;
+ var blockScopeContainer;
+ var lastContainer;
+ var seenThisKeyword;
+ var hasExplicitReturn;
+ var currentReachabilityState;
+ var labelStack;
+ var labelIndexMap;
+ var implicitLabels;
+ var inStrictMode;
+ var symbolCount = 0;
+ var Symbol;
+ var classifiableNames;
+ function bindSourceFile(f, opts) {
+ file = f;
+ options = opts;
+ inStrictMode = !!file.externalModuleIndicator;
+ classifiableNames = {};
+ Symbol = ts.objectAllocator.getSymbolConstructor();
+ if (!file.locals) {
+ bind(file);
+ file.symbolCount = symbolCount;
+ file.classifiableNames = classifiableNames;
+ }
+ parent = undefined;
+ container = undefined;
+ blockScopeContainer = undefined;
+ lastContainer = undefined;
+ seenThisKeyword = false;
+ hasExplicitReturn = false;
+ labelStack = undefined;
+ labelIndexMap = undefined;
+ implicitLabels = undefined;
+ }
+ return bindSourceFile;
+ function createSymbol(flags, name) {
+ symbolCount++;
+ return new Symbol(flags, name);
+ }
+ function addDeclarationToSymbol(symbol, node, symbolFlags) {
+ symbol.flags |= symbolFlags;
+ node.symbol = symbol;
+ if (!symbol.declarations) {
+ symbol.declarations = [];
+ }
+ symbol.declarations.push(node);
+ if (symbolFlags & 1952 && !symbol.exports) {
+ symbol.exports = {};
+ }
+ if (symbolFlags & 6240 && !symbol.members) {
+ symbol.members = {};
+ }
+ if (symbolFlags & 107455 && !symbol.valueDeclaration) {
+ symbol.valueDeclaration = node;
+ }
+ }
+ function getDeclarationName(node) {
+ if (node.name) {
+ if (node.kind === 218 && node.name.kind === 9) {
+ return "\"" + node.name.text + "\"";
+ }
+ if (node.name.kind === 136) {
+ var nameExpression = node.name.expression;
+ if (ts.isStringOrNumericLiteral(nameExpression.kind)) {
+ return nameExpression.text;
+ }
+ ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
+ return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
+ }
+ return node.name.text;
+ }
+ switch (node.kind) {
+ case 144:
+ return "__constructor";
+ case 152:
+ case 147:
+ return "__call";
+ case 153:
+ case 148:
+ return "__new";
+ case 149:
+ return "__index";
+ case 228:
+ return "__export";
+ case 227:
+ return node.isExportEquals ? "export=" : "default";
+ case 181:
+ return "export=";
+ case 213:
+ case 214:
+ return node.flags & 512 ? "default" : undefined;
+ }
+ }
+ function getDisplayName(node) {
+ return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node);
+ }
+ function declareSymbol(symbolTable, parent, node, includes, excludes) {
+ ts.Debug.assert(!ts.hasDynamicName(node));
+ var isDefaultExport = node.flags & 512;
+ var name = isDefaultExport && parent ? "default" : getDeclarationName(node);
+ var symbol;
+ if (name !== undefined) {
+ symbol = ts.hasProperty(symbolTable, name)
+ ? symbolTable[name]
+ : (symbolTable[name] = createSymbol(0, name));
+ if (name && (includes & 788448)) {
+ classifiableNames[name] = name;
+ }
+ if (symbol.flags & excludes) {
+ if (node.name) {
+ node.name.parent = node;
+ }
+ var message = symbol.flags & 2
+ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
+ : ts.Diagnostics.Duplicate_identifier_0;
+ ts.forEach(symbol.declarations, function (declaration) {
+ if (declaration.flags & 512) {
+ message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
+ }
+ });
+ ts.forEach(symbol.declarations, function (declaration) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
+ });
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
+ symbol = createSymbol(0, name);
+ }
+ }
+ else {
+ symbol = createSymbol(0, "__missing");
+ }
+ addDeclarationToSymbol(symbol, node, includes);
+ symbol.parent = parent;
+ return symbol;
+ }
+ function declareModuleMember(node, symbolFlags, symbolExcludes) {
+ var hasExportModifier = ts.getCombinedNodeFlags(node) & 2;
+ if (symbolFlags & 8388608) {
+ if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) {
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ else {
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ else {
+ if (hasExportModifier || container.flags & 131072) {
+ var exportKind = (symbolFlags & 107455 ? 1048576 : 0) |
+ (symbolFlags & 793056 ? 2097152 : 0) |
+ (symbolFlags & 1536 ? 4194304 : 0);
+ var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
+ local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ node.localSymbol = local;
+ return local;
+ }
+ else {
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ }
+ function bindChildren(node) {
+ var saveParent = parent;
+ var saveContainer = container;
+ var savedBlockScopeContainer = blockScopeContainer;
+ parent = node;
+ var containerFlags = getContainerFlags(node);
+ if (containerFlags & 1) {
+ container = blockScopeContainer = node;
+ if (containerFlags & 4) {
+ container.locals = {};
+ }
+ addToContainerChain(container);
+ }
+ else if (containerFlags & 2) {
+ blockScopeContainer = node;
+ blockScopeContainer.locals = undefined;
+ }
+ var savedReachabilityState;
+ var savedLabelStack;
+ var savedLabels;
+ var savedImplicitLabels;
+ var savedHasExplicitReturn;
+ var kind = node.kind;
+ var flags = node.flags;
+ flags &= ~1572864;
+ if (kind === 215) {
+ seenThisKeyword = false;
+ }
+ var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind);
+ if (saveState) {
+ savedReachabilityState = currentReachabilityState;
+ savedLabelStack = labelStack;
+ savedLabels = labelIndexMap;
+ savedImplicitLabels = implicitLabels;
+ savedHasExplicitReturn = hasExplicitReturn;
+ currentReachabilityState = 2;
+ hasExplicitReturn = false;
+ labelStack = labelIndexMap = implicitLabels = undefined;
+ }
+ bindReachableStatement(node);
+ if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) {
+ flags |= 524288;
+ if (hasExplicitReturn) {
+ flags |= 1048576;
+ }
+ }
+ if (kind === 215) {
+ flags = seenThisKeyword ? flags | 262144 : flags & ~262144;
+ }
+ node.flags = flags;
+ if (saveState) {
+ hasExplicitReturn = savedHasExplicitReturn;
+ currentReachabilityState = savedReachabilityState;
+ labelStack = savedLabelStack;
+ labelIndexMap = savedLabels;
+ implicitLabels = savedImplicitLabels;
+ }
+ container = saveContainer;
+ parent = saveParent;
+ blockScopeContainer = savedBlockScopeContainer;
+ }
+ function bindReachableStatement(node) {
+ if (checkUnreachable(node)) {
+ ts.forEachChild(node, bind);
+ return;
+ }
+ switch (node.kind) {
+ case 198:
+ bindWhileStatement(node);
+ break;
+ case 197:
+ bindDoStatement(node);
+ break;
+ case 199:
+ bindForStatement(node);
+ break;
+ case 200:
+ case 201:
+ bindForInOrForOfStatement(node);
+ break;
+ case 196:
+ bindIfStatement(node);
+ break;
+ case 204:
+ case 208:
+ bindReturnOrThrow(node);
+ break;
+ case 203:
+ case 202:
+ bindBreakOrContinueStatement(node);
+ break;
+ case 209:
+ bindTryStatement(node);
+ break;
+ case 206:
+ bindSwitchStatement(node);
+ break;
+ case 220:
+ bindCaseBlock(node);
+ break;
+ case 207:
+ bindLabeledStatement(node);
+ break;
+ default:
+ ts.forEachChild(node, bind);
+ break;
+ }
+ }
+ function bindWhileStatement(n) {
+ var preWhileState = n.expression.kind === 84 ? 4 : currentReachabilityState;
+ var postWhileState = n.expression.kind === 99 ? 4 : currentReachabilityState;
+ bind(n.expression);
+ currentReachabilityState = preWhileState;
+ var postWhileLabel = pushImplicitLabel();
+ bind(n.statement);
+ popImplicitLabel(postWhileLabel, postWhileState);
+ }
+ function bindDoStatement(n) {
+ var preDoState = currentReachabilityState;
+ var postDoLabel = pushImplicitLabel();
+ bind(n.statement);
+ var postDoState = n.expression.kind === 99 ? 4 : preDoState;
+ popImplicitLabel(postDoLabel, postDoState);
+ bind(n.expression);
+ }
+ function bindForStatement(n) {
+ var preForState = currentReachabilityState;
+ var postForLabel = pushImplicitLabel();
+ bind(n.initializer);
+ bind(n.condition);
+ bind(n.incrementor);
+ bind(n.statement);
+ var isInfiniteLoop = (!n.condition || n.condition.kind === 99);
+ var postForState = isInfiniteLoop ? 4 : preForState;
+ popImplicitLabel(postForLabel, postForState);
+ }
+ function bindForInOrForOfStatement(n) {
+ var preStatementState = currentReachabilityState;
+ var postStatementLabel = pushImplicitLabel();
+ bind(n.initializer);
+ bind(n.expression);
+ bind(n.statement);
+ popImplicitLabel(postStatementLabel, preStatementState);
+ }
+ function bindIfStatement(n) {
+ var ifTrueState = n.expression.kind === 84 ? 4 : currentReachabilityState;
+ var ifFalseState = n.expression.kind === 99 ? 4 : currentReachabilityState;
+ currentReachabilityState = ifTrueState;
+ bind(n.expression);
+ bind(n.thenStatement);
+ if (n.elseStatement) {
+ var preElseState = currentReachabilityState;
+ currentReachabilityState = ifFalseState;
+ bind(n.elseStatement);
+ currentReachabilityState = or(currentReachabilityState, preElseState);
+ }
+ else {
+ currentReachabilityState = or(currentReachabilityState, ifFalseState);
+ }
+ }
+ function bindReturnOrThrow(n) {
+ bind(n.expression);
+ if (n.kind === 204) {
+ hasExplicitReturn = true;
+ }
+ currentReachabilityState = 4;
+ }
+ function bindBreakOrContinueStatement(n) {
+ bind(n.label);
+ var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4);
+ if (isValidJump) {
+ currentReachabilityState = 4;
+ }
+ }
+ function bindTryStatement(n) {
+ var preTryState = currentReachabilityState;
+ bind(n.tryBlock);
+ var postTryState = currentReachabilityState;
+ currentReachabilityState = preTryState;
+ bind(n.catchClause);
+ var postCatchState = currentReachabilityState;
+ currentReachabilityState = preTryState;
+ bind(n.finallyBlock);
+ currentReachabilityState = or(postTryState, postCatchState);
+ }
+ function bindSwitchStatement(n) {
+ var preSwitchState = currentReachabilityState;
+ var postSwitchLabel = pushImplicitLabel();
+ bind(n.expression);
+ bind(n.caseBlock);
+ var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; });
+ var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState;
+ popImplicitLabel(postSwitchLabel, postSwitchState);
+ }
+ function bindCaseBlock(n) {
+ var startState = currentReachabilityState;
+ for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) {
+ var clause = _a[_i];
+ currentReachabilityState = startState;
+ bind(clause);
+ if (clause.statements.length && currentReachabilityState === 2 && options.noFallthroughCasesInSwitch) {
+ errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
+ }
+ }
+ }
+ function bindLabeledStatement(n) {
+ bind(n.label);
+ var ok = pushNamedLabel(n.label);
+ bind(n.statement);
+ if (ok) {
+ popNamedLabel(n.label, currentReachabilityState);
+ }
+ }
+ function getContainerFlags(node) {
+ switch (node.kind) {
+ case 186:
+ case 214:
+ case 215:
+ case 217:
+ case 155:
+ case 165:
+ return 1;
+ case 147:
+ case 148:
+ case 149:
+ case 143:
+ case 142:
+ case 213:
+ case 144:
+ case 145:
+ case 146:
+ case 152:
+ case 153:
+ case 173:
+ case 174:
+ case 218:
+ case 248:
+ case 216:
+ return 5;
+ case 244:
+ case 199:
+ case 200:
+ case 201:
+ case 220:
+ return 2;
+ case 192:
+ return ts.isFunctionLike(node.parent) ? 0 : 2;
+ }
+ return 0;
+ }
+ function addToContainerChain(next) {
+ if (lastContainer) {
+ lastContainer.nextContainer = next;
+ }
+ lastContainer = next;
+ }
+ function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
+ declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes);
+ }
+ function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) {
+ switch (container.kind) {
+ case 218:
+ return declareModuleMember(node, symbolFlags, symbolExcludes);
+ case 248:
+ return declareSourceFileMember(node, symbolFlags, symbolExcludes);
+ case 186:
+ case 214:
+ return declareClassMember(node, symbolFlags, symbolExcludes);
+ case 217:
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ case 155:
+ case 165:
+ case 215:
+ return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ case 152:
+ case 153:
+ case 147:
+ case 148:
+ case 149:
+ case 143:
+ case 142:
+ case 144:
+ case 145:
+ case 146:
+ case 213:
+ case 173:
+ case 174:
+ case 216:
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function declareClassMember(node, symbolFlags, symbolExcludes) {
+ return node.flags & 64
+ ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
+ : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
+ return ts.isExternalModule(file)
+ ? declareModuleMember(node, symbolFlags, symbolExcludes)
+ : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ function hasExportDeclarations(node) {
+ var body = node.kind === 248 ? node : node.body;
+ if (body.kind === 248 || body.kind === 219) {
+ for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
+ var stat = _a[_i];
+ if (stat.kind === 228 || stat.kind === 227) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ function setExportContextFlag(node) {
+ if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) {
+ node.flags |= 131072;
+ }
+ else {
+ node.flags &= ~131072;
+ }
+ }
+ function bindModuleDeclaration(node) {
+ setExportContextFlag(node);
+ if (node.name.kind === 9) {
+ declareSymbolAndAddToSymbolTable(node, 512, 106639);
+ }
+ else {
+ var state = getModuleInstanceState(node);
+ if (state === 0) {
+ declareSymbolAndAddToSymbolTable(node, 1024, 0);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 512, 106639);
+ if (node.symbol.flags & (16 | 32 | 256)) {
+ node.symbol.constEnumOnlyModule = false;
+ }
+ else {
+ var currentModuleIsConstEnumOnly = state === 2;
+ if (node.symbol.constEnumOnlyModule === undefined) {
+ node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
+ }
+ else {
+ node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
+ }
+ }
+ }
+ }
+ }
+ function bindFunctionOrConstructorType(node) {
+ var symbol = createSymbol(131072, getDeclarationName(node));
+ addDeclarationToSymbol(symbol, node, 131072);
+ var typeLiteralSymbol = createSymbol(2048, "__type");
+ addDeclarationToSymbol(typeLiteralSymbol, node, 2048);
+ typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a);
+ var _a;
+ }
+ function bindObjectLiteralExpression(node) {
+ if (inStrictMode) {
+ var seen = {};
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (prop.name.kind !== 69) {
+ continue;
+ }
+ var identifier = prop.name;
+ var currentKind = prop.kind === 245 || prop.kind === 246 || prop.kind === 143
+ ? 1
+ : 2;
+ var existingKind = seen[identifier.text];
+ if (!existingKind) {
+ seen[identifier.text] = currentKind;
+ continue;
+ }
+ if (currentKind === 1 && existingKind === 1) {
+ var span = ts.getErrorSpanForNode(file, identifier);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
+ }
+ }
+ }
+ return bindAnonymousDeclaration(node, 4096, "__object");
+ }
+ function bindAnonymousDeclaration(node, symbolFlags, name) {
+ var symbol = createSymbol(symbolFlags, name);
+ addDeclarationToSymbol(symbol, node, symbolFlags);
+ }
+ function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
+ switch (blockScopeContainer.kind) {
+ case 218:
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ case 248:
+ if (ts.isExternalModule(container)) {
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ }
+ default:
+ if (!blockScopeContainer.locals) {
+ blockScopeContainer.locals = {};
+ addToContainerChain(blockScopeContainer);
+ }
+ declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function bindBlockScopedVariableDeclaration(node) {
+ bindBlockScopedDeclaration(node, 2, 107455);
+ }
+ function checkStrictModeIdentifier(node) {
+ if (inStrictMode &&
+ node.originalKeywordKind >= 106 &&
+ node.originalKeywordKind <= 114 &&
+ !ts.isIdentifierName(node)) {
+ if (!file.parseDiagnostics.length) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
+ }
+ }
+ }
+ function getStrictModeIdentifierMessage(node) {
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
+ }
+ function checkStrictModeBinaryExpression(node) {
+ if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
+ checkStrictModeEvalOrArguments(node, node.left);
+ }
+ }
+ function checkStrictModeCatchClause(node) {
+ if (inStrictMode && node.variableDeclaration) {
+ checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
+ }
+ }
+ function checkStrictModeDeleteExpression(node) {
+ if (inStrictMode && node.expression.kind === 69) {
+ var span = ts.getErrorSpanForNode(file, node.expression);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
+ }
+ }
+ function isEvalOrArgumentsIdentifier(node) {
+ return node.kind === 69 &&
+ (node.text === "eval" || node.text === "arguments");
+ }
+ function checkStrictModeEvalOrArguments(contextNode, name) {
+ if (name && name.kind === 69) {
+ var identifier = name;
+ if (isEvalOrArgumentsIdentifier(identifier)) {
+ var span = ts.getErrorSpanForNode(file, name);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));
+ }
+ }
+ }
+ function getStrictModeEvalOrArgumentsMessage(node) {
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
+ }
+ function checkStrictModeFunctionName(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ }
+ function checkStrictModeNumericLiteral(node) {
+ if (inStrictMode && node.flags & 32768) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
+ }
+ }
+ function checkStrictModePostfixUnaryExpression(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
+ }
+ function checkStrictModePrefixUnaryExpression(node) {
+ if (inStrictMode) {
+ if (node.operator === 41 || node.operator === 42) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
+ }
+ }
+ function checkStrictModeWithStatement(node) {
+ if (inStrictMode) {
+ errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
+ }
+ }
+ function errorOnFirstToken(node, message, arg0, arg1, arg2) {
+ var span = ts.getSpanOfTokenAtPosition(file, node.pos);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
+ }
+ function getDestructuringParameterName(node) {
+ return "__" + ts.indexOf(node.parent.parameters, node);
+ }
+ function bind(node) {
+ if (!node) {
+ return;
+ }
+ node.parent = parent;
+ var savedInStrictMode = inStrictMode;
+ if (!savedInStrictMode) {
+ updateStrictMode(node);
+ }
+ bindWorker(node);
+ bindChildren(node);
+ inStrictMode = savedInStrictMode;
+ }
+ function updateStrictMode(node) {
+ switch (node.kind) {
+ case 248:
+ case 219:
+ updateStrictModeStatementList(node.statements);
+ return;
+ case 192:
+ if (ts.isFunctionLike(node.parent)) {
+ updateStrictModeStatementList(node.statements);
+ }
+ return;
+ case 214:
+ case 186:
+ inStrictMode = true;
+ return;
+ }
+ }
+ function updateStrictModeStatementList(statements) {
+ for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
+ var statement = statements_1[_i];
+ if (!ts.isPrologueDirective(statement)) {
+ return;
+ }
+ if (isUseStrictPrologueDirective(statement)) {
+ inStrictMode = true;
+ return;
+ }
+ }
+ }
+ function isUseStrictPrologueDirective(node) {
+ var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression);
+ return nodeText === "\"use strict\"" || nodeText === "'use strict'";
+ }
+ function bindWorker(node) {
+ switch (node.kind) {
+ case 69:
+ return checkStrictModeIdentifier(node);
+ case 181:
+ if (ts.isInJavaScriptFile(node)) {
+ if (ts.isExportsPropertyAssignment(node)) {
+ bindExportsPropertyAssignment(node);
+ }
+ else if (ts.isModuleExportsAssignment(node)) {
+ bindModuleExportsAssignment(node);
+ }
+ }
+ return checkStrictModeBinaryExpression(node);
+ case 244:
+ return checkStrictModeCatchClause(node);
+ case 175:
+ return checkStrictModeDeleteExpression(node);
+ case 8:
+ return checkStrictModeNumericLiteral(node);
+ case 180:
+ return checkStrictModePostfixUnaryExpression(node);
+ case 179:
+ return checkStrictModePrefixUnaryExpression(node);
+ case 205:
+ return checkStrictModeWithStatement(node);
+ case 97:
+ seenThisKeyword = true;
+ return;
+ case 137:
+ return declareSymbolAndAddToSymbolTable(node, 262144, 530912);
+ case 138:
+ return bindParameter(node);
+ case 211:
+ case 163:
+ return bindVariableDeclarationOrBindingElement(node);
+ case 141:
+ case 140:
+ return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455);
+ case 245:
+ case 246:
+ return bindPropertyOrMethodOrAccessor(node, 4, 107455);
+ case 247:
+ return bindPropertyOrMethodOrAccessor(node, 8, 107455);
+ case 147:
+ case 148:
+ case 149:
+ return declareSymbolAndAddToSymbolTable(node, 131072, 0);
+ case 143:
+ case 142:
+ return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263);
+ case 213:
+ checkStrictModeFunctionName(node);
+ return declareSymbolAndAddToSymbolTable(node, 16, 106927);
+ case 144:
+ return declareSymbolAndAddToSymbolTable(node, 16384, 0);
+ case 145:
+ return bindPropertyOrMethodOrAccessor(node, 32768, 41919);
+ case 146:
+ return bindPropertyOrMethodOrAccessor(node, 65536, 74687);
+ case 152:
+ case 153:
+ return bindFunctionOrConstructorType(node);
+ case 155:
+ return bindAnonymousDeclaration(node, 2048, "__type");
+ case 165:
+ return bindObjectLiteralExpression(node);
+ case 173:
+ case 174:
+ checkStrictModeFunctionName(node);
+ var bindingName = node.name ? node.name.text : "__function";
+ return bindAnonymousDeclaration(node, 16, bindingName);
+ case 168:
+ if (ts.isInJavaScriptFile(node)) {
+ bindCallExpression(node);
+ }
+ break;
+ case 186:
+ case 214:
+ return bindClassLikeDeclaration(node);
+ case 215:
+ return bindBlockScopedDeclaration(node, 64, 792960);
+ case 216:
+ return bindBlockScopedDeclaration(node, 524288, 793056);
+ case 217:
+ return bindEnumDeclaration(node);
+ case 218:
+ return bindModuleDeclaration(node);
+ case 221:
+ case 224:
+ case 226:
+ case 230:
+ return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608);
+ case 223:
+ return bindImportClause(node);
+ case 228:
+ return bindExportDeclaration(node);
+ case 227:
+ return bindExportAssignment(node);
+ case 248:
+ return bindSourceFileIfExternalModule();
+ }
+ }
+ function bindSourceFileIfExternalModule() {
+ setExportContextFlag(file);
+ if (ts.isExternalModule(file)) {
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindSourceFileAsExternalModule() {
+ bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\"");
+ }
+ function bindExportAssignment(node) {
+ var boundExpression = node.kind === 227 ? node.expression : node.right;
+ if (!container.symbol || !container.symbol.exports) {
+ bindAnonymousDeclaration(node, 8388608, getDeclarationName(node));
+ }
+ else if (boundExpression.kind === 69) {
+ declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608);
+ }
+ else {
+ declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608);
+ }
+ }
+ function bindExportDeclaration(node) {
+ if (!container.symbol || !container.symbol.exports) {
+ bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node));
+ }
+ else if (!node.exportClause) {
+ declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0);
+ }
+ }
+ function bindImportClause(node) {
+ if (node.name) {
+ declareSymbolAndAddToSymbolTable(node, 8388608, 8388608);
+ }
+ }
+ function setCommonJsModuleIndicator(node) {
+ if (!file.commonJsModuleIndicator) {
+ file.commonJsModuleIndicator = node;
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindExportsPropertyAssignment(node) {
+ setCommonJsModuleIndicator(node);
+ declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0);
+ }
+ function bindModuleExportsAssignment(node) {
+ setCommonJsModuleIndicator(node);
+ bindExportAssignment(node);
+ }
+ function bindCallExpression(node) {
+ if (!file.commonJsModuleIndicator && ts.isRequireCall(node)) {
+ setCommonJsModuleIndicator(node);
+ }
+ }
+ function bindClassLikeDeclaration(node) {
+ if (node.kind === 214) {
+ bindBlockScopedDeclaration(node, 32, 899519);
+ }
+ else {
+ var bindingName = node.name ? node.name.text : "__class";
+ bindAnonymousDeclaration(node, 32, bindingName);
+ if (node.name) {
+ classifiableNames[node.name.text] = node.name.text;
+ }
+ }
+ var symbol = node.symbol;
+ var prototypeSymbol = createSymbol(4 | 134217728, "prototype");
+ if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) {
+ if (node.name) {
+ node.name.parent = node;
+ }
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
+ }
+ symbol.exports[prototypeSymbol.name] = prototypeSymbol;
+ prototypeSymbol.parent = symbol;
+ }
+ function bindEnumDeclaration(node) {
+ return ts.isConst(node)
+ ? bindBlockScopedDeclaration(node, 128, 899967)
+ : bindBlockScopedDeclaration(node, 256, 899327);
+ }
+ function bindVariableDeclarationOrBindingElement(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (!ts.isBindingPattern(node.name)) {
+ if (ts.isBlockOrCatchScoped(node)) {
+ bindBlockScopedVariableDeclaration(node);
+ }
+ else if (ts.isParameterDeclaration(node)) {
+ declareSymbolAndAddToSymbolTable(node, 1, 107455);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1, 107454);
+ }
+ }
+ }
+ function bindParameter(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (ts.isBindingPattern(node.name)) {
+ bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node));
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1, 107455);
+ }
+ if (node.flags & 56 &&
+ node.parent.kind === 144 &&
+ ts.isClassLike(node.parent.parent)) {
+ var classDeclaration = node.parent.parent;
+ declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455);
+ }
+ }
+ function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
+ return ts.hasDynamicName(node)
+ ? bindAnonymousDeclaration(node, symbolFlags, "__computed")
+ : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ }
+ function pushNamedLabel(name) {
+ initializeReachabilityStateIfNecessary();
+ if (ts.hasProperty(labelIndexMap, name.text)) {
+ return false;
+ }
+ labelIndexMap[name.text] = labelStack.push(1) - 1;
+ return true;
+ }
+ function pushImplicitLabel() {
+ initializeReachabilityStateIfNecessary();
+ var index = labelStack.push(1) - 1;
+ implicitLabels.push(index);
+ return index;
+ }
+ function popNamedLabel(label, outerState) {
+ var index = labelIndexMap[label.text];
+ ts.Debug.assert(index !== undefined);
+ ts.Debug.assert(labelStack.length == index + 1);
+ labelIndexMap[label.text] = undefined;
+ setCurrentStateAtLabel(labelStack.pop(), outerState, label);
+ }
+ function popImplicitLabel(implicitLabelIndex, outerState) {
+ if (labelStack.length !== implicitLabelIndex + 1) {
+ ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex);
+ }
+ var i = implicitLabels.pop();
+ if (implicitLabelIndex !== i) {
+ ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex);
+ }
+ setCurrentStateAtLabel(labelStack.pop(), outerState, undefined);
+ }
+ function setCurrentStateAtLabel(innerMergedState, outerState, label) {
+ if (innerMergedState === 1) {
+ if (label && !options.allowUnusedLabels) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label));
+ }
+ currentReachabilityState = outerState;
+ }
+ else {
+ currentReachabilityState = or(innerMergedState, outerState);
+ }
+ }
+ function jumpToLabel(label, outerState) {
+ initializeReachabilityStateIfNecessary();
+ var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels);
+ if (index === undefined) {
+ return false;
+ }
+ var stateAtLabel = labelStack[index];
+ labelStack[index] = stateAtLabel === 1 ? outerState : or(stateAtLabel, outerState);
+ return true;
+ }
+ function checkUnreachable(node) {
+ switch (currentReachabilityState) {
+ case 4:
+ var reportError = (ts.isStatement(node) && node.kind !== 194) ||
+ node.kind === 214 ||
+ (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) ||
+ (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
+ if (reportError) {
+ currentReachabilityState = 8;
+ var reportUnreachableCode = !options.allowUnreachableCode &&
+ !ts.isInAmbientContext(node) &&
+ (node.kind !== 193 ||
+ ts.getCombinedNodeFlags(node.declarationList) & 24576 ||
+ ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
+ if (reportUnreachableCode) {
+ errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected);
+ }
+ }
+ case 8:
+ return true;
+ default:
+ return false;
+ }
+ function shouldReportErrorOnModuleDeclaration(node) {
+ var instanceState = getModuleInstanceState(node);
+ return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums);
+ }
+ }
+ function initializeReachabilityStateIfNecessary() {
+ if (labelIndexMap) {
+ return;
+ }
+ currentReachabilityState = 2;
+ labelIndexMap = {};
+ labelStack = [];
+ implicitLabels = [];
+ }
+ }
+})(ts || (ts = {}));
+var ts;
(function (ts) {
var nextSymbolId = 1;
var nextNodeId = 1;
@@ -10853,7 +10987,7 @@ var ts;
symbolToString: symbolToString,
getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
getRootSymbols: getRootSymbols,
- getContextualType: getContextualType,
+ getContextualType: getApparentTypeOfContextualType,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: getResolvedSignature,
getConstantValue: getConstantValue,
@@ -11109,7 +11243,7 @@ var ts;
return ts.getAncestor(node, 248);
}
function isGlobalSourceFile(node) {
- return node.kind === 248 && !ts.isExternalModule(node);
+ return node.kind === 248 && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning && ts.hasProperty(symbols, name)) {
@@ -11195,23 +11329,24 @@ var ts;
}
switch (location.kind) {
case 248:
- if (!ts.isExternalModule(location))
+ if (!ts.isExternalOrCommonJsModule(location))
break;
case 218:
var moduleExports = getSymbolOfNode(location).exports;
if (location.kind === 248 ||
(location.kind === 218 && location.name.kind === 9)) {
+ if (result = moduleExports["default"]) {
+ var localSymbol = ts.getLocalSymbolForExportDefault(result);
+ if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
+ break loop;
+ }
+ result = undefined;
+ }
if (ts.hasProperty(moduleExports, name) &&
moduleExports[name].flags === 8388608 &&
ts.getDeclarationOfKind(moduleExports[name], 230)) {
break;
}
- result = moduleExports["default"];
- var localSymbol = ts.getLocalSymbolForExportDefault(result);
- if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) {
- break loop;
- }
- result = undefined;
}
if (result = getSymbol(moduleExports, name, meaning & 8914931)) {
break loop;
@@ -11569,6 +11704,9 @@ var ts;
if (moduleName === undefined) {
return;
}
+ if (moduleName.indexOf("!") >= 0) {
+ moduleName = moduleName.substr(0, moduleName.indexOf("!"));
+ }
var isRelative = ts.isExternalModuleNameRelative(moduleName);
if (!isRelative) {
var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512);
@@ -11739,7 +11877,7 @@ var ts;
}
switch (location_1.kind) {
case 248:
- if (!ts.isExternalModule(location_1)) {
+ if (!ts.isExternalOrCommonJsModule(location_1)) {
break;
}
case 218:
@@ -11866,7 +12004,7 @@ var ts;
}
function hasExternalModuleSymbol(declaration) {
return (declaration.kind === 218 && declaration.name.kind === 9) ||
- (declaration.kind === 248 && ts.isExternalModule(declaration));
+ (declaration.kind === 248 && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol) {
var aliasesToMakeVisible;
@@ -12064,7 +12202,7 @@ var ts;
writeAnonymousType(type, flags);
}
else if (type.flags & 256) {
- writer.writeStringLiteral(type.text);
+ writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\"");
}
else {
writePunctuation(writer, 15);
@@ -12428,7 +12566,7 @@ var ts;
}
}
else if (node.kind === 248) {
- return ts.isExternalModule(node) ? node : undefined;
+ return ts.isExternalOrCommonJsModule(node) ? node : undefined;
}
}
ts.Debug.fail("getContainingModule cant reach here");
@@ -12633,6 +12771,23 @@ var ts;
var symbol = getSymbolOfNode(node);
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);
}
+ function getTextOfPropertyName(name) {
+ switch (name.kind) {
+ case 69:
+ return name.text;
+ case 9:
+ case 8:
+ return name.text;
+ case 136:
+ if (ts.isStringOrNumericLiteral(name.expression.kind)) {
+ return name.expression.text;
+ }
+ }
+ return undefined;
+ }
+ function isComputedNonLiteralName(name) {
+ return name.kind === 136 && !ts.isStringOrNumericLiteral(name.expression.kind);
+ }
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
@@ -12648,8 +12803,12 @@ var ts;
var type;
if (pattern.kind === 161) {
var name_10 = declaration.propertyName || declaration.name;
- type = getTypeOfPropertyOfType(parentType, name_10.text) ||
- isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1) ||
+ if (isComputedNonLiteralName(name_10)) {
+ return anyType;
+ }
+ var text = getTextOfPropertyName(name_10);
+ type = getTypeOfPropertyOfType(parentType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) ||
getIndexTypeOfType(parentType, 0);
if (!type) {
error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10));
@@ -12727,10 +12886,16 @@ var ts;
}
function getTypeFromObjectBindingPattern(pattern, includePatternInType) {
var members = {};
+ var hasComputedProperties = false;
ts.forEach(pattern.elements, function (e) {
- var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0);
var name = e.propertyName || e.name;
- var symbol = createSymbol(flags, name.text);
+ if (isComputedNonLiteralName(name)) {
+ hasComputedProperties = true;
+ return;
+ }
+ var text = getTextOfPropertyName(name);
+ var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0);
+ var symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType);
symbol.bindingElement = e;
members[symbol.name] = symbol;
@@ -12739,6 +12904,9 @@ var ts;
if (includePatternInType) {
result.pattern = pattern;
}
+ if (hasComputedProperties) {
+ result.flags |= 67108864;
+ }
return result;
}
function getTypeFromArrayBindingPattern(pattern, includePatternInType) {
@@ -12789,6 +12957,12 @@ var ts;
if (declaration.kind === 227) {
return links.type = checkExpression(declaration.expression);
}
+ if (declaration.kind === 181) {
+ return links.type = checkExpression(declaration.right);
+ }
+ if (declaration.kind === 166) {
+ return checkExpressionCached(declaration.parent.right);
+ }
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
@@ -13038,17 +13212,19 @@ var ts;
}
function resolveBaseTypesOfClass(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
- var baseContructorType = getBaseConstructorTypeOfClass(type);
- if (!(baseContructorType.flags & 80896)) {
+ var baseConstructorType = getBaseConstructorTypeOfClass(type);
+ if (!(baseConstructorType.flags & 80896)) {
return;
}
var baseTypeNode = getBaseTypeNodeOfClass(type);
var baseType;
- if (baseContructorType.symbol && baseContructorType.symbol.flags & 32) {
- baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol);
+ var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
+ if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 &&
+ areAllOuterTypeParametersApplied(originalBaseType)) {
+ baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
}
else {
- var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments);
+ var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments);
if (!constructors.length) {
error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
return;
@@ -13073,6 +13249,15 @@ var ts;
type.resolvedBaseTypes.push(baseType);
}
}
+ function areAllOuterTypeParametersApplied(type) {
+ var outerTypeParameters = type.outerTypeParameters;
+ if (outerTypeParameters) {
+ var last = outerTypeParameters.length - 1;
+ var typeArguments = type.typeArguments;
+ return outerTypeParameters[last].symbol !== typeArguments[last].symbol;
+ }
+ return true;
+ }
function resolveBaseTypesOfInterface(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
@@ -13144,7 +13329,7 @@ var ts;
type.typeArguments = type.typeParameters;
type.thisType = createType(512 | 33554432);
type.thisType.symbol = symbol;
- type.thisType.constraint = getTypeWithThisArgument(type);
+ type.thisType.constraint = type;
}
}
return links.declaredType;
@@ -13619,14 +13804,19 @@ var ts;
type = getApparentType(type);
return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
}
+ function getApparentTypeOfTypeParameter(type) {
+ if (!type.resolvedApparentType) {
+ var constraintType = getConstraintOfTypeParameter(type);
+ while (constraintType && constraintType.flags & 512) {
+ constraintType = getConstraintOfTypeParameter(constraintType);
+ }
+ type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
+ }
+ return type.resolvedApparentType;
+ }
function getApparentType(type) {
if (type.flags & 512) {
- do {
- type = getConstraintOfTypeParameter(type);
- } while (type && type.flags & 512);
- if (!type) {
- type = emptyObjectType;
- }
+ type = getApparentTypeOfTypeParameter(type);
}
if (type.flags & 258) {
type = globalStringType;
@@ -13779,7 +13969,7 @@ var ts;
if (node.initializer) {
var signatureDeclaration = node.parent;
var signature = getSignatureFromDeclaration(signatureDeclaration);
- var parameterIndex = signatureDeclaration.parameters.indexOf(node);
+ var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node);
ts.Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
@@ -13874,6 +14064,16 @@ var ts;
}
return result;
}
+ function resolveExternalModuleTypeByLiteral(name) {
+ var moduleSym = resolveExternalModuleName(name, name);
+ if (moduleSym) {
+ var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
+ if (resolvedModuleSymbol) {
+ return getTypeOfSymbol(resolvedModuleSymbol);
+ }
+ }
+ return anyType;
+ }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3)) {
@@ -14335,11 +14535,12 @@ var ts;
return links.resolvedType;
}
function getStringLiteralType(node) {
- if (ts.hasProperty(stringLiteralTypes, node.text)) {
- return stringLiteralTypes[node.text];
+ var text = node.text;
+ if (ts.hasProperty(stringLiteralTypes, text)) {
+ return stringLiteralTypes[text];
}
- var type = stringLiteralTypes[node.text] = createType(256);
- type.text = ts.getTextOfNode(node);
+ var type = stringLiteralTypes[text] = createType(256);
+ type.text = text;
return type;
}
function getTypeFromStringLiteral(node) {
@@ -14808,7 +15009,7 @@ var ts;
return false;
}
function hasExcessProperties(source, target, reportErrors) {
- if (someConstituentTypeHasKind(target, 80896)) {
+ if (!(target.flags & 67108864) && someConstituentTypeHasKind(target, 80896)) {
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
if (!isKnownProperty(target, prop.name)) {
@@ -14898,9 +15099,6 @@ var ts;
return result;
}
function typeParameterIdenticalTo(source, target) {
- if (source.symbol.name !== target.symbol.name) {
- return 0;
- }
if (source.constraint === target.constraint) {
return -1;
}
@@ -15345,18 +15543,24 @@ var ts;
}
return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
}
+ function isMatchingSignature(source, target, partialMatch) {
+ if (source.parameters.length === target.parameters.length &&
+ source.minArgumentCount === target.minArgumentCount &&
+ source.hasRestParameter === target.hasRestParameter) {
+ return true;
+ }
+ if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter ||
+ source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) {
+ return true;
+ }
+ return false;
+ }
function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) {
if (source === target) {
return -1;
}
- if (source.parameters.length !== target.parameters.length ||
- source.minArgumentCount !== target.minArgumentCount ||
- source.hasRestParameter !== target.hasRestParameter) {
- if (!partialMatch ||
- source.parameters.length < target.parameters.length && !source.hasRestParameter ||
- source.minArgumentCount > target.minArgumentCount) {
- return 0;
- }
+ if (!(isMatchingSignature(source, target, partialMatch))) {
+ return 0;
}
var result = -1;
if (source.typeParameters && target.typeParameters) {
@@ -15441,6 +15645,9 @@ var ts;
function isTupleLikeType(type) {
return !!getPropertyOfType(type, "0");
}
+ function isStringLiteralType(type) {
+ return type.flags & 256;
+ }
function isTupleType(type) {
return !!(type.flags & 8192);
}
@@ -16032,7 +16239,7 @@ var ts;
}
}
function narrowTypeByInstanceof(type, expr, assumeTrue) {
- if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) {
+ if (isTypeAny(type) || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) {
return type;
}
var rightType = checkExpression(expr.right);
@@ -16060,6 +16267,12 @@ var ts;
}
}
if (targetType) {
+ if (!assumeTrue) {
+ if (type.flags & 16384) {
+ return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); }));
+ }
+ return type;
+ }
return getNarrowedType(type, targetType);
}
return type;
@@ -16471,6 +16684,9 @@ var ts;
function getIndexTypeOfContextualType(type, kind) {
return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); });
}
+ function contextualTypeIsStringLiteralType(type) {
+ return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type));
+ }
function contextualTypeIsTupleLikeType(type) {
return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type));
}
@@ -16486,7 +16702,7 @@ var ts;
}
function getContextualTypeForObjectLiteralElement(element) {
var objectLiteral = element.parent;
- var type = getContextualType(objectLiteral);
+ var type = getApparentTypeOfContextualType(objectLiteral);
if (type) {
if (!ts.hasDynamicName(element)) {
var symbolName = getSymbolOfNode(element).name;
@@ -16502,7 +16718,7 @@ var ts;
}
function getContextualTypeForElementExpression(node) {
var arrayLiteral = node.parent;
- var type = getContextualType(arrayLiteral);
+ var type = getApparentTypeOfContextualType(arrayLiteral);
if (type) {
var index = ts.indexOf(arrayLiteral.elements, node);
return getTypeOfPropertyOfContextualType(type, "" + index)
@@ -16531,11 +16747,11 @@ var ts;
}
return undefined;
}
- function getContextualType(node) {
- var type = getContextualTypeWorker(node);
+ function getApparentTypeOfContextualType(node) {
+ var type = getContextualType(node);
return type && getApparentType(type);
}
- function getContextualTypeWorker(node) {
+ function getContextualType(node) {
if (isInsideWithStatementBody(node)) {
return undefined;
}
@@ -16601,7 +16817,7 @@ var ts;
ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node));
var type = ts.isObjectLiteralMethod(node)
? getContextualTypeForObjectLiteralMethod(node)
- : getContextualType(node);
+ : getApparentTypeOfContextualType(node);
if (!type) {
return undefined;
}
@@ -16684,7 +16900,7 @@ var ts;
type.pattern = node;
return type;
}
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
var pattern = contextualType.pattern;
if (pattern && (pattern.kind === 162 || pattern.kind === 164)) {
@@ -16739,10 +16955,11 @@ var ts;
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
var propertiesTable = {};
var propertiesArray = [];
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 161 || contextualType.pattern.kind === 165);
var typeFlags = 0;
+ var patternWithComputedProperties = false;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var memberDecl = _a[_i];
var member = memberDecl.symbol;
@@ -16768,8 +16985,11 @@ var ts;
if (isOptional) {
prop.flags |= 536870912;
}
+ if (ts.hasDynamicName(memberDecl)) {
+ patternWithComputedProperties = true;
+ }
}
- else if (contextualTypeHasPattern) {
+ else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) {
var impliedProp = getPropertyOfType(contextualType, member.name);
if (impliedProp) {
prop.flags |= impliedProp.flags & 536870912;
@@ -16812,7 +17032,7 @@ var ts;
var numberIndexType = getIndexType(1);
var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType);
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576;
- result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064);
+ result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0);
if (inDestructuringPattern) {
result.pattern = node;
}
@@ -18027,6 +18247,9 @@ var ts;
return anyType;
}
}
+ if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node)) {
+ return resolveExternalModuleTypeByLiteral(node.arguments[0]);
+ }
return getReturnTypeOfSignature(signature);
}
function checkTaggedTemplateExpression(node) {
@@ -18037,7 +18260,9 @@ var ts;
var targetType = getTypeFromTypeNode(node.type);
if (produceDiagnostics && targetType !== unknownType) {
var widenedType = getWidenedType(exprType);
- if (!(isTypeAssignableTo(targetType, widenedType))) {
+ var bothAreStringLike = someConstituentTypeHasKind(targetType, 258) &&
+ someConstituentTypeHasKind(widenedType, 258);
+ if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) {
checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other);
}
}
@@ -18476,17 +18701,24 @@ var ts;
var p = properties_3[_i];
if (p.kind === 245 || p.kind === 246) {
var name_13 = p.name;
+ if (name_13.kind === 136) {
+ checkComputedPropertyName(name_13);
+ }
+ if (isComputedNonLiteralName(name_13)) {
+ continue;
+ }
+ var text = getTextOfPropertyName(name_13);
var type = isTypeAny(sourceType)
? sourceType
- : getTypeOfPropertyOfType(sourceType, name_13.text) ||
- isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1) ||
+ : getTypeOfPropertyOfType(sourceType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1) ||
getIndexTypeOfType(sourceType, 0);
if (type) {
if (p.kind === 246) {
checkDestructuringAssignment(p, type);
}
else {
- checkDestructuringAssignment(p.initializer || name_13, type);
+ checkDestructuringAssignment(p.initializer, type);
}
}
else {
@@ -18664,6 +18896,9 @@ var ts;
case 31:
case 32:
case 33:
+ if (someConstituentTypeHasKind(leftType, 258) && someConstituentTypeHasKind(rightType, 258)) {
+ return booleanType;
+ }
if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) {
reportOperatorError();
}
@@ -18771,6 +19006,13 @@ var ts;
var type2 = checkExpression(node.whenFalse, contextualMapper);
return getUnionType([type1, type2]);
}
+ function checkStringLiteralExpression(node) {
+ var contextualType = getContextualType(node);
+ if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
+ return getStringLiteralType(node);
+ }
+ return stringType;
+ }
function checkTemplateExpression(node) {
ts.forEach(node.templateSpans, function (templateSpan) {
checkExpression(templateSpan.expression);
@@ -18809,7 +19051,7 @@ var ts;
if (isInferentialContext(contextualMapper)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(contextualType);
if (contextualSignature && !contextualSignature.typeParameters) {
@@ -18861,6 +19103,7 @@ var ts;
case 183:
return checkTemplateExpression(node);
case 9:
+ return checkStringLiteralExpression(node);
case 11:
return stringType;
case 10:
@@ -19922,7 +20165,7 @@ var ts;
return;
}
var parent = getDeclarationContainer(node);
- if (parent.kind === 248 && ts.isExternalModule(parent)) {
+ if (parent.kind === 248 && ts.isExternalOrCommonJsModule(parent)) {
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
}
@@ -19993,6 +20236,11 @@ var ts;
checkExpressionCached(node.initializer);
}
}
+ if (node.kind === 163) {
+ if (node.propertyName && node.propertyName.kind === 136) {
+ checkComputedPropertyName(node.propertyName);
+ }
+ }
if (ts.isBindingPattern(node.name)) {
ts.forEach(node.name.elements, checkSourceElement);
}
@@ -20351,6 +20599,7 @@ var ts;
var firstDefaultClause;
var hasDuplicateDefaultClause = false;
var expressionType = checkExpression(node.expression);
+ var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258);
ts.forEach(node.caseBlock.clauses, function (clause) {
if (clause.kind === 242 && !hasDuplicateDefaultClause) {
if (firstDefaultClause === undefined) {
@@ -20367,6 +20616,9 @@ var ts;
if (produceDiagnostics && clause.kind === 241) {
var caseClause = clause;
var caseType = checkExpression(caseClause.expression);
+ if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258)) {
+ return;
+ }
if (!isTypeAssignableTo(expressionType, caseType)) {
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, undefined);
}
@@ -20774,11 +21026,14 @@ var ts;
var enumIsConst = ts.isConst(node);
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.name.kind === 136) {
+ if (isComputedNonLiteralName(member.name)) {
error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
}
- else if (isNumericLiteralName(member.name.text)) {
- error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ else {
+ var text = getTextOfPropertyName(member.name);
+ if (isNumericLiteralName(text)) {
+ error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ }
}
var previousEnumMemberIsNonConstant = autoValue === undefined;
var initializer = member.initializer;
@@ -21476,8 +21731,10 @@ var ts;
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
if (!(links.flags & 1)) {
- if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) {
- return;
+ if (compilerOptions.skipDefaultLibCheck) {
+ if (node.hasNoDefaultLib) {
+ return;
+ }
}
checkGrammarSourceFile(node);
emitExtends = false;
@@ -21486,7 +21743,7 @@ var ts;
potentialThisCollisions.length = 0;
ts.forEach(node.statements, checkSourceElement);
checkFunctionAndClassExpressionBodies(node);
- if (ts.isExternalModule(node)) {
+ if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
if (potentialThisCollisions.length) {
@@ -21564,7 +21821,7 @@ var ts;
}
switch (location.kind) {
case 248:
- if (!ts.isExternalModule(location)) {
+ if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
case 218:
@@ -22123,15 +22380,24 @@ var ts;
getReferencedValueDeclaration: getReferencedValueDeclaration,
getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
isOptionalParameter: isOptionalParameter,
- isArgumentsLocalBinding: isArgumentsLocalBinding
+ isArgumentsLocalBinding: isArgumentsLocalBinding,
+ getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration
};
}
+ function getExternalModuleFileFromDeclaration(declaration) {
+ var specifier = ts.getExternalModuleName(declaration);
+ var moduleSymbol = getSymbolAtLocation(specifier);
+ if (!moduleSymbol) {
+ return undefined;
+ }
+ return ts.getDeclarationOfKind(moduleSymbol, 248);
+ }
function initializeTypeChecker() {
ts.forEach(host.getSourceFiles(), function (file) {
ts.bindSourceFile(file, compilerOptions);
});
ts.forEach(host.getSourceFiles(), function (file) {
- if (!ts.isExternalModule(file)) {
+ if (!ts.isExternalOrCommonJsModule(file)) {
mergeSymbolTable(globals, file.locals);
}
});
@@ -22808,7 +23074,7 @@ var ts;
}
}
function checkGrammarForNonSymbolComputedProperty(node, message) {
- if (node.kind === 136 && !ts.isWellKnownSymbolSyntactically(node.expression)) {
+ if (ts.isDynamicName(node)) {
return grammarErrorOnNode(node, message);
}
}
@@ -23122,11 +23388,15 @@ var ts;
var writeTextOfNode;
var writer = createAndSetNewTextWriterWithSymbolWriter();
var enclosingDeclaration;
- var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentIdentifiers;
+ var isCurrentFileExternalModule;
var reportedDeclarationError = false;
var errorNameNode;
var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments;
var emit = compilerOptions.stripInternal ? stripInternal : emitNode;
+ var noDeclare = !root;
var moduleElementDeclarationEmitInfo = [];
var asynchronousSubModuleDeclarationEmitInfo;
var referencePathsOutput = "";
@@ -23162,21 +23432,53 @@ var ts;
}
else {
var emittedReferencedFiles = [];
+ var prevModuleElementDeclarationEmitInfo = [];
ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ if (!ts.isDeclarationFile(sourceFile)) {
if (!compilerOptions.noResolve) {
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
- if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) &&
+ if (referencedFile && (ts.isDeclarationFile(referencedFile) &&
!ts.contains(emittedReferencedFiles, referencedFile))) {
writeReferencePath(referencedFile);
emittedReferencedFiles.push(referencedFile);
}
});
}
+ }
+ if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ noDeclare = false;
emitSourceFile(sourceFile);
}
+ else if (ts.isExternalModule(sourceFile)) {
+ noDeclare = true;
+ write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {");
+ writeLine();
+ increaseIndent();
+ emitSourceFile(sourceFile);
+ decreaseIndent();
+ write("}");
+ writeLine();
+ if (moduleElementDeclarationEmitInfo.length) {
+ var oldWriter = writer;
+ ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) {
+ if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
+ ts.Debug.assert(aliasEmitInfo.node.kind === 222);
+ createAndSetNewTextWriterWithSymbolWriter();
+ ts.Debug.assert(aliasEmitInfo.indent === 1);
+ increaseIndent();
+ writeImportDeclaration(aliasEmitInfo.node);
+ aliasEmitInfo.asynchronousOutput = writer.getText();
+ decreaseIndent();
+ }
+ });
+ setWriter(oldWriter);
+ }
+ prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
+ moduleElementDeclarationEmitInfo = [];
+ }
});
+ moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo);
}
return {
reportedDeclarationError: reportedDeclarationError,
@@ -23185,13 +23487,12 @@ var ts;
referencePathsOutput: referencePathsOutput
};
function hasInternalAnnotation(range) {
- var text = currentSourceFile.text;
- var comment = text.substring(range.pos, range.end);
+ var comment = currentText.substring(range.pos, range.end);
return comment.indexOf("@internal") >= 0;
}
function stripInternal(node) {
if (node) {
- var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos);
if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
return;
}
@@ -23272,7 +23573,7 @@ var ts;
var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
- diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
+ diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
}
else {
diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
@@ -23336,9 +23637,9 @@ var ts;
}
function writeJsDocComments(declaration) {
if (declaration) {
- var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile);
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments);
- ts.emitComments(currentSourceFile, writer, jsDocComments, true, newLine, ts.writeCommentRange);
+ var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
+ ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange);
}
}
function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) {
@@ -23355,7 +23656,7 @@ var ts;
case 103:
case 97:
case 9:
- return writeTextOfNode(currentSourceFile, type);
+ return writeTextOfNode(currentText, type);
case 188:
return emitExpressionWithTypeArguments(type);
case 151:
@@ -23386,14 +23687,14 @@ var ts;
}
function writeEntityName(entityName) {
if (entityName.kind === 69) {
- writeTextOfNode(currentSourceFile, entityName);
+ writeTextOfNode(currentText, entityName);
}
else {
var left = entityName.kind === 135 ? entityName.left : entityName.expression;
var right = entityName.kind === 135 ? entityName.right : entityName.name;
writeEntityName(left);
write(".");
- writeTextOfNode(currentSourceFile, right);
+ writeTextOfNode(currentText, right);
}
}
function emitEntityName(entityName) {
@@ -23421,7 +23722,7 @@ var ts;
}
}
function emitTypePredicate(type) {
- writeTextOfNode(currentSourceFile, type.parameterName);
+ writeTextOfNode(currentText, type.parameterName);
write(" is ");
emitType(type.type);
}
@@ -23461,20 +23762,23 @@ var ts;
}
}
function emitSourceFile(node) {
- currentSourceFile = node;
+ currentText = node.text;
+ currentLineMap = ts.getLineStarts(node);
+ currentIdentifiers = node.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(node);
enclosingDeclaration = node;
- ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true);
+ ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true);
emitLines(node.statements);
}
function getExportDefaultTempVariableName() {
var baseName = "_default";
- if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) {
+ if (!ts.hasProperty(currentIdentifiers, baseName)) {
return baseName;
}
var count = 0;
while (true) {
var name_18 = baseName + "_" + (++count);
- if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) {
+ if (!ts.hasProperty(currentIdentifiers, name_18)) {
return name_18;
}
}
@@ -23482,7 +23786,7 @@ var ts;
function emitExportAssignment(node) {
if (node.expression.kind === 69) {
write(node.isExportEquals ? "export = " : "export default ");
- writeTextOfNode(currentSourceFile, node.expression);
+ writeTextOfNode(currentText, node.expression);
}
else {
var tempVarName = getExportDefaultTempVariableName();
@@ -23517,7 +23821,7 @@ var ts;
writeModuleElement(node);
}
else if (node.kind === 221 ||
- (node.parent.kind === 248 && ts.isExternalModule(currentSourceFile))) {
+ (node.parent.kind === 248 && isCurrentFileExternalModule)) {
var isVisible;
if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248) {
asynchronousSubModuleDeclarationEmitInfo.push({
@@ -23569,14 +23873,14 @@ var ts;
}
}
function emitModuleElementDeclarationFlags(node) {
- if (node.parent === currentSourceFile) {
+ if (node.parent.kind === 248) {
if (node.flags & 2) {
write("export ");
}
if (node.flags & 512) {
write("default ");
}
- else if (node.kind !== 215) {
+ else if (node.kind !== 215 && !noDeclare) {
write("declare ");
}
}
@@ -23601,7 +23905,7 @@ var ts;
write("export ");
}
write("import ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" = ");
if (ts.isInternalModuleImportEqualsDeclaration(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError);
@@ -23609,7 +23913,7 @@ var ts;
}
else {
write("require(");
- writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node));
+ writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node));
write(");");
}
writer.writeLine();
@@ -23643,7 +23947,7 @@ var ts;
if (node.importClause) {
var currentWriterPos = writer.getTextPos();
if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) {
- writeTextOfNode(currentSourceFile, node.importClause.name);
+ writeTextOfNode(currentText, node.importClause.name);
}
if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) {
if (currentWriterPos !== writer.getTextPos()) {
@@ -23651,7 +23955,7 @@ var ts;
}
if (node.importClause.namedBindings.kind === 224) {
write("* as ");
- writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name);
+ writeTextOfNode(currentText, node.importClause.namedBindings.name);
}
else {
write("{ ");
@@ -23661,16 +23965,28 @@ var ts;
}
write(" from ");
}
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
write(";");
writer.writeLine();
}
+ function emitExternalModuleSpecifier(moduleSpecifier) {
+ if (moduleSpecifier.kind === 9 && (!root) && (compilerOptions.out || compilerOptions.outFile)) {
+ var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent);
+ if (moduleName) {
+ write("\"");
+ write(moduleName);
+ write("\"");
+ return;
+ }
+ }
+ writeTextOfNode(currentText, moduleSpecifier);
+ }
function emitImportOrExportSpecifier(node) {
if (node.propertyName) {
- writeTextOfNode(currentSourceFile, node.propertyName);
+ writeTextOfNode(currentText, node.propertyName);
write(" as ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
function emitExportSpecifier(node) {
emitImportOrExportSpecifier(node);
@@ -23690,7 +24006,7 @@ var ts;
}
if (node.moduleSpecifier) {
write(" from ");
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
}
write(";");
writer.writeLine();
@@ -23704,11 +24020,11 @@ var ts;
else {
write("module ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
while (node.body.kind !== 219) {
node = node.body;
write(".");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
@@ -23727,7 +24043,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
@@ -23749,7 +24065,7 @@ var ts;
write("const ");
}
write("enum ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" {");
writeLine();
increaseIndent();
@@ -23760,7 +24076,7 @@ var ts;
}
function emitEnumMemberDeclaration(node) {
emitJsDocComments(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
@@ -23777,7 +24093,7 @@ var ts;
increaseIndent();
emitJsDocComments(node);
decreaseIndent();
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (node.constraint && !isPrivateMethodTypeParameter(node)) {
write(" extends ");
if (node.parent.kind === 152 ||
@@ -23887,7 +24203,7 @@ var ts;
write("abstract ");
}
write("class ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -23910,7 +24226,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("interface ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -23940,7 +24256,7 @@ var ts;
emitBindingPattern(node.name);
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if ((node.kind === 141 || node.kind === 140) && ts.hasQuestionToken(node)) {
write("?");
}
@@ -24014,7 +24330,7 @@ var ts;
emitBindingPattern(bindingElement.name);
}
else {
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError);
}
}
@@ -24055,7 +24371,7 @@ var ts;
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (!(node.flags & 16)) {
accessorWithTypeAnnotation = node;
var type = getTypeAnnotationFromAccessor(node);
@@ -24136,13 +24452,13 @@ var ts;
}
if (node.kind === 213) {
write("function ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
else if (node.kind === 144) {
write("constructor");
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (ts.hasQuestionToken(node)) {
write("?");
}
@@ -24255,7 +24571,7 @@ var ts;
emitBindingPattern(node.name);
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
if (resolver.isOptionalParameter(node)) {
write("?");
@@ -24354,7 +24670,7 @@ var ts;
}
else if (bindingElement.kind === 163) {
if (bindingElement.propertyName) {
- writeTextOfNode(currentSourceFile, bindingElement.propertyName);
+ writeTextOfNode(currentText, bindingElement.propertyName);
write(": ");
}
if (bindingElement.name) {
@@ -24366,7 +24682,7 @@ var ts;
if (bindingElement.dotDotDotToken) {
write("...");
}
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
}
}
}
@@ -24449,6 +24765,18 @@ var ts;
return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile);
}
ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile;
+ function getResolvedExternalModuleName(host, file) {
+ return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName);
+ }
+ ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
+ function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
+ var file = resolver.getExternalModuleFileFromDeclaration(declaration);
+ if (!file || ts.isDeclarationFile(file)) {
+ return undefined;
+ }
+ return getResolvedExternalModuleName(host, file);
+ }
+ ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
var entities = {
"quot": 0x0022,
"amp": 0x0026,
@@ -24718,15 +25046,19 @@ var ts;
var newLine = host.getNewLine();
var jsxDesugaring = host.getCompilerOptions().jsx !== 1;
var shouldEmitJsx = function (s) { return (s.languageVariant === 1 && !jsxDesugaring); };
+ var outFile = compilerOptions.outFile || compilerOptions.out;
+ var emitJavaScript = createFileEmitter();
if (targetSourceFile === undefined) {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
- var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
- emitFile(jsFilePath, sourceFile);
- }
- });
- if (compilerOptions.outFile || compilerOptions.out) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ if (outFile) {
+ emitFile(outFile);
+ }
+ else {
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
+ var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
+ emitFile(jsFilePath, sourceFile);
+ }
+ });
}
}
else {
@@ -24734,8 +25066,8 @@ var ts;
var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
- else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ else if (!ts.isDeclarationFile(targetSourceFile) && outFile) {
+ emitFile(outFile);
}
}
diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics);
@@ -24785,20 +25117,26 @@ var ts;
}
}
}
- function emitJavaScript(jsFilePath, root) {
+ function createFileEmitter() {
var writer = ts.createTextWriter(newLine);
var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;
var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentFileIdentifiers;
+ var renamedDependencies;
+ var isEs6Module;
+ var isCurrentFileExternalModule;
var exportFunctionForFile;
- var generatedNameSet = {};
- var nodeToGeneratedName = [];
+ var generatedNameSet;
+ var nodeToGeneratedName;
var computedPropertyNamesToGeneratedNames;
var convertedLoopState;
- var extendsEmitted = false;
- var decorateEmitted = false;
- var paramEmitted = false;
- var awaiterEmitted = false;
- var tempFlags = 0;
+ var extendsEmitted;
+ var decorateEmitted;
+ var paramEmitted;
+ var awaiterEmitted;
+ var tempFlags;
var tempVariables;
var tempParameters;
var externalImports;
@@ -24815,6 +25153,7 @@ var ts;
var scopeEmitStart = function (scopeDeclaration, scopeName) { };
var scopeEmitEnd = function () { };
var sourceMapData;
+ var root;
var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker;
var moduleEmitDelegates = (_a = {},
_a[5] = emitES6Module,
@@ -24824,30 +25163,75 @@ var ts;
_a[1] = emitCommonJSModule,
_a
);
- if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
- initializeEmitterWithSourceMaps();
- }
- if (root) {
- emitSourceFile(root);
- }
- else {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!isExternalModuleOrDeclarationFile(sourceFile)) {
- emitSourceFile(sourceFile);
+ var bundleEmitDelegates = (_b = {},
+ _b[5] = function () { },
+ _b[2] = emitAMDModule,
+ _b[4] = emitSystemModule,
+ _b[3] = function () { },
+ _b[1] = function () { },
+ _b
+ );
+ return doEmit;
+ function doEmit(jsFilePath, rootFile) {
+ writer.reset();
+ currentSourceFile = undefined;
+ currentText = undefined;
+ currentLineMap = undefined;
+ exportFunctionForFile = undefined;
+ generatedNameSet = {};
+ nodeToGeneratedName = [];
+ computedPropertyNamesToGeneratedNames = undefined;
+ convertedLoopState = undefined;
+ extendsEmitted = false;
+ decorateEmitted = false;
+ paramEmitted = false;
+ awaiterEmitted = false;
+ tempFlags = 0;
+ tempVariables = undefined;
+ tempParameters = undefined;
+ externalImports = undefined;
+ exportSpecifiers = undefined;
+ exportEquals = undefined;
+ hasExportStars = undefined;
+ detachedCommentsInfo = undefined;
+ sourceMapData = undefined;
+ isEs6Module = false;
+ renamedDependencies = undefined;
+ isCurrentFileExternalModule = false;
+ root = rootFile;
+ if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
+ initializeEmitterWithSourceMaps(jsFilePath, root);
+ }
+ if (root) {
+ emitSourceFile(root);
+ }
+ else {
+ if (modulekind) {
+ ts.forEach(host.getSourceFiles(), emitEmitHelpers);
}
- });
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) {
+ emitSourceFile(sourceFile);
+ }
+ });
+ }
+ writeLine();
+ writeEmittedFiles(writer.getText(), jsFilePath, compilerOptions.emitBOM);
}
- writeLine();
- writeEmittedFiles(writer.getText(), compilerOptions.emitBOM);
- return;
function emitSourceFile(sourceFile) {
currentSourceFile = sourceFile;
+ currentText = sourceFile.text;
+ currentLineMap = ts.getLineStarts(sourceFile);
exportFunctionForFile = undefined;
+ isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"];
+ renamedDependencies = sourceFile.renamedDependencies;
+ currentFileIdentifiers = sourceFile.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(sourceFile);
emit(sourceFile);
}
function isUniqueName(name) {
return !resolver.hasGlobalName(name) &&
- !ts.hasProperty(currentSourceFile.identifiers, name) &&
+ !ts.hasProperty(currentFileIdentifiers, name) &&
!ts.hasProperty(generatedNameSet, name);
}
function makeTempVariableName(flags) {
@@ -24920,7 +25304,7 @@ var ts;
var id = ts.getNodeId(node);
return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node)));
}
- function initializeEmitterWithSourceMaps() {
+ function initializeEmitterWithSourceMaps(jsFilePath, root) {
var sourceMapDir;
var sourceMapSourceIndex = -1;
var sourceMapNameIndexMap = {};
@@ -24989,7 +25373,7 @@ var ts;
}
}
function recordSourceMapSpan(pos) {
- var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos);
+ var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos);
sourceLinePos.line++;
sourceLinePos.character++;
var emittedLine = writer.getLine();
@@ -25017,13 +25401,13 @@ var ts;
}
}
function recordEmitNodeStartSpan(node) {
- recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos));
+ recordSourceMapSpan(ts.skipTrivia(currentText, node.pos));
}
function recordEmitNodeEndSpan(node) {
recordSourceMapSpan(node.end);
}
function writeTextWithSpanRecord(tokenKind, startPos, emitFn) {
- var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);
+ var tokenStartPos = ts.skipTrivia(currentText, startPos);
recordSourceMapSpan(tokenStartPos);
var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);
recordSourceMapSpan(tokenEndPos);
@@ -25093,9 +25477,9 @@ var ts;
sourceMapNameIndices.pop();
}
;
- function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) {
+ function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) {
recordSourceMapSpan(comment.pos);
- ts.writeCommentRange(currentSourceFile, writer, comment, newLine);
+ ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine);
recordSourceMapSpan(comment.end);
}
function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) {
@@ -25125,7 +25509,7 @@ var ts;
return output;
}
}
- function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) {
encodeLastRecordedSourceMapSpan();
var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent);
sourceMapDataList.push(sourceMapData);
@@ -25138,7 +25522,7 @@ var ts;
ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, false);
sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL;
}
- writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);
+ writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark);
}
var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath));
sourceMapData = {
@@ -25201,7 +25585,7 @@ var ts;
scopeEmitEnd = recordScopeNameEnd;
writeComment = writeCommentRangeWithMap;
}
- function writeJavaScriptFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) {
ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
function createTempVariable(flags) {
@@ -25371,7 +25755,7 @@ var ts;
return getQuotedEscapedLiteralText("\"", node.text, "\"");
}
if (node.parent) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ return ts.getTextOfNodeFromSourceText(currentText, node);
}
switch (node.kind) {
case 9:
@@ -25393,7 +25777,7 @@ var ts;
return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote;
}
function emitDownlevelRawTemplateLiteral(node) {
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node);
var isLast = node.kind === 11 || node.kind === 14;
text = text.substring(1, text.length - (isLast ? 1 : 2));
text = text.replace(/\r\n?/g, "\n");
@@ -25723,7 +26107,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
write("\"");
}
@@ -25819,7 +26203,7 @@ var ts;
else if (declaration.kind === 226) {
write(getGeneratedNameForNode(declaration.parent.parent.parent));
var name_23 = declaration.propertyName || declaration.name;
- var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23);
+ var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23);
if (languageVersion === 0 && identifier === "default") {
write("[\"default\"]");
}
@@ -25843,7 +26227,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function isNameOfNestedRedeclaration(node) {
@@ -25880,7 +26264,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function emitThis(node) {
@@ -26247,8 +26631,8 @@ var ts;
return container && container.kind !== 248;
}
function emitShorthandPropertyAssignment(node) {
- writeTextOfNode(currentSourceFile, node.name);
- if (languageVersion < 2 || isNamespaceExportReference(node.name)) {
+ writeTextOfNode(currentText, node.name);
+ if (modulekind !== 5 || isNamespaceExportReference(node.name)) {
write(": ");
emit(node.name);
}
@@ -26298,10 +26682,10 @@ var ts;
}
emit(node.expression);
var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
- var shouldEmitSpace;
+ var shouldEmitSpace = false;
if (!indentedBeforeDot) {
if (node.expression.kind === 8) {
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node.expression);
shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0;
}
else {
@@ -27307,16 +27691,16 @@ var ts;
emitToken(16, node.clauses.end);
}
function nodeStartPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function nodeEndPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, node2.end);
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end);
}
function nodeEndIsOnSameLineAsNodeStart(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function emitCaseOrDefaultClause(node) {
if (node.kind === 241) {
@@ -27421,7 +27805,7 @@ var ts;
if (node.parent.kind === 248) {
ts.Debug.assert(!!(node.flags & 512) || node.kind === 227);
if (modulekind === 1 || modulekind === 2 || modulekind === 3) {
- if (!currentSourceFile.symbol.exports["___esModule"]) {
+ if (!isEs6Module) {
if (languageVersion === 1) {
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
writeLine();
@@ -27584,12 +27968,18 @@ var ts;
return node;
}
function createPropertyAccessForDestructuringProperty(object, propName) {
- var syntheticName = ts.createSynthesizedNode(propName.kind);
- syntheticName.text = propName.text;
- if (syntheticName.kind !== 69) {
- return createElementAccessExpression(object, syntheticName);
+ var index;
+ var nameIsComputed = propName.kind === 136;
+ if (nameIsComputed) {
+ index = ensureIdentifier(propName.expression, false);
}
- return createPropertyAccessExpression(object, syntheticName);
+ else {
+ index = ts.createSynthesizedNode(propName.kind);
+ index.text = propName.text;
+ }
+ return !nameIsComputed && index.kind === 69
+ ? createPropertyAccessExpression(object, index)
+ : createElementAccessExpression(object, index);
}
function createSliceCall(value, sliceIndex) {
var call = ts.createSynthesizedNode(168);
@@ -28003,7 +28393,6 @@ var ts;
var promiseConstructor = ts.getEntityNameFromTypeNode(node.type);
var isArrowFunction = node.kind === 174;
var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096) !== 0;
- var args;
if (!isArrowFunction) {
write(" {");
increaseIndent();
@@ -29177,8 +29566,8 @@ var ts;
}
}
function tryRenameExternalModule(moduleName) {
- if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
- return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\"";
+ if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) {
+ return "\"" + renamedDependencies[moduleName.text] + "\"";
}
return undefined;
}
@@ -29318,7 +29707,7 @@ var ts;
return;
}
if (resolver.isReferencedAliasDeclaration(node) ||
- (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
+ (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
emitLeadingComments(node);
emitStart(node);
var variableDeclarationIsHoisted = shouldHoistVariable(node, true);
@@ -29530,7 +29919,7 @@ var ts;
function getLocalNameForExternalImport(node) {
var namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);
+ return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name);
}
if (node.kind === 222 && node.importClause) {
return getGeneratedNameForNode(node);
@@ -29803,7 +30192,7 @@ var ts;
ts.getEnclosingBlockScopeContainer(node).kind === 248;
}
function isCurrentFileSystemExternalModule() {
- return modulekind === 4 && ts.isExternalModule(currentSourceFile);
+ return modulekind === 4 && isCurrentFileExternalModule;
}
function emitSystemModuleBody(node, dependencyGroups, startIndex) {
emitVariableDeclarationsForImports();
@@ -29916,15 +30305,19 @@ var ts;
writeLine();
write("}");
}
- function emitSystemModule(node) {
+ function writeModuleName(node, emitRelativePathAsModuleName) {
+ var moduleName = node.moduleName;
+ if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) {
+ write("\"" + moduleName + "\", ");
+ }
+ }
+ function emitSystemModule(node, emitRelativePathAsModuleName) {
collectExternalModuleInfo(node);
ts.Debug.assert(!exportFunctionForFile);
exportFunctionForFile = makeUniqueName("exports");
writeLine();
write("System.register(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
+ writeModuleName(node, emitRelativePathAsModuleName);
write("[");
var groupIndices = {};
var dependencyGroups = [];
@@ -29942,6 +30335,12 @@ var ts;
if (i !== 0) {
write(", ");
}
+ if (emitRelativePathAsModuleName) {
+ var name_29 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
+ if (name_29) {
+ text = "\"" + name_29 + "\"";
+ }
+ }
write(text);
}
write("], function(" + exportFunctionForFile + ") {");
@@ -29955,7 +30354,7 @@ var ts;
writeLine();
write("});");
}
- function getAMDDependencyNames(node, includeNonAmdDependencies) {
+ function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
var aliasedModuleNames = [];
var unaliasedModuleNames = [];
var importAliasNames = [];
@@ -29972,6 +30371,12 @@ var ts;
for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) {
var importNode = externalImports_4[_c];
var externalModuleName = getExternalModuleNameText(importNode);
+ if (emitRelativePathAsModuleName) {
+ var name_30 = getExternalModuleNameFromDeclaration(host, resolver, importNode);
+ if (name_30) {
+ externalModuleName = "\"" + name_30 + "\"";
+ }
+ }
var importAliasName = getLocalNameForExternalImport(importNode);
if (includeNonAmdDependencies && importAliasName) {
aliasedModuleNames.push(externalModuleName);
@@ -29983,8 +30388,8 @@ var ts;
}
return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
}
- function emitAMDDependencies(node, includeNonAmdDependencies) {
- var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);
+ function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
+ var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName);
emitAMDDependencyList(dependencyNames);
write(", ");
emitAMDFactoryHeader(dependencyNames);
@@ -30011,15 +30416,13 @@ var ts;
}
write(") {");
}
- function emitAMDModule(node) {
+ function emitAMDModule(node, emitRelativePathAsModuleName) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
write("define(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
- emitAMDDependencies(node, true);
+ writeModuleName(node, emitRelativePathAsModuleName);
+ emitAMDDependencies(node, true, emitRelativePathAsModuleName);
increaseIndent();
var startIndex = emitDirectivePrologues(node.statements, true);
emitExportStarHelper();
@@ -30225,8 +30628,13 @@ var ts;
emitShebang();
emitDetachedCommentsAndUpdateCommentsInfo(node);
if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
- var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1];
- emitModule(node);
+ if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) {
+ var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1];
+ emitModule(node);
+ }
+ else {
+ bundleEmitDelegates[modulekind](node, true);
+ }
}
else {
var startIndex = emitDirectivePrologues(node.statements, false);
@@ -30470,7 +30878,7 @@ var ts;
return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos;
}
function getLeadingCommentsWithoutDetachedComments() {
- var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
+ var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@@ -30480,10 +30888,10 @@ var ts;
return leadingComments;
}
function isTripleSlashComment(comment) {
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 &&
+ if (currentText.charCodeAt(comment.pos + 1) === 47 &&
comment.pos + 2 < comment.end &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 47) {
- var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);
+ currentText.charCodeAt(comment.pos + 2) === 47) {
+ var textSubStr = currentText.substring(comment.pos, comment.end);
return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?
true : false;
@@ -30497,7 +30905,7 @@ var ts;
return getLeadingCommentsWithoutDetachedComments();
}
else {
- return ts.getLeadingCommentRangesOfNode(node, currentSourceFile);
+ return ts.getLeadingCommentRangesOfNodeFromText(node, currentText);
}
}
}
@@ -30505,7 +30913,7 @@ var ts;
function getTrailingCommentsToEmit(node) {
if (node.parent) {
if (node.parent.kind === 248 || node.end !== node.parent.end) {
- return ts.getTrailingCommentRanges(currentSourceFile.text, node.end);
+ return ts.getTrailingCommentRanges(currentText, node.end);
}
}
}
@@ -30528,22 +30936,22 @@ var ts;
leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment);
}
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
- ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment);
}
function emitTrailingComments(node) {
if (compilerOptions.removeComments) {
return;
}
var trailingComments = getTrailingCommentsToEmit(node);
- ts.emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment);
}
function emitTrailingCommentsOfPosition(pos) {
if (compilerOptions.removeComments) {
return;
}
- var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos);
- ts.emitComments(currentSourceFile, writer, trailingComments, true, newLine, writeComment);
+ var trailingComments = ts.getTrailingCommentRanges(currentText, pos);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment);
}
function emitLeadingCommentsOfPositionWorker(pos) {
if (compilerOptions.removeComments) {
@@ -30554,13 +30962,13 @@ var ts;
leadingComments = getLeadingCommentsWithoutDetachedComments();
}
else {
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos);
+ leadingComments = ts.getLeadingCommentRanges(currentText, pos);
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);
- ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment);
}
function emitDetachedCommentsAndUpdateCommentsInfo(node) {
- var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments);
+ var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments);
if (currentDetachedCommentInfo) {
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
@@ -30571,12 +30979,12 @@ var ts;
}
}
function emitShebang() {
- var shebang = ts.getShebang(currentSourceFile.text);
+ var shebang = ts.getShebang(currentText);
if (shebang) {
write(shebang);
}
}
- var _a;
+ var _a, _b;
}
function emitFile(jsFilePath, sourceFile) {
emitJavaScript(jsFilePath, sourceFile);
@@ -30632,11 +31040,11 @@ var ts;
if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
var failedLookupLocations = [];
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations };
}
- resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
@@ -30646,8 +31054,8 @@ var ts;
}
}
ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function loadNodeModuleFromFile(candidate, failedLookupLocation, host) {
- return ts.forEach(ts.moduleFileExtensions, tryLoad);
+ function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) {
+ return ts.forEach(extensions, tryLoad);
function tryLoad(ext) {
var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (host.fileExists(fileName)) {
@@ -30659,7 +31067,7 @@ var ts;
}
}
}
- function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) {
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) {
var packageJsonPath = ts.combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
var jsonContent;
@@ -30671,7 +31079,7 @@ var ts;
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
- var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
+ var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
if (result) {
return result;
}
@@ -30680,7 +31088,7 @@ var ts;
else {
failedLookupLocation.push(packageJsonPath);
}
- return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host);
+ return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName, directory, host) {
var failedLookupLocations = [];
@@ -30690,11 +31098,11 @@ var ts;
if (baseName !== "node_modules") {
var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
- result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
@@ -30719,9 +31127,10 @@ var ts;
var searchName;
var failedLookupLocations = [];
var referencedSourceFile;
+ var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions;
while (true) {
searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName));
- referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) {
+ referencedSourceFile = ts.forEach(extensions, function (extension) {
if (extension === ".tsx" && !compilerOptions.jsx) {
return undefined;
}
@@ -30749,10 +31158,8 @@ var ts;
ts.classicNameResolver = classicNameResolver;
ts.defaultInitCompilerOptions = {
module: 1,
- target: 0,
+ target: 1,
noImplicitAny: false,
- outDir: "built",
- rootDir: ".",
sourceMap: false
};
function createCompilerHost(options, setParentNodes) {
@@ -31110,35 +31517,47 @@ var ts;
if (file.imports) {
return;
}
+ var isJavaScriptFile = ts.isSourceFileJavaScript(file);
var imports;
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var node = _a[_i];
- collect(node, true);
+ collect(node, true, false);
}
file.imports = imports || emptyArray;
- function collect(node, allowRelativeModuleNames) {
- switch (node.kind) {
- case 222:
- case 221:
- case 228:
- var moduleNameExpr = ts.getExternalModuleName(node);
- if (!moduleNameExpr || moduleNameExpr.kind !== 9) {
+ return;
+ function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
+ if (!collectOnlyRequireCalls) {
+ switch (node.kind) {
+ case 222:
+ case 221:
+ case 228:
+ var moduleNameExpr = ts.getExternalModuleName(node);
+ if (!moduleNameExpr || moduleNameExpr.kind !== 9) {
+ break;
+ }
+ if (!moduleNameExpr.text) {
+ break;
+ }
+ if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
+ (imports || (imports = [])).push(moduleNameExpr);
+ }
break;
- }
- if (!moduleNameExpr.text) {
+ case 218:
+ if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) {
+ ts.forEachChild(node.body, function (node) {
+ collect(node, false, collectOnlyRequireCalls);
+ });
+ }
break;
- }
- if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
- (imports || (imports = [])).push(moduleNameExpr);
- }
- break;
- case 218:
- if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) {
- ts.forEachChild(node.body, function (node) {
- collect(node, false);
- });
- }
- break;
+ }
+ }
+ if (isJavaScriptFile) {
+ if (ts.isRequireCall(node)) {
+ (imports || (imports = [])).push(node.arguments[0]);
+ }
+ else {
+ ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, true); });
+ }
}
}
}
@@ -31225,7 +31644,6 @@ var ts;
}
processImportedModules(file, basePath);
if (isDefaultLib) {
- file.isDefaultLib = true;
files.unshift(file);
}
else {
@@ -31298,6 +31716,9 @@ var ts;
commonPathComponents.length = sourcePathComponents.length;
}
});
+ if (!commonPathComponents) {
+ return currentDirectory;
+ }
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
@@ -31380,10 +31801,12 @@ var ts;
if (options.module === 5 && languageVersion < 2) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
+ if (outFile && options.module && !(options.module === 2 || options.module === 4)) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
+ }
if (options.outDir ||
options.sourceRoot ||
- (options.mapRoot &&
- (!outFile || firstExternalModuleSourceFile !== undefined))) {
+ options.mapRoot) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
@@ -31862,20 +32285,20 @@ var ts;
var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (var i = 0; i < sysFiles.length; i++) {
- var name_29 = sysFiles[i];
- if (ts.fileExtensionIs(name_29, ".d.ts")) {
- var baseName = name_29.substr(0, name_29.length - ".d.ts".length);
+ var name_31 = sysFiles[i];
+ if (ts.fileExtensionIs(name_31, ".d.ts")) {
+ var baseName = name_31.substr(0, name_31.length - ".d.ts".length);
if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) {
- fileNames.push(name_29);
+ fileNames.push(name_31);
}
}
- else if (ts.fileExtensionIs(name_29, ".ts")) {
- if (!ts.contains(sysFiles, name_29 + "x")) {
- fileNames.push(name_29);
+ else if (ts.fileExtensionIs(name_31, ".ts")) {
+ if (!ts.contains(sysFiles, name_31 + "x")) {
+ fileNames.push(name_31);
}
}
else {
- fileNames.push(name_29);
+ fileNames.push(name_31);
}
}
}
@@ -31994,14 +32417,15 @@ var ts;
var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
return diagnostic.messageText;
}
+ function getRelativeFileName(fileName, host) {
+ return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName;
+ }
function reportDiagnosticSimply(diagnostic, host) {
var output = "";
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
- var relativeFileName = host
- ? ts.convertToRelativePath(diagnostic.file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); })
- : diagnostic.file.fileName;
- output += diagnostic.file.fileName + "(" + (line + 1) + "," + (character + 1) + "): ";
+ var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host);
+ output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine;
@@ -32030,6 +32454,7 @@ var ts;
var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character;
var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
+ var relativeFileName = getRelativeFileName(file.fileName, host);
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
@@ -32065,7 +32490,7 @@ var ts;
output += ts.sys.newLine;
}
output += ts.sys.newLine;
- output += file.fileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): ";
+ output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): ";
}
var categoryColor = categoryFormatMap[diagnostic.category];
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
@@ -32191,8 +32616,19 @@ var ts;
return;
}
}
+ if (!cachedConfigFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ reportDiagnostics([error], undefined);
+ ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
+ return;
+ }
var result = ts.parseConfigFileTextToJson(configFileName, cachedConfigFileText);
var configObject = result.config;
+ if (!configObject) {
+ reportDiagnostics([result.error], undefined);
+ ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
+ return;
+ }
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getDirectoryPath(configFileName));
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, undefined);
@@ -32455,10 +32891,10 @@ var ts;
function serializeCompilerOptions(options) {
var result = {};
var optionsNameMap = ts.getOptionNameMap().optionNameMap;
- for (var name_30 in options) {
- if (ts.hasProperty(options, name_30)) {
- var value = options[name_30];
- switch (name_30) {
+ for (var name_32 in options) {
+ if (ts.hasProperty(options, name_32)) {
+ var value = options[name_32];
+ switch (name_32) {
case "init":
case "watch":
case "version":
@@ -32466,17 +32902,17 @@ var ts;
case "project":
break;
default:
- var optionDefinition = optionsNameMap[name_30.toLowerCase()];
+ var optionDefinition = optionsNameMap[name_32.toLowerCase()];
if (optionDefinition) {
if (typeof optionDefinition.type === "string") {
- result[name_30] = value;
+ result[name_32] = value;
}
else {
var typeMap = optionDefinition.type;
for (var key in typeMap) {
if (ts.hasProperty(typeMap, key)) {
if (typeMap[key] === value)
- result[name_30] = key;
+ result[name_32] = key;
}
}
}
diff --git a/lib/tsserver.js b/lib/tsserver.js
index 2893dab82ef..9f0c1674080 100644
--- a/lib/tsserver.js
+++ b/lib/tsserver.js
@@ -665,7 +665,7 @@ var ts;
}
ts.fileExtensionIs = fileExtensionIs;
ts.supportedExtensions = [".ts", ".tsx", ".d.ts"];
- ts.moduleFileExtensions = ts.supportedExtensions;
+ ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx");
function isSupportedSourceFileName(fileName) {
if (!fileName) {
return false;
@@ -716,17 +716,16 @@ var ts;
}
function Signature(checker) {
}
+ function Node(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0;
+ this.parent = undefined;
+ }
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0;
- this.parent = undefined;
- }
- Node.prototype = { kind: kind };
- return Node;
- },
+ getNodeConstructor: function () { return Node; },
+ getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
getSignatureConstructor: function () { return Signature; }
@@ -1003,7 +1002,16 @@ var ts;
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
- _fs.writeFileSync(fileName, data, "utf8");
+ var fd;
+ try {
+ fd = _fs.openSync(fileName, "w");
+ _fs.writeSync(fd, data, undefined, "utf8");
+ }
+ finally {
+ if (fd !== undefined) {
+ _fs.closeSync(fd);
+ }
+ }
}
function getCanonicalPath(path) {
return useCaseSensitiveFileNames ? path.toLowerCase() : path;
@@ -1688,6 +1696,7 @@ var ts;
Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." },
+ Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -2148,7 +2157,7 @@ var ts;
function getCommentRanges(text, pos, trailing) {
var result;
var collecting = trailing || pos === 0;
- while (true) {
+ while (pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
case 13:
@@ -2217,6 +2226,7 @@ var ts;
}
return result;
}
+ return result;
}
function getLeadingCommentRanges(text, pos) {
return getCommentRanges(text, pos, false);
@@ -2312,7 +2322,7 @@ var ts;
error(ts.Diagnostics.Digit_expected);
}
}
- return +(text.substring(start, end));
+ return "" + +(text.substring(start, end));
}
function scanOctalDigits() {
var start = pos;
@@ -2704,7 +2714,7 @@ var ts;
return pos++, token = 36;
case 46:
if (isDigit(text.charCodeAt(pos + 1))) {
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8;
}
if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) {
@@ -2801,7 +2811,7 @@ var ts;
case 55:
case 56:
case 57:
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8;
case 58:
return pos++, token = 54;
@@ -3879,6 +3889,10 @@ var ts;
return file.externalModuleIndicator !== undefined;
}
ts.isExternalModule = isExternalModule;
+ function isExternalOrCommonJsModule(file) {
+ return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
+ }
+ ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
function isDeclarationFile(file) {
return (file.flags & 4096) !== 0;
}
@@ -3925,18 +3939,26 @@ var ts;
return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
+ function getLeadingCommentRangesOfNodeFromText(node, text) {
+ return ts.getLeadingCommentRanges(text, node.pos);
+ }
+ ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText;
function getJsDocComments(node, sourceFileOfNode) {
- var commentRanges = (node.kind === 138 || node.kind === 137) ?
- ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
- getLeadingCommentRangesOfNode(node, sourceFileOfNode);
- return ts.filter(commentRanges, isJsDocComment);
- function isJsDocComment(comment) {
- return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47;
- }
+ return getJsDocCommentsFromText(node, sourceFileOfNode.text);
}
ts.getJsDocComments = getJsDocComments;
+ function getJsDocCommentsFromText(node, text) {
+ var commentRanges = (node.kind === 138 || node.kind === 137) ?
+ ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
+ getLeadingCommentRangesOfNodeFromText(node, text);
+ return ts.filter(commentRanges, isJsDocComment);
+ function isJsDocComment(comment) {
+ return text.charCodeAt(comment.pos + 1) === 42 &&
+ text.charCodeAt(comment.pos + 2) === 42 &&
+ text.charCodeAt(comment.pos + 3) !== 47;
+ }
+ }
+ ts.getJsDocCommentsFromText = getJsDocCommentsFromText;
ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/;
ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
function isTypeNode(node) {
@@ -4465,6 +4487,41 @@ var ts;
return node.kind === 221 && node.moduleReference.kind !== 232;
}
ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
+ function isSourceFileJavaScript(file) {
+ return isInJavaScriptFile(file);
+ }
+ ts.isSourceFileJavaScript = isSourceFileJavaScript;
+ function isInJavaScriptFile(node) {
+ return node && !!(node.parserContextFlags & 32);
+ }
+ ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isRequireCall(expression) {
+ return expression.kind === 168 &&
+ expression.expression.kind === 69 &&
+ expression.expression.text === "require" &&
+ expression.arguments.length === 1 &&
+ expression.arguments[0].kind === 9;
+ }
+ ts.isRequireCall = isRequireCall;
+ function isExportsPropertyAssignment(expression) {
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181) &&
+ (expression.operatorToken.kind === 56) &&
+ (expression.left.kind === 166) &&
+ (expression.left.expression.kind === 69) &&
+ ((expression.left.expression).text === "exports");
+ }
+ ts.isExportsPropertyAssignment = isExportsPropertyAssignment;
+ function isModuleExportsAssignment(expression) {
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181) &&
+ (expression.operatorToken.kind === 56) &&
+ (expression.left.kind === 166) &&
+ (expression.left.expression.kind === 69) &&
+ ((expression.left.expression).text === "module") &&
+ (expression.left.name.text === "exports");
+ }
+ ts.isModuleExportsAssignment = isModuleExportsAssignment;
function getExternalModuleName(node) {
if (node.kind === 222) {
return node.moduleSpecifier;
@@ -4776,8 +4833,8 @@ var ts;
function getFileReferenceFromReferencePath(comment, commentRange) {
var simpleReferenceRegEx = /^\/\/\/\s*/gim;
- if (simpleReferenceRegEx.exec(comment)) {
- if (isNoDefaultLibRegEx.exec(comment)) {
+ if (simpleReferenceRegEx.test(comment)) {
+ if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
@@ -4819,12 +4876,20 @@ var ts;
return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node);
}
ts.isAsyncFunctionLike = isAsyncFunctionLike;
+ function isStringOrNumericLiteral(kind) {
+ return kind === 9 || kind === 8;
+ }
+ ts.isStringOrNumericLiteral = isStringOrNumericLiteral;
function hasDynamicName(declaration) {
- return declaration.name &&
- declaration.name.kind === 136 &&
- !isWellKnownSymbolSyntactically(declaration.name.expression);
+ return declaration.name && isDynamicName(declaration.name);
}
ts.hasDynamicName = hasDynamicName;
+ function isDynamicName(name) {
+ return name.kind === 136 &&
+ !isStringOrNumericLiteral(name.expression.kind) &&
+ !isWellKnownSymbolSyntactically(name.expression);
+ }
+ ts.isDynamicName = isDynamicName;
function isWellKnownSymbolSyntactically(node) {
return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
}
@@ -5045,11 +5110,11 @@ var ts;
}
ts.getIndentSize = getIndentSize;
function createTextWriter(newLine) {
- var output = "";
- var indent = 0;
- var lineStart = true;
- var lineCount = 0;
- var linePos = 0;
+ var output;
+ var indent;
+ var lineStart;
+ var lineCount;
+ var linePos;
function write(s) {
if (s && s.length) {
if (lineStart) {
@@ -5059,6 +5124,13 @@ var ts;
output += s;
}
}
+ function reset() {
+ output = "";
+ indent = 0;
+ lineStart = true;
+ lineCount = 0;
+ linePos = 0;
+ }
function rawWrite(s) {
if (s !== undefined) {
if (lineStart) {
@@ -5085,9 +5157,10 @@ var ts;
lineStart = true;
}
}
- function writeTextOfNode(sourceFile, node) {
- write(getSourceTextOfNodeFromSourceFile(sourceFile, node));
+ function writeTextOfNode(text, node) {
+ write(getTextOfNodeFromSourceText(text, node));
}
+ reset();
return {
write: write,
rawWrite: rawWrite,
@@ -5100,10 +5173,17 @@ var ts;
getTextPos: function () { return output.length; },
getLine: function () { return lineCount + 1; },
getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; },
- getText: function () { return output; }
+ getText: function () { return output; },
+ reset: reset
};
}
ts.createTextWriter = createTextWriter;
+ function getExternalModuleNameFromPath(host, fileName) {
+ var dir = host.getCurrentDirectory();
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, false);
+ return ts.removeFileExtension(relativePath);
+ }
+ ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
var compilerOptions = host.getCompilerOptions();
var emitOutputFilePathWithoutExtension;
@@ -5132,6 +5212,10 @@ var ts;
return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
ts.getLineOfLocalPosition = getLineOfLocalPosition;
+ function getLineOfLocalPositionFromLineMap(lineMap, pos) {
+ return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
+ }
+ ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
function getFirstConstructorWithBody(node) {
return ts.forEach(node.members, function (member) {
if (member.kind === 144 && nodeIsPresent(member.body)) {
@@ -5202,21 +5286,21 @@ var ts;
};
}
ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
- function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) {
+ function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
- getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) {
+ getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
}
}
ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
- function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) {
+ function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) {
var emitLeadingSpace = !trailingSeparator;
ts.forEach(comments, function (comment) {
if (emitLeadingSpace) {
writer.write(" ");
emitLeadingSpace = false;
}
- writeComment(currentSourceFile, writer, comment, newLine);
+ writeComment(text, lineMap, writer, comment, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
@@ -5229,16 +5313,16 @@ var ts;
});
}
ts.emitComments = emitComments;
- function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) {
+ function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
var leadingComments;
var currentDetachedCommentInfo;
if (removeComments) {
if (node.pos === 0) {
- leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment);
+ leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment);
}
}
else {
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ leadingComments = ts.getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
var detachedComments = [];
@@ -5246,8 +5330,8 @@ var ts;
for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
var comment = leadingComments_1[_i];
if (lastComment) {
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end);
- var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos);
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
+ var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
if (commentLine >= lastCommentLine + 2) {
break;
}
@@ -5256,37 +5340,37 @@ var ts;
lastComment = comment;
}
if (detachedComments.length) {
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end);
- var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end);
+ var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
- emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
- emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment);
+ emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
+ emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end };
}
}
}
return currentDetachedCommentInfo;
function isPinnedComment(comment) {
- return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 33;
+ return text.charCodeAt(comment.pos + 1) === 42 &&
+ text.charCodeAt(comment.pos + 2) === 33;
}
}
ts.emitDetachedComments = emitDetachedComments;
- function writeCommentRange(currentSourceFile, writer, comment, newLine) {
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42) {
- var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
- var lineCount = ts.getLineStarts(currentSourceFile).length;
+ function writeCommentRange(text, lineMap, writer, comment, newLine) {
+ if (text.charCodeAt(comment.pos + 1) === 42) {
+ var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos);
+ var lineCount = lineMap.length;
var firstCommentLineIndent;
for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
var nextLineStart = (currentLine + 1) === lineCount
- ? currentSourceFile.text.length + 1
- : getStartPositionOfLine(currentLine + 1, currentSourceFile);
+ ? text.length + 1
+ : lineMap[currentLine + 1];
if (pos !== comment.pos) {
if (firstCommentLineIndent === undefined) {
- firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
+ firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos);
}
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
- var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
+ var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
@@ -5300,40 +5384,40 @@ var ts;
writer.rawWrite("");
}
}
- writeTrimmedCurrentLine(pos, nextLineStart);
+ writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
- writer.write(currentSourceFile.text.substring(comment.pos, comment.end));
- }
- function writeTrimmedCurrentLine(pos, nextLineStart) {
- var end = Math.min(comment.end, nextLineStart - 1);
- var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
- if (currentLineText) {
- writer.write(currentLineText);
- if (end !== comment.end) {
- writer.writeLine();
- }
- }
- else {
- writer.writeLiteral(newLine);
- }
- }
- function calculateIndent(pos, end) {
- var currentLineIndent = 0;
- for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
- if (currentSourceFile.text.charCodeAt(pos) === 9) {
- currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
- }
- else {
- currentLineIndent++;
- }
- }
- return currentLineIndent;
+ writer.write(text.substring(comment.pos, comment.end));
}
}
ts.writeCommentRange = writeCommentRange;
+ function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) {
+ var end = Math.min(comment.end, nextLineStart - 1);
+ var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
+ if (currentLineText) {
+ writer.write(currentLineText);
+ if (end !== comment.end) {
+ writer.writeLine();
+ }
+ }
+ else {
+ writer.writeLiteral(newLine);
+ }
+ }
+ function calculateIndent(text, pos, end) {
+ var currentLineIndent = 0;
+ for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) {
+ if (text.charCodeAt(pos) === 9) {
+ currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
+ }
+ else {
+ currentLineIndent++;
+ }
+ }
+ return currentLineIndent;
+ }
function modifierToFlag(token) {
switch (token) {
case 113: return 64;
@@ -5427,14 +5511,14 @@ var ts;
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
- function isJavaScript(fileName) {
- return ts.fileExtensionIs(fileName, ".js");
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isJavaScript = isJavaScript;
- function isTsx(fileName) {
- return ts.fileExtensionIs(fileName, ".tsx");
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function allowsJsxExpressions(fileName) {
+ return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isTsx = isTsx;
+ ts.allowsJsxExpressions = allowsJsxExpressions;
function getExpandedCharCodes(input) {
var output = [];
var length = input.length;
@@ -5644,14 +5728,16 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var nodeConstructors = new Array(272);
ts.parseTime = 0;
- function getNodeConstructor(kind) {
- return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind));
- }
- ts.getNodeConstructor = getNodeConstructor;
+ var NodeConstructor;
+ var SourceFileConstructor;
function createNode(kind, pos, end) {
- return new (getNodeConstructor(kind))(pos, end);
+ if (kind === 248) {
+ return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
+ }
+ else {
+ return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
+ }
}
ts.createNode = createNode;
function visitNode(cbNode, node) {
@@ -6050,6 +6136,8 @@ var ts;
(function (Parser) {
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 1 | 4;
+ var NodeConstructor;
+ var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
var syntaxCursor;
@@ -6062,13 +6150,16 @@ var ts;
var contextFlags;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) {
- initializeState(fileName, _sourceText, languageVersion, _syntaxCursor);
+ var isJavaScriptFile = ts.hasJavaScriptFileExtension(fileName) || _sourceText.lastIndexOf("// @language=javascript", 0) === 0;
+ initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes);
clearState();
return result;
}
Parser.parseSourceFile = parseSourceFile;
- function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) {
+ function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) {
+ NodeConstructor = ts.objectAllocator.getNodeConstructor();
+ SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
parseDiagnostics = [];
@@ -6076,12 +6167,12 @@ var ts;
identifiers = {};
identifierCount = 0;
nodeCount = 0;
- contextFlags = ts.isJavaScript(fileName) ? 32 : 0;
+ contextFlags = isJavaScriptFile ? 32 : 0;
parseErrorBeforeNextFinishedNode = false;
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
- scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 : 0);
+ scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 : 0);
}
function clearState() {
scanner.setText("");
@@ -6094,6 +6185,9 @@ var ts;
}
function parseSourceFileWorker(fileName, languageVersion, setParentNodes) {
sourceFile = createSourceFile(fileName, languageVersion);
+ if (contextFlags & 32) {
+ sourceFile.parserContextFlags = 32;
+ }
token = nextToken();
processReferenceComments(sourceFile);
sourceFile.statements = parseList(0, parseStatement);
@@ -6107,7 +6201,7 @@ var ts;
if (setParentNodes) {
fixupParentReferences(sourceFile);
}
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
addJSDocComments();
}
return sourceFile;
@@ -6153,15 +6247,14 @@ var ts;
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion) {
- var sourceFile = createNode(248, 0);
- sourceFile.pos = 0;
- sourceFile.end = sourceText.length;
+ var sourceFile = new SourceFileConstructor(248, 0, sourceText.length);
+ nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = ts.normalizePath(fileName);
sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0;
- sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 : 0;
+ sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 : 0;
return sourceFile;
}
function setContextFlag(val, flag) {
@@ -6383,7 +6476,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
- return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos);
+ return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -6521,7 +6614,7 @@ var ts;
case 12:
return token === 19 || token === 37 || isLiteralPropertyName();
case 9:
- return isLiteralPropertyName();
+ return token === 19 || isLiteralPropertyName();
case 7:
if (token === 15) {
return lookAhead(isValidHeritageClauseObjectLiteral);
@@ -7042,9 +7135,7 @@ var ts;
}
function parseParameterType() {
if (parseOptional(54)) {
- return token === 9
- ? parseLiteralNode(true)
- : parseType();
+ return parseType();
}
return undefined;
}
@@ -7301,6 +7392,8 @@ var ts;
case 131:
var node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
+ case 9:
+ return parseLiteralNode(true);
case 103:
case 97:
return parseTokenNode();
@@ -7330,6 +7423,7 @@ var ts;
case 19:
case 25:
case 92:
+ case 9:
return true;
case 17:
return lookAhead(isStartOfParenthesizedOrFunctionType);
@@ -7843,7 +7937,6 @@ var ts;
var unaryOperator = token;
var simpleUnaryExpression = parseSimpleUnaryExpression();
if (token === 38) {
- var diagnostic;
var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
if (simpleUnaryExpression.kind === 171) {
parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
@@ -9507,7 +9600,7 @@ var ts;
}
JSDocParser.isJSDocType = isJSDocType;
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState("file.js", content, 2, undefined);
+ initializeState("file.js", content, 2, true, undefined);
var jsDocTypeExpression = parseJSDocTypeExpression(start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -9758,7 +9851,7 @@ var ts;
}
}
function parseIsolatedJSDocComment(content, start, length) {
- initializeState("file.js", content, 2, undefined);
+ initializeState("file.js", content, 2, true, undefined);
var jsDocComment = parseJSDocComment(undefined, start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -10394,6 +10487,9 @@ var ts;
}
if (node.name.kind === 136) {
var nameExpression = node.name.expression;
+ if (ts.isStringOrNumericLiteral(nameExpression.kind)) {
+ return nameExpression.text;
+ }
ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
}
@@ -10414,6 +10510,8 @@ var ts;
return "__export";
case 227:
return node.isExportEquals ? "export=" : "default";
+ case 181:
+ return "export=";
case 213:
case 214:
return node.flags & 512 ? "default" : undefined;
@@ -11033,6 +11131,14 @@ var ts;
case 69:
return checkStrictModeIdentifier(node);
case 181:
+ if (ts.isInJavaScriptFile(node)) {
+ if (ts.isExportsPropertyAssignment(node)) {
+ bindExportsPropertyAssignment(node);
+ }
+ else if (ts.isModuleExportsAssignment(node)) {
+ bindModuleExportsAssignment(node);
+ }
+ }
return checkStrictModeBinaryExpression(node);
case 244:
return checkStrictModeCatchClause(node);
@@ -11092,6 +11198,11 @@ var ts;
checkStrictModeFunctionName(node);
var bindingName = node.name ? node.name.text : "__function";
return bindAnonymousDeclaration(node, 16, bindingName);
+ case 168:
+ if (ts.isInJavaScriptFile(node)) {
+ bindCallExpression(node);
+ }
+ break;
case 186:
case 214:
return bindClassLikeDeclaration(node);
@@ -11121,14 +11232,18 @@ var ts;
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (ts.isExternalModule(file)) {
- bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\"");
+ bindSourceFileAsExternalModule();
}
}
+ function bindSourceFileAsExternalModule() {
+ bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\"");
+ }
function bindExportAssignment(node) {
+ var boundExpression = node.kind === 227 ? node.expression : node.right;
if (!container.symbol || !container.symbol.exports) {
bindAnonymousDeclaration(node, 8388608, getDeclarationName(node));
}
- else if (node.expression.kind === 69) {
+ else if (boundExpression.kind === 69) {
declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608);
}
else {
@@ -11148,6 +11263,25 @@ var ts;
declareSymbolAndAddToSymbolTable(node, 8388608, 8388608);
}
}
+ function setCommonJsModuleIndicator(node) {
+ if (!file.commonJsModuleIndicator) {
+ file.commonJsModuleIndicator = node;
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindExportsPropertyAssignment(node) {
+ setCommonJsModuleIndicator(node);
+ declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0);
+ }
+ function bindModuleExportsAssignment(node) {
+ setCommonJsModuleIndicator(node);
+ bindExportAssignment(node);
+ }
+ function bindCallExpression(node) {
+ if (!file.commonJsModuleIndicator && ts.isRequireCall(node)) {
+ setCommonJsModuleIndicator(node);
+ }
+ }
function bindClassLikeDeclaration(node) {
if (node.kind === 214) {
bindBlockScopedDeclaration(node, 32, 899519);
@@ -11268,7 +11402,7 @@ var ts;
function checkUnreachable(node) {
switch (currentReachabilityState) {
case 4:
- var reportError = ts.isStatement(node) ||
+ var reportError = (ts.isStatement(node) && node.kind !== 194) ||
node.kind === 214 ||
(node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) ||
(node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
@@ -11364,7 +11498,7 @@ var ts;
symbolToString: symbolToString,
getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
getRootSymbols: getRootSymbols,
- getContextualType: getContextualType,
+ getContextualType: getApparentTypeOfContextualType,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: getResolvedSignature,
getConstantValue: getConstantValue,
@@ -11620,7 +11754,7 @@ var ts;
return ts.getAncestor(node, 248);
}
function isGlobalSourceFile(node) {
- return node.kind === 248 && !ts.isExternalModule(node);
+ return node.kind === 248 && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning && ts.hasProperty(symbols, name)) {
@@ -11706,23 +11840,24 @@ var ts;
}
switch (location.kind) {
case 248:
- if (!ts.isExternalModule(location))
+ if (!ts.isExternalOrCommonJsModule(location))
break;
case 218:
var moduleExports = getSymbolOfNode(location).exports;
if (location.kind === 248 ||
(location.kind === 218 && location.name.kind === 9)) {
+ if (result = moduleExports["default"]) {
+ var localSymbol = ts.getLocalSymbolForExportDefault(result);
+ if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
+ break loop;
+ }
+ result = undefined;
+ }
if (ts.hasProperty(moduleExports, name) &&
moduleExports[name].flags === 8388608 &&
ts.getDeclarationOfKind(moduleExports[name], 230)) {
break;
}
- result = moduleExports["default"];
- var localSymbol = ts.getLocalSymbolForExportDefault(result);
- if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) {
- break loop;
- }
- result = undefined;
}
if (result = getSymbol(moduleExports, name, meaning & 8914931)) {
break loop;
@@ -12080,6 +12215,9 @@ var ts;
if (moduleName === undefined) {
return;
}
+ if (moduleName.indexOf("!") >= 0) {
+ moduleName = moduleName.substr(0, moduleName.indexOf("!"));
+ }
var isRelative = ts.isExternalModuleNameRelative(moduleName);
if (!isRelative) {
var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512);
@@ -12250,7 +12388,7 @@ var ts;
}
switch (location_1.kind) {
case 248:
- if (!ts.isExternalModule(location_1)) {
+ if (!ts.isExternalOrCommonJsModule(location_1)) {
break;
}
case 218:
@@ -12377,7 +12515,7 @@ var ts;
}
function hasExternalModuleSymbol(declaration) {
return (declaration.kind === 218 && declaration.name.kind === 9) ||
- (declaration.kind === 248 && ts.isExternalModule(declaration));
+ (declaration.kind === 248 && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol) {
var aliasesToMakeVisible;
@@ -12575,7 +12713,7 @@ var ts;
writeAnonymousType(type, flags);
}
else if (type.flags & 256) {
- writer.writeStringLiteral(type.text);
+ writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\"");
}
else {
writePunctuation(writer, 15);
@@ -12939,7 +13077,7 @@ var ts;
}
}
else if (node.kind === 248) {
- return ts.isExternalModule(node) ? node : undefined;
+ return ts.isExternalOrCommonJsModule(node) ? node : undefined;
}
}
ts.Debug.fail("getContainingModule cant reach here");
@@ -13144,6 +13282,23 @@ var ts;
var symbol = getSymbolOfNode(node);
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);
}
+ function getTextOfPropertyName(name) {
+ switch (name.kind) {
+ case 69:
+ return name.text;
+ case 9:
+ case 8:
+ return name.text;
+ case 136:
+ if (ts.isStringOrNumericLiteral(name.expression.kind)) {
+ return name.expression.text;
+ }
+ }
+ return undefined;
+ }
+ function isComputedNonLiteralName(name) {
+ return name.kind === 136 && !ts.isStringOrNumericLiteral(name.expression.kind);
+ }
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
@@ -13159,8 +13314,12 @@ var ts;
var type;
if (pattern.kind === 161) {
var name_11 = declaration.propertyName || declaration.name;
- type = getTypeOfPropertyOfType(parentType, name_11.text) ||
- isNumericLiteralName(name_11.text) && getIndexTypeOfType(parentType, 1) ||
+ if (isComputedNonLiteralName(name_11)) {
+ return anyType;
+ }
+ var text = getTextOfPropertyName(name_11);
+ type = getTypeOfPropertyOfType(parentType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) ||
getIndexTypeOfType(parentType, 0);
if (!type) {
error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11));
@@ -13238,10 +13397,16 @@ var ts;
}
function getTypeFromObjectBindingPattern(pattern, includePatternInType) {
var members = {};
+ var hasComputedProperties = false;
ts.forEach(pattern.elements, function (e) {
- var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0);
var name = e.propertyName || e.name;
- var symbol = createSymbol(flags, name.text);
+ if (isComputedNonLiteralName(name)) {
+ hasComputedProperties = true;
+ return;
+ }
+ var text = getTextOfPropertyName(name);
+ var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0);
+ var symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType);
symbol.bindingElement = e;
members[symbol.name] = symbol;
@@ -13250,6 +13415,9 @@ var ts;
if (includePatternInType) {
result.pattern = pattern;
}
+ if (hasComputedProperties) {
+ result.flags |= 67108864;
+ }
return result;
}
function getTypeFromArrayBindingPattern(pattern, includePatternInType) {
@@ -13300,6 +13468,12 @@ var ts;
if (declaration.kind === 227) {
return links.type = checkExpression(declaration.expression);
}
+ if (declaration.kind === 181) {
+ return links.type = checkExpression(declaration.right);
+ }
+ if (declaration.kind === 166) {
+ return checkExpressionCached(declaration.parent.right);
+ }
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
@@ -13549,17 +13723,19 @@ var ts;
}
function resolveBaseTypesOfClass(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
- var baseContructorType = getBaseConstructorTypeOfClass(type);
- if (!(baseContructorType.flags & 80896)) {
+ var baseConstructorType = getBaseConstructorTypeOfClass(type);
+ if (!(baseConstructorType.flags & 80896)) {
return;
}
var baseTypeNode = getBaseTypeNodeOfClass(type);
var baseType;
- if (baseContructorType.symbol && baseContructorType.symbol.flags & 32) {
- baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol);
+ var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
+ if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 &&
+ areAllOuterTypeParametersApplied(originalBaseType)) {
+ baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
}
else {
- var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments);
+ var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments);
if (!constructors.length) {
error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
return;
@@ -13584,6 +13760,15 @@ var ts;
type.resolvedBaseTypes.push(baseType);
}
}
+ function areAllOuterTypeParametersApplied(type) {
+ var outerTypeParameters = type.outerTypeParameters;
+ if (outerTypeParameters) {
+ var last = outerTypeParameters.length - 1;
+ var typeArguments = type.typeArguments;
+ return outerTypeParameters[last].symbol !== typeArguments[last].symbol;
+ }
+ return true;
+ }
function resolveBaseTypesOfInterface(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
@@ -13655,7 +13840,7 @@ var ts;
type.typeArguments = type.typeParameters;
type.thisType = createType(512 | 33554432);
type.thisType.symbol = symbol;
- type.thisType.constraint = getTypeWithThisArgument(type);
+ type.thisType.constraint = type;
}
}
return links.declaredType;
@@ -14130,14 +14315,19 @@ var ts;
type = getApparentType(type);
return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
}
+ function getApparentTypeOfTypeParameter(type) {
+ if (!type.resolvedApparentType) {
+ var constraintType = getConstraintOfTypeParameter(type);
+ while (constraintType && constraintType.flags & 512) {
+ constraintType = getConstraintOfTypeParameter(constraintType);
+ }
+ type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
+ }
+ return type.resolvedApparentType;
+ }
function getApparentType(type) {
if (type.flags & 512) {
- do {
- type = getConstraintOfTypeParameter(type);
- } while (type && type.flags & 512);
- if (!type) {
- type = emptyObjectType;
- }
+ type = getApparentTypeOfTypeParameter(type);
}
if (type.flags & 258) {
type = globalStringType;
@@ -14290,7 +14480,7 @@ var ts;
if (node.initializer) {
var signatureDeclaration = node.parent;
var signature = getSignatureFromDeclaration(signatureDeclaration);
- var parameterIndex = signatureDeclaration.parameters.indexOf(node);
+ var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node);
ts.Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
@@ -14385,6 +14575,16 @@ var ts;
}
return result;
}
+ function resolveExternalModuleTypeByLiteral(name) {
+ var moduleSym = resolveExternalModuleName(name, name);
+ if (moduleSym) {
+ var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
+ if (resolvedModuleSymbol) {
+ return getTypeOfSymbol(resolvedModuleSymbol);
+ }
+ }
+ return anyType;
+ }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3)) {
@@ -14846,11 +15046,12 @@ var ts;
return links.resolvedType;
}
function getStringLiteralType(node) {
- if (ts.hasProperty(stringLiteralTypes, node.text)) {
- return stringLiteralTypes[node.text];
+ var text = node.text;
+ if (ts.hasProperty(stringLiteralTypes, text)) {
+ return stringLiteralTypes[text];
}
- var type = stringLiteralTypes[node.text] = createType(256);
- type.text = ts.getTextOfNode(node);
+ var type = stringLiteralTypes[text] = createType(256);
+ type.text = text;
return type;
}
function getTypeFromStringLiteral(node) {
@@ -15319,7 +15520,7 @@ var ts;
return false;
}
function hasExcessProperties(source, target, reportErrors) {
- if (someConstituentTypeHasKind(target, 80896)) {
+ if (!(target.flags & 67108864) && someConstituentTypeHasKind(target, 80896)) {
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
if (!isKnownProperty(target, prop.name)) {
@@ -15409,9 +15610,6 @@ var ts;
return result;
}
function typeParameterIdenticalTo(source, target) {
- if (source.symbol.name !== target.symbol.name) {
- return 0;
- }
if (source.constraint === target.constraint) {
return -1;
}
@@ -15856,18 +16054,24 @@ var ts;
}
return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
}
+ function isMatchingSignature(source, target, partialMatch) {
+ if (source.parameters.length === target.parameters.length &&
+ source.minArgumentCount === target.minArgumentCount &&
+ source.hasRestParameter === target.hasRestParameter) {
+ return true;
+ }
+ if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter ||
+ source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) {
+ return true;
+ }
+ return false;
+ }
function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) {
if (source === target) {
return -1;
}
- if (source.parameters.length !== target.parameters.length ||
- source.minArgumentCount !== target.minArgumentCount ||
- source.hasRestParameter !== target.hasRestParameter) {
- if (!partialMatch ||
- source.parameters.length < target.parameters.length && !source.hasRestParameter ||
- source.minArgumentCount > target.minArgumentCount) {
- return 0;
- }
+ if (!(isMatchingSignature(source, target, partialMatch))) {
+ return 0;
}
var result = -1;
if (source.typeParameters && target.typeParameters) {
@@ -15952,6 +16156,9 @@ var ts;
function isTupleLikeType(type) {
return !!getPropertyOfType(type, "0");
}
+ function isStringLiteralType(type) {
+ return type.flags & 256;
+ }
function isTupleType(type) {
return !!(type.flags & 8192);
}
@@ -16543,7 +16750,7 @@ var ts;
}
}
function narrowTypeByInstanceof(type, expr, assumeTrue) {
- if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) {
+ if (isTypeAny(type) || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) {
return type;
}
var rightType = checkExpression(expr.right);
@@ -16571,6 +16778,12 @@ var ts;
}
}
if (targetType) {
+ if (!assumeTrue) {
+ if (type.flags & 16384) {
+ return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); }));
+ }
+ return type;
+ }
return getNarrowedType(type, targetType);
}
return type;
@@ -16982,6 +17195,9 @@ var ts;
function getIndexTypeOfContextualType(type, kind) {
return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); });
}
+ function contextualTypeIsStringLiteralType(type) {
+ return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type));
+ }
function contextualTypeIsTupleLikeType(type) {
return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type));
}
@@ -16997,7 +17213,7 @@ var ts;
}
function getContextualTypeForObjectLiteralElement(element) {
var objectLiteral = element.parent;
- var type = getContextualType(objectLiteral);
+ var type = getApparentTypeOfContextualType(objectLiteral);
if (type) {
if (!ts.hasDynamicName(element)) {
var symbolName = getSymbolOfNode(element).name;
@@ -17013,7 +17229,7 @@ var ts;
}
function getContextualTypeForElementExpression(node) {
var arrayLiteral = node.parent;
- var type = getContextualType(arrayLiteral);
+ var type = getApparentTypeOfContextualType(arrayLiteral);
if (type) {
var index = ts.indexOf(arrayLiteral.elements, node);
return getTypeOfPropertyOfContextualType(type, "" + index)
@@ -17042,11 +17258,11 @@ var ts;
}
return undefined;
}
- function getContextualType(node) {
- var type = getContextualTypeWorker(node);
+ function getApparentTypeOfContextualType(node) {
+ var type = getContextualType(node);
return type && getApparentType(type);
}
- function getContextualTypeWorker(node) {
+ function getContextualType(node) {
if (isInsideWithStatementBody(node)) {
return undefined;
}
@@ -17112,7 +17328,7 @@ var ts;
ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node));
var type = ts.isObjectLiteralMethod(node)
? getContextualTypeForObjectLiteralMethod(node)
- : getContextualType(node);
+ : getApparentTypeOfContextualType(node);
if (!type) {
return undefined;
}
@@ -17195,7 +17411,7 @@ var ts;
type.pattern = node;
return type;
}
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
var pattern = contextualType.pattern;
if (pattern && (pattern.kind === 162 || pattern.kind === 164)) {
@@ -17250,10 +17466,11 @@ var ts;
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
var propertiesTable = {};
var propertiesArray = [];
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 161 || contextualType.pattern.kind === 165);
var typeFlags = 0;
+ var patternWithComputedProperties = false;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var memberDecl = _a[_i];
var member = memberDecl.symbol;
@@ -17279,8 +17496,11 @@ var ts;
if (isOptional) {
prop.flags |= 536870912;
}
+ if (ts.hasDynamicName(memberDecl)) {
+ patternWithComputedProperties = true;
+ }
}
- else if (contextualTypeHasPattern) {
+ else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) {
var impliedProp = getPropertyOfType(contextualType, member.name);
if (impliedProp) {
prop.flags |= impliedProp.flags & 536870912;
@@ -17323,7 +17543,7 @@ var ts;
var numberIndexType = getIndexType(1);
var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType);
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576;
- result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064);
+ result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0);
if (inDestructuringPattern) {
result.pattern = node;
}
@@ -18538,6 +18758,9 @@ var ts;
return anyType;
}
}
+ if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node)) {
+ return resolveExternalModuleTypeByLiteral(node.arguments[0]);
+ }
return getReturnTypeOfSignature(signature);
}
function checkTaggedTemplateExpression(node) {
@@ -18548,7 +18771,9 @@ var ts;
var targetType = getTypeFromTypeNode(node.type);
if (produceDiagnostics && targetType !== unknownType) {
var widenedType = getWidenedType(exprType);
- if (!(isTypeAssignableTo(targetType, widenedType))) {
+ var bothAreStringLike = someConstituentTypeHasKind(targetType, 258) &&
+ someConstituentTypeHasKind(widenedType, 258);
+ if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) {
checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other);
}
}
@@ -18987,17 +19212,24 @@ var ts;
var p = properties_3[_i];
if (p.kind === 245 || p.kind === 246) {
var name_14 = p.name;
+ if (name_14.kind === 136) {
+ checkComputedPropertyName(name_14);
+ }
+ if (isComputedNonLiteralName(name_14)) {
+ continue;
+ }
+ var text = getTextOfPropertyName(name_14);
var type = isTypeAny(sourceType)
? sourceType
- : getTypeOfPropertyOfType(sourceType, name_14.text) ||
- isNumericLiteralName(name_14.text) && getIndexTypeOfType(sourceType, 1) ||
+ : getTypeOfPropertyOfType(sourceType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1) ||
getIndexTypeOfType(sourceType, 0);
if (type) {
if (p.kind === 246) {
checkDestructuringAssignment(p, type);
}
else {
- checkDestructuringAssignment(p.initializer || name_14, type);
+ checkDestructuringAssignment(p.initializer, type);
}
}
else {
@@ -19175,6 +19407,9 @@ var ts;
case 31:
case 32:
case 33:
+ if (someConstituentTypeHasKind(leftType, 258) && someConstituentTypeHasKind(rightType, 258)) {
+ return booleanType;
+ }
if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) {
reportOperatorError();
}
@@ -19282,6 +19517,13 @@ var ts;
var type2 = checkExpression(node.whenFalse, contextualMapper);
return getUnionType([type1, type2]);
}
+ function checkStringLiteralExpression(node) {
+ var contextualType = getContextualType(node);
+ if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
+ return getStringLiteralType(node);
+ }
+ return stringType;
+ }
function checkTemplateExpression(node) {
ts.forEach(node.templateSpans, function (templateSpan) {
checkExpression(templateSpan.expression);
@@ -19320,7 +19562,7 @@ var ts;
if (isInferentialContext(contextualMapper)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(contextualType);
if (contextualSignature && !contextualSignature.typeParameters) {
@@ -19372,6 +19614,7 @@ var ts;
case 183:
return checkTemplateExpression(node);
case 9:
+ return checkStringLiteralExpression(node);
case 11:
return stringType;
case 10:
@@ -20433,7 +20676,7 @@ var ts;
return;
}
var parent = getDeclarationContainer(node);
- if (parent.kind === 248 && ts.isExternalModule(parent)) {
+ if (parent.kind === 248 && ts.isExternalOrCommonJsModule(parent)) {
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
}
@@ -20504,6 +20747,11 @@ var ts;
checkExpressionCached(node.initializer);
}
}
+ if (node.kind === 163) {
+ if (node.propertyName && node.propertyName.kind === 136) {
+ checkComputedPropertyName(node.propertyName);
+ }
+ }
if (ts.isBindingPattern(node.name)) {
ts.forEach(node.name.elements, checkSourceElement);
}
@@ -20862,6 +21110,7 @@ var ts;
var firstDefaultClause;
var hasDuplicateDefaultClause = false;
var expressionType = checkExpression(node.expression);
+ var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258);
ts.forEach(node.caseBlock.clauses, function (clause) {
if (clause.kind === 242 && !hasDuplicateDefaultClause) {
if (firstDefaultClause === undefined) {
@@ -20878,6 +21127,9 @@ var ts;
if (produceDiagnostics && clause.kind === 241) {
var caseClause = clause;
var caseType = checkExpression(caseClause.expression);
+ if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258)) {
+ return;
+ }
if (!isTypeAssignableTo(expressionType, caseType)) {
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, undefined);
}
@@ -21285,11 +21537,14 @@ var ts;
var enumIsConst = ts.isConst(node);
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.name.kind === 136) {
+ if (isComputedNonLiteralName(member.name)) {
error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
}
- else if (isNumericLiteralName(member.name.text)) {
- error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ else {
+ var text = getTextOfPropertyName(member.name);
+ if (isNumericLiteralName(text)) {
+ error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ }
}
var previousEnumMemberIsNonConstant = autoValue === undefined;
var initializer = member.initializer;
@@ -21987,8 +22242,10 @@ var ts;
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
if (!(links.flags & 1)) {
- if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) {
- return;
+ if (compilerOptions.skipDefaultLibCheck) {
+ if (node.hasNoDefaultLib) {
+ return;
+ }
}
checkGrammarSourceFile(node);
emitExtends = false;
@@ -21997,7 +22254,7 @@ var ts;
potentialThisCollisions.length = 0;
ts.forEach(node.statements, checkSourceElement);
checkFunctionAndClassExpressionBodies(node);
- if (ts.isExternalModule(node)) {
+ if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
if (potentialThisCollisions.length) {
@@ -22075,7 +22332,7 @@ var ts;
}
switch (location.kind) {
case 248:
- if (!ts.isExternalModule(location)) {
+ if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
case 218:
@@ -22634,15 +22891,24 @@ var ts;
getReferencedValueDeclaration: getReferencedValueDeclaration,
getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
isOptionalParameter: isOptionalParameter,
- isArgumentsLocalBinding: isArgumentsLocalBinding
+ isArgumentsLocalBinding: isArgumentsLocalBinding,
+ getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration
};
}
+ function getExternalModuleFileFromDeclaration(declaration) {
+ var specifier = ts.getExternalModuleName(declaration);
+ var moduleSymbol = getSymbolAtLocation(specifier);
+ if (!moduleSymbol) {
+ return undefined;
+ }
+ return ts.getDeclarationOfKind(moduleSymbol, 248);
+ }
function initializeTypeChecker() {
ts.forEach(host.getSourceFiles(), function (file) {
ts.bindSourceFile(file, compilerOptions);
});
ts.forEach(host.getSourceFiles(), function (file) {
- if (!ts.isExternalModule(file)) {
+ if (!ts.isExternalOrCommonJsModule(file)) {
mergeSymbolTable(globals, file.locals);
}
});
@@ -23319,7 +23585,7 @@ var ts;
}
}
function checkGrammarForNonSymbolComputedProperty(node, message) {
- if (node.kind === 136 && !ts.isWellKnownSymbolSyntactically(node.expression)) {
+ if (ts.isDynamicName(node)) {
return grammarErrorOnNode(node, message);
}
}
@@ -23633,11 +23899,15 @@ var ts;
var writeTextOfNode;
var writer = createAndSetNewTextWriterWithSymbolWriter();
var enclosingDeclaration;
- var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentIdentifiers;
+ var isCurrentFileExternalModule;
var reportedDeclarationError = false;
var errorNameNode;
var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments;
var emit = compilerOptions.stripInternal ? stripInternal : emitNode;
+ var noDeclare = !root;
var moduleElementDeclarationEmitInfo = [];
var asynchronousSubModuleDeclarationEmitInfo;
var referencePathsOutput = "";
@@ -23673,21 +23943,53 @@ var ts;
}
else {
var emittedReferencedFiles = [];
+ var prevModuleElementDeclarationEmitInfo = [];
ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ if (!ts.isDeclarationFile(sourceFile)) {
if (!compilerOptions.noResolve) {
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
- if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) &&
+ if (referencedFile && (ts.isDeclarationFile(referencedFile) &&
!ts.contains(emittedReferencedFiles, referencedFile))) {
writeReferencePath(referencedFile);
emittedReferencedFiles.push(referencedFile);
}
});
}
+ }
+ if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ noDeclare = false;
emitSourceFile(sourceFile);
}
+ else if (ts.isExternalModule(sourceFile)) {
+ noDeclare = true;
+ write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {");
+ writeLine();
+ increaseIndent();
+ emitSourceFile(sourceFile);
+ decreaseIndent();
+ write("}");
+ writeLine();
+ if (moduleElementDeclarationEmitInfo.length) {
+ var oldWriter = writer;
+ ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) {
+ if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
+ ts.Debug.assert(aliasEmitInfo.node.kind === 222);
+ createAndSetNewTextWriterWithSymbolWriter();
+ ts.Debug.assert(aliasEmitInfo.indent === 1);
+ increaseIndent();
+ writeImportDeclaration(aliasEmitInfo.node);
+ aliasEmitInfo.asynchronousOutput = writer.getText();
+ decreaseIndent();
+ }
+ });
+ setWriter(oldWriter);
+ }
+ prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
+ moduleElementDeclarationEmitInfo = [];
+ }
});
+ moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo);
}
return {
reportedDeclarationError: reportedDeclarationError,
@@ -23696,13 +23998,12 @@ var ts;
referencePathsOutput: referencePathsOutput
};
function hasInternalAnnotation(range) {
- var text = currentSourceFile.text;
- var comment = text.substring(range.pos, range.end);
+ var comment = currentText.substring(range.pos, range.end);
return comment.indexOf("@internal") >= 0;
}
function stripInternal(node) {
if (node) {
- var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos);
if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
return;
}
@@ -23783,7 +24084,7 @@ var ts;
var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
- diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
+ diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
}
else {
diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
@@ -23847,9 +24148,9 @@ var ts;
}
function writeJsDocComments(declaration) {
if (declaration) {
- var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile);
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments);
- ts.emitComments(currentSourceFile, writer, jsDocComments, true, newLine, ts.writeCommentRange);
+ var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
+ ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange);
}
}
function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) {
@@ -23866,7 +24167,7 @@ var ts;
case 103:
case 97:
case 9:
- return writeTextOfNode(currentSourceFile, type);
+ return writeTextOfNode(currentText, type);
case 188:
return emitExpressionWithTypeArguments(type);
case 151:
@@ -23897,14 +24198,14 @@ var ts;
}
function writeEntityName(entityName) {
if (entityName.kind === 69) {
- writeTextOfNode(currentSourceFile, entityName);
+ writeTextOfNode(currentText, entityName);
}
else {
var left = entityName.kind === 135 ? entityName.left : entityName.expression;
var right = entityName.kind === 135 ? entityName.right : entityName.name;
writeEntityName(left);
write(".");
- writeTextOfNode(currentSourceFile, right);
+ writeTextOfNode(currentText, right);
}
}
function emitEntityName(entityName) {
@@ -23932,7 +24233,7 @@ var ts;
}
}
function emitTypePredicate(type) {
- writeTextOfNode(currentSourceFile, type.parameterName);
+ writeTextOfNode(currentText, type.parameterName);
write(" is ");
emitType(type.type);
}
@@ -23972,20 +24273,23 @@ var ts;
}
}
function emitSourceFile(node) {
- currentSourceFile = node;
+ currentText = node.text;
+ currentLineMap = ts.getLineStarts(node);
+ currentIdentifiers = node.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(node);
enclosingDeclaration = node;
- ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true);
+ ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true);
emitLines(node.statements);
}
function getExportDefaultTempVariableName() {
var baseName = "_default";
- if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) {
+ if (!ts.hasProperty(currentIdentifiers, baseName)) {
return baseName;
}
var count = 0;
while (true) {
var name_19 = baseName + "_" + (++count);
- if (!ts.hasProperty(currentSourceFile.identifiers, name_19)) {
+ if (!ts.hasProperty(currentIdentifiers, name_19)) {
return name_19;
}
}
@@ -23993,7 +24297,7 @@ var ts;
function emitExportAssignment(node) {
if (node.expression.kind === 69) {
write(node.isExportEquals ? "export = " : "export default ");
- writeTextOfNode(currentSourceFile, node.expression);
+ writeTextOfNode(currentText, node.expression);
}
else {
var tempVarName = getExportDefaultTempVariableName();
@@ -24028,7 +24332,7 @@ var ts;
writeModuleElement(node);
}
else if (node.kind === 221 ||
- (node.parent.kind === 248 && ts.isExternalModule(currentSourceFile))) {
+ (node.parent.kind === 248 && isCurrentFileExternalModule)) {
var isVisible;
if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248) {
asynchronousSubModuleDeclarationEmitInfo.push({
@@ -24080,14 +24384,14 @@ var ts;
}
}
function emitModuleElementDeclarationFlags(node) {
- if (node.parent === currentSourceFile) {
+ if (node.parent.kind === 248) {
if (node.flags & 2) {
write("export ");
}
if (node.flags & 512) {
write("default ");
}
- else if (node.kind !== 215) {
+ else if (node.kind !== 215 && !noDeclare) {
write("declare ");
}
}
@@ -24112,7 +24416,7 @@ var ts;
write("export ");
}
write("import ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" = ");
if (ts.isInternalModuleImportEqualsDeclaration(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError);
@@ -24120,7 +24424,7 @@ var ts;
}
else {
write("require(");
- writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node));
+ writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node));
write(");");
}
writer.writeLine();
@@ -24154,7 +24458,7 @@ var ts;
if (node.importClause) {
var currentWriterPos = writer.getTextPos();
if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) {
- writeTextOfNode(currentSourceFile, node.importClause.name);
+ writeTextOfNode(currentText, node.importClause.name);
}
if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) {
if (currentWriterPos !== writer.getTextPos()) {
@@ -24162,7 +24466,7 @@ var ts;
}
if (node.importClause.namedBindings.kind === 224) {
write("* as ");
- writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name);
+ writeTextOfNode(currentText, node.importClause.namedBindings.name);
}
else {
write("{ ");
@@ -24172,16 +24476,28 @@ var ts;
}
write(" from ");
}
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
write(";");
writer.writeLine();
}
+ function emitExternalModuleSpecifier(moduleSpecifier) {
+ if (moduleSpecifier.kind === 9 && (!root) && (compilerOptions.out || compilerOptions.outFile)) {
+ var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent);
+ if (moduleName) {
+ write("\"");
+ write(moduleName);
+ write("\"");
+ return;
+ }
+ }
+ writeTextOfNode(currentText, moduleSpecifier);
+ }
function emitImportOrExportSpecifier(node) {
if (node.propertyName) {
- writeTextOfNode(currentSourceFile, node.propertyName);
+ writeTextOfNode(currentText, node.propertyName);
write(" as ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
function emitExportSpecifier(node) {
emitImportOrExportSpecifier(node);
@@ -24201,7 +24517,7 @@ var ts;
}
if (node.moduleSpecifier) {
write(" from ");
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
}
write(";");
writer.writeLine();
@@ -24215,11 +24531,11 @@ var ts;
else {
write("module ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
while (node.body.kind !== 219) {
node = node.body;
write(".");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
@@ -24238,7 +24554,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
@@ -24260,7 +24576,7 @@ var ts;
write("const ");
}
write("enum ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" {");
writeLine();
increaseIndent();
@@ -24271,7 +24587,7 @@ var ts;
}
function emitEnumMemberDeclaration(node) {
emitJsDocComments(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
@@ -24288,7 +24604,7 @@ var ts;
increaseIndent();
emitJsDocComments(node);
decreaseIndent();
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (node.constraint && !isPrivateMethodTypeParameter(node)) {
write(" extends ");
if (node.parent.kind === 152 ||
@@ -24398,7 +24714,7 @@ var ts;
write("abstract ");
}
write("class ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -24421,7 +24737,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("interface ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -24451,7 +24767,7 @@ var ts;
emitBindingPattern(node.name);
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if ((node.kind === 141 || node.kind === 140) && ts.hasQuestionToken(node)) {
write("?");
}
@@ -24525,7 +24841,7 @@ var ts;
emitBindingPattern(bindingElement.name);
}
else {
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError);
}
}
@@ -24566,7 +24882,7 @@ var ts;
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (!(node.flags & 16)) {
accessorWithTypeAnnotation = node;
var type = getTypeAnnotationFromAccessor(node);
@@ -24647,13 +24963,13 @@ var ts;
}
if (node.kind === 213) {
write("function ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
else if (node.kind === 144) {
write("constructor");
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (ts.hasQuestionToken(node)) {
write("?");
}
@@ -24766,7 +25082,7 @@ var ts;
emitBindingPattern(node.name);
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
if (resolver.isOptionalParameter(node)) {
write("?");
@@ -24865,7 +25181,7 @@ var ts;
}
else if (bindingElement.kind === 163) {
if (bindingElement.propertyName) {
- writeTextOfNode(currentSourceFile, bindingElement.propertyName);
+ writeTextOfNode(currentText, bindingElement.propertyName);
write(": ");
}
if (bindingElement.name) {
@@ -24877,7 +25193,7 @@ var ts;
if (bindingElement.dotDotDotToken) {
write("...");
}
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
}
}
}
@@ -24960,6 +25276,18 @@ var ts;
return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile);
}
ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile;
+ function getResolvedExternalModuleName(host, file) {
+ return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName);
+ }
+ ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
+ function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
+ var file = resolver.getExternalModuleFileFromDeclaration(declaration);
+ if (!file || ts.isDeclarationFile(file)) {
+ return undefined;
+ }
+ return getResolvedExternalModuleName(host, file);
+ }
+ ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
var entities = {
"quot": 0x0022,
"amp": 0x0026,
@@ -25229,15 +25557,19 @@ var ts;
var newLine = host.getNewLine();
var jsxDesugaring = host.getCompilerOptions().jsx !== 1;
var shouldEmitJsx = function (s) { return (s.languageVariant === 1 && !jsxDesugaring); };
+ var outFile = compilerOptions.outFile || compilerOptions.out;
+ var emitJavaScript = createFileEmitter();
if (targetSourceFile === undefined) {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
- var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
- emitFile(jsFilePath, sourceFile);
- }
- });
- if (compilerOptions.outFile || compilerOptions.out) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ if (outFile) {
+ emitFile(outFile);
+ }
+ else {
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
+ var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
+ emitFile(jsFilePath, sourceFile);
+ }
+ });
}
}
else {
@@ -25245,8 +25577,8 @@ var ts;
var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
- else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ else if (!ts.isDeclarationFile(targetSourceFile) && outFile) {
+ emitFile(outFile);
}
}
diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics);
@@ -25296,20 +25628,26 @@ var ts;
}
}
}
- function emitJavaScript(jsFilePath, root) {
+ function createFileEmitter() {
var writer = ts.createTextWriter(newLine);
var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;
var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentFileIdentifiers;
+ var renamedDependencies;
+ var isEs6Module;
+ var isCurrentFileExternalModule;
var exportFunctionForFile;
- var generatedNameSet = {};
- var nodeToGeneratedName = [];
+ var generatedNameSet;
+ var nodeToGeneratedName;
var computedPropertyNamesToGeneratedNames;
var convertedLoopState;
- var extendsEmitted = false;
- var decorateEmitted = false;
- var paramEmitted = false;
- var awaiterEmitted = false;
- var tempFlags = 0;
+ var extendsEmitted;
+ var decorateEmitted;
+ var paramEmitted;
+ var awaiterEmitted;
+ var tempFlags;
var tempVariables;
var tempParameters;
var externalImports;
@@ -25326,6 +25664,7 @@ var ts;
var scopeEmitStart = function (scopeDeclaration, scopeName) { };
var scopeEmitEnd = function () { };
var sourceMapData;
+ var root;
var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker;
var moduleEmitDelegates = (_a = {},
_a[5] = emitES6Module,
@@ -25335,30 +25674,75 @@ var ts;
_a[1] = emitCommonJSModule,
_a
);
- if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
- initializeEmitterWithSourceMaps();
- }
- if (root) {
- emitSourceFile(root);
- }
- else {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!isExternalModuleOrDeclarationFile(sourceFile)) {
- emitSourceFile(sourceFile);
+ var bundleEmitDelegates = (_b = {},
+ _b[5] = function () { },
+ _b[2] = emitAMDModule,
+ _b[4] = emitSystemModule,
+ _b[3] = function () { },
+ _b[1] = function () { },
+ _b
+ );
+ return doEmit;
+ function doEmit(jsFilePath, rootFile) {
+ writer.reset();
+ currentSourceFile = undefined;
+ currentText = undefined;
+ currentLineMap = undefined;
+ exportFunctionForFile = undefined;
+ generatedNameSet = {};
+ nodeToGeneratedName = [];
+ computedPropertyNamesToGeneratedNames = undefined;
+ convertedLoopState = undefined;
+ extendsEmitted = false;
+ decorateEmitted = false;
+ paramEmitted = false;
+ awaiterEmitted = false;
+ tempFlags = 0;
+ tempVariables = undefined;
+ tempParameters = undefined;
+ externalImports = undefined;
+ exportSpecifiers = undefined;
+ exportEquals = undefined;
+ hasExportStars = undefined;
+ detachedCommentsInfo = undefined;
+ sourceMapData = undefined;
+ isEs6Module = false;
+ renamedDependencies = undefined;
+ isCurrentFileExternalModule = false;
+ root = rootFile;
+ if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
+ initializeEmitterWithSourceMaps(jsFilePath, root);
+ }
+ if (root) {
+ emitSourceFile(root);
+ }
+ else {
+ if (modulekind) {
+ ts.forEach(host.getSourceFiles(), emitEmitHelpers);
}
- });
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) {
+ emitSourceFile(sourceFile);
+ }
+ });
+ }
+ writeLine();
+ writeEmittedFiles(writer.getText(), jsFilePath, compilerOptions.emitBOM);
}
- writeLine();
- writeEmittedFiles(writer.getText(), compilerOptions.emitBOM);
- return;
function emitSourceFile(sourceFile) {
currentSourceFile = sourceFile;
+ currentText = sourceFile.text;
+ currentLineMap = ts.getLineStarts(sourceFile);
exportFunctionForFile = undefined;
+ isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"];
+ renamedDependencies = sourceFile.renamedDependencies;
+ currentFileIdentifiers = sourceFile.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(sourceFile);
emit(sourceFile);
}
function isUniqueName(name) {
return !resolver.hasGlobalName(name) &&
- !ts.hasProperty(currentSourceFile.identifiers, name) &&
+ !ts.hasProperty(currentFileIdentifiers, name) &&
!ts.hasProperty(generatedNameSet, name);
}
function makeTempVariableName(flags) {
@@ -25431,7 +25815,7 @@ var ts;
var id = ts.getNodeId(node);
return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node)));
}
- function initializeEmitterWithSourceMaps() {
+ function initializeEmitterWithSourceMaps(jsFilePath, root) {
var sourceMapDir;
var sourceMapSourceIndex = -1;
var sourceMapNameIndexMap = {};
@@ -25500,7 +25884,7 @@ var ts;
}
}
function recordSourceMapSpan(pos) {
- var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos);
+ var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos);
sourceLinePos.line++;
sourceLinePos.character++;
var emittedLine = writer.getLine();
@@ -25528,13 +25912,13 @@ var ts;
}
}
function recordEmitNodeStartSpan(node) {
- recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos));
+ recordSourceMapSpan(ts.skipTrivia(currentText, node.pos));
}
function recordEmitNodeEndSpan(node) {
recordSourceMapSpan(node.end);
}
function writeTextWithSpanRecord(tokenKind, startPos, emitFn) {
- var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);
+ var tokenStartPos = ts.skipTrivia(currentText, startPos);
recordSourceMapSpan(tokenStartPos);
var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);
recordSourceMapSpan(tokenEndPos);
@@ -25604,9 +25988,9 @@ var ts;
sourceMapNameIndices.pop();
}
;
- function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) {
+ function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) {
recordSourceMapSpan(comment.pos);
- ts.writeCommentRange(currentSourceFile, writer, comment, newLine);
+ ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine);
recordSourceMapSpan(comment.end);
}
function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) {
@@ -25636,7 +26020,7 @@ var ts;
return output;
}
}
- function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) {
encodeLastRecordedSourceMapSpan();
var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent);
sourceMapDataList.push(sourceMapData);
@@ -25649,7 +26033,7 @@ var ts;
ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, false);
sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL;
}
- writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);
+ writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark);
}
var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath));
sourceMapData = {
@@ -25712,7 +26096,7 @@ var ts;
scopeEmitEnd = recordScopeNameEnd;
writeComment = writeCommentRangeWithMap;
}
- function writeJavaScriptFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) {
ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
function createTempVariable(flags) {
@@ -25882,7 +26266,7 @@ var ts;
return getQuotedEscapedLiteralText("\"", node.text, "\"");
}
if (node.parent) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ return ts.getTextOfNodeFromSourceText(currentText, node);
}
switch (node.kind) {
case 9:
@@ -25904,7 +26288,7 @@ var ts;
return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote;
}
function emitDownlevelRawTemplateLiteral(node) {
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node);
var isLast = node.kind === 11 || node.kind === 14;
text = text.substring(1, text.length - (isLast ? 1 : 2));
text = text.replace(/\r\n?/g, "\n");
@@ -26234,7 +26618,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
write("\"");
}
@@ -26330,7 +26714,7 @@ var ts;
else if (declaration.kind === 226) {
write(getGeneratedNameForNode(declaration.parent.parent.parent));
var name_24 = declaration.propertyName || declaration.name;
- var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_24);
+ var identifier = ts.getTextOfNodeFromSourceText(currentText, name_24);
if (languageVersion === 0 && identifier === "default") {
write("[\"default\"]");
}
@@ -26354,7 +26738,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function isNameOfNestedRedeclaration(node) {
@@ -26391,7 +26775,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function emitThis(node) {
@@ -26758,8 +27142,8 @@ var ts;
return container && container.kind !== 248;
}
function emitShorthandPropertyAssignment(node) {
- writeTextOfNode(currentSourceFile, node.name);
- if (languageVersion < 2 || isNamespaceExportReference(node.name)) {
+ writeTextOfNode(currentText, node.name);
+ if (modulekind !== 5 || isNamespaceExportReference(node.name)) {
write(": ");
emit(node.name);
}
@@ -26809,10 +27193,10 @@ var ts;
}
emit(node.expression);
var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
- var shouldEmitSpace;
+ var shouldEmitSpace = false;
if (!indentedBeforeDot) {
if (node.expression.kind === 8) {
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node.expression);
shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0;
}
else {
@@ -27818,16 +28202,16 @@ var ts;
emitToken(16, node.clauses.end);
}
function nodeStartPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function nodeEndPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, node2.end);
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end);
}
function nodeEndIsOnSameLineAsNodeStart(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function emitCaseOrDefaultClause(node) {
if (node.kind === 241) {
@@ -27932,7 +28316,7 @@ var ts;
if (node.parent.kind === 248) {
ts.Debug.assert(!!(node.flags & 512) || node.kind === 227);
if (modulekind === 1 || modulekind === 2 || modulekind === 3) {
- if (!currentSourceFile.symbol.exports["___esModule"]) {
+ if (!isEs6Module) {
if (languageVersion === 1) {
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
writeLine();
@@ -28095,12 +28479,18 @@ var ts;
return node;
}
function createPropertyAccessForDestructuringProperty(object, propName) {
- var syntheticName = ts.createSynthesizedNode(propName.kind);
- syntheticName.text = propName.text;
- if (syntheticName.kind !== 69) {
- return createElementAccessExpression(object, syntheticName);
+ var index;
+ var nameIsComputed = propName.kind === 136;
+ if (nameIsComputed) {
+ index = ensureIdentifier(propName.expression, false);
}
- return createPropertyAccessExpression(object, syntheticName);
+ else {
+ index = ts.createSynthesizedNode(propName.kind);
+ index.text = propName.text;
+ }
+ return !nameIsComputed && index.kind === 69
+ ? createPropertyAccessExpression(object, index)
+ : createElementAccessExpression(object, index);
}
function createSliceCall(value, sliceIndex) {
var call = ts.createSynthesizedNode(168);
@@ -28514,7 +28904,6 @@ var ts;
var promiseConstructor = ts.getEntityNameFromTypeNode(node.type);
var isArrowFunction = node.kind === 174;
var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096) !== 0;
- var args;
if (!isArrowFunction) {
write(" {");
increaseIndent();
@@ -29688,8 +30077,8 @@ var ts;
}
}
function tryRenameExternalModule(moduleName) {
- if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
- return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\"";
+ if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) {
+ return "\"" + renamedDependencies[moduleName.text] + "\"";
}
return undefined;
}
@@ -29829,7 +30218,7 @@ var ts;
return;
}
if (resolver.isReferencedAliasDeclaration(node) ||
- (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
+ (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
emitLeadingComments(node);
emitStart(node);
var variableDeclarationIsHoisted = shouldHoistVariable(node, true);
@@ -30041,7 +30430,7 @@ var ts;
function getLocalNameForExternalImport(node) {
var namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);
+ return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name);
}
if (node.kind === 222 && node.importClause) {
return getGeneratedNameForNode(node);
@@ -30314,7 +30703,7 @@ var ts;
ts.getEnclosingBlockScopeContainer(node).kind === 248;
}
function isCurrentFileSystemExternalModule() {
- return modulekind === 4 && ts.isExternalModule(currentSourceFile);
+ return modulekind === 4 && isCurrentFileExternalModule;
}
function emitSystemModuleBody(node, dependencyGroups, startIndex) {
emitVariableDeclarationsForImports();
@@ -30427,15 +30816,19 @@ var ts;
writeLine();
write("}");
}
- function emitSystemModule(node) {
+ function writeModuleName(node, emitRelativePathAsModuleName) {
+ var moduleName = node.moduleName;
+ if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) {
+ write("\"" + moduleName + "\", ");
+ }
+ }
+ function emitSystemModule(node, emitRelativePathAsModuleName) {
collectExternalModuleInfo(node);
ts.Debug.assert(!exportFunctionForFile);
exportFunctionForFile = makeUniqueName("exports");
writeLine();
write("System.register(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
+ writeModuleName(node, emitRelativePathAsModuleName);
write("[");
var groupIndices = {};
var dependencyGroups = [];
@@ -30453,6 +30846,12 @@ var ts;
if (i !== 0) {
write(", ");
}
+ if (emitRelativePathAsModuleName) {
+ var name_30 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
+ if (name_30) {
+ text = "\"" + name_30 + "\"";
+ }
+ }
write(text);
}
write("], function(" + exportFunctionForFile + ") {");
@@ -30466,7 +30865,7 @@ var ts;
writeLine();
write("});");
}
- function getAMDDependencyNames(node, includeNonAmdDependencies) {
+ function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
var aliasedModuleNames = [];
var unaliasedModuleNames = [];
var importAliasNames = [];
@@ -30483,6 +30882,12 @@ var ts;
for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) {
var importNode = externalImports_4[_c];
var externalModuleName = getExternalModuleNameText(importNode);
+ if (emitRelativePathAsModuleName) {
+ var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode);
+ if (name_31) {
+ externalModuleName = "\"" + name_31 + "\"";
+ }
+ }
var importAliasName = getLocalNameForExternalImport(importNode);
if (includeNonAmdDependencies && importAliasName) {
aliasedModuleNames.push(externalModuleName);
@@ -30494,8 +30899,8 @@ var ts;
}
return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
}
- function emitAMDDependencies(node, includeNonAmdDependencies) {
- var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);
+ function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
+ var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName);
emitAMDDependencyList(dependencyNames);
write(", ");
emitAMDFactoryHeader(dependencyNames);
@@ -30522,15 +30927,13 @@ var ts;
}
write(") {");
}
- function emitAMDModule(node) {
+ function emitAMDModule(node, emitRelativePathAsModuleName) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
write("define(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
- emitAMDDependencies(node, true);
+ writeModuleName(node, emitRelativePathAsModuleName);
+ emitAMDDependencies(node, true, emitRelativePathAsModuleName);
increaseIndent();
var startIndex = emitDirectivePrologues(node.statements, true);
emitExportStarHelper();
@@ -30736,8 +31139,13 @@ var ts;
emitShebang();
emitDetachedCommentsAndUpdateCommentsInfo(node);
if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
- var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1];
- emitModule(node);
+ if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) {
+ var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1];
+ emitModule(node);
+ }
+ else {
+ bundleEmitDelegates[modulekind](node, true);
+ }
}
else {
var startIndex = emitDirectivePrologues(node.statements, false);
@@ -30981,7 +31389,7 @@ var ts;
return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos;
}
function getLeadingCommentsWithoutDetachedComments() {
- var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
+ var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@@ -30991,10 +31399,10 @@ var ts;
return leadingComments;
}
function isTripleSlashComment(comment) {
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 &&
+ if (currentText.charCodeAt(comment.pos + 1) === 47 &&
comment.pos + 2 < comment.end &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 47) {
- var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);
+ currentText.charCodeAt(comment.pos + 2) === 47) {
+ var textSubStr = currentText.substring(comment.pos, comment.end);
return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?
true : false;
@@ -31008,7 +31416,7 @@ var ts;
return getLeadingCommentsWithoutDetachedComments();
}
else {
- return ts.getLeadingCommentRangesOfNode(node, currentSourceFile);
+ return ts.getLeadingCommentRangesOfNodeFromText(node, currentText);
}
}
}
@@ -31016,7 +31424,7 @@ var ts;
function getTrailingCommentsToEmit(node) {
if (node.parent) {
if (node.parent.kind === 248 || node.end !== node.parent.end) {
- return ts.getTrailingCommentRanges(currentSourceFile.text, node.end);
+ return ts.getTrailingCommentRanges(currentText, node.end);
}
}
}
@@ -31039,22 +31447,22 @@ var ts;
leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment);
}
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
- ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment);
}
function emitTrailingComments(node) {
if (compilerOptions.removeComments) {
return;
}
var trailingComments = getTrailingCommentsToEmit(node);
- ts.emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment);
}
function emitTrailingCommentsOfPosition(pos) {
if (compilerOptions.removeComments) {
return;
}
- var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos);
- ts.emitComments(currentSourceFile, writer, trailingComments, true, newLine, writeComment);
+ var trailingComments = ts.getTrailingCommentRanges(currentText, pos);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment);
}
function emitLeadingCommentsOfPositionWorker(pos) {
if (compilerOptions.removeComments) {
@@ -31065,13 +31473,13 @@ var ts;
leadingComments = getLeadingCommentsWithoutDetachedComments();
}
else {
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos);
+ leadingComments = ts.getLeadingCommentRanges(currentText, pos);
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);
- ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment);
}
function emitDetachedCommentsAndUpdateCommentsInfo(node) {
- var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments);
+ var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments);
if (currentDetachedCommentInfo) {
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
@@ -31082,12 +31490,12 @@ var ts;
}
}
function emitShebang() {
- var shebang = ts.getShebang(currentSourceFile.text);
+ var shebang = ts.getShebang(currentText);
if (shebang) {
write(shebang);
}
}
- var _a;
+ var _a, _b;
}
function emitFile(jsFilePath, sourceFile) {
emitJavaScript(jsFilePath, sourceFile);
@@ -31143,11 +31551,11 @@ var ts;
if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
var failedLookupLocations = [];
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations };
}
- resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
@@ -31157,8 +31565,8 @@ var ts;
}
}
ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function loadNodeModuleFromFile(candidate, failedLookupLocation, host) {
- return ts.forEach(ts.moduleFileExtensions, tryLoad);
+ function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) {
+ return ts.forEach(extensions, tryLoad);
function tryLoad(ext) {
var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (host.fileExists(fileName)) {
@@ -31170,7 +31578,7 @@ var ts;
}
}
}
- function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) {
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) {
var packageJsonPath = ts.combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
var jsonContent;
@@ -31182,7 +31590,7 @@ var ts;
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
- var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
+ var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
if (result) {
return result;
}
@@ -31191,7 +31599,7 @@ var ts;
else {
failedLookupLocation.push(packageJsonPath);
}
- return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host);
+ return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName, directory, host) {
var failedLookupLocations = [];
@@ -31201,11 +31609,11 @@ var ts;
if (baseName !== "node_modules") {
var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
- result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
@@ -31230,9 +31638,10 @@ var ts;
var searchName;
var failedLookupLocations = [];
var referencedSourceFile;
+ var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions;
while (true) {
searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName));
- referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) {
+ referencedSourceFile = ts.forEach(extensions, function (extension) {
if (extension === ".tsx" && !compilerOptions.jsx) {
return undefined;
}
@@ -31260,10 +31669,8 @@ var ts;
ts.classicNameResolver = classicNameResolver;
ts.defaultInitCompilerOptions = {
module: 1,
- target: 0,
+ target: 1,
noImplicitAny: false,
- outDir: "built",
- rootDir: ".",
sourceMap: false
};
function createCompilerHost(options, setParentNodes) {
@@ -31621,35 +32028,47 @@ var ts;
if (file.imports) {
return;
}
+ var isJavaScriptFile = ts.isSourceFileJavaScript(file);
var imports;
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var node = _a[_i];
- collect(node, true);
+ collect(node, true, false);
}
file.imports = imports || emptyArray;
- function collect(node, allowRelativeModuleNames) {
- switch (node.kind) {
- case 222:
- case 221:
- case 228:
- var moduleNameExpr = ts.getExternalModuleName(node);
- if (!moduleNameExpr || moduleNameExpr.kind !== 9) {
+ return;
+ function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
+ if (!collectOnlyRequireCalls) {
+ switch (node.kind) {
+ case 222:
+ case 221:
+ case 228:
+ var moduleNameExpr = ts.getExternalModuleName(node);
+ if (!moduleNameExpr || moduleNameExpr.kind !== 9) {
+ break;
+ }
+ if (!moduleNameExpr.text) {
+ break;
+ }
+ if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
+ (imports || (imports = [])).push(moduleNameExpr);
+ }
break;
- }
- if (!moduleNameExpr.text) {
+ case 218:
+ if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) {
+ ts.forEachChild(node.body, function (node) {
+ collect(node, false, collectOnlyRequireCalls);
+ });
+ }
break;
- }
- if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
- (imports || (imports = [])).push(moduleNameExpr);
- }
- break;
- case 218:
- if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) {
- ts.forEachChild(node.body, function (node) {
- collect(node, false);
- });
- }
- break;
+ }
+ }
+ if (isJavaScriptFile) {
+ if (ts.isRequireCall(node)) {
+ (imports || (imports = [])).push(node.arguments[0]);
+ }
+ else {
+ ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, true); });
+ }
}
}
}
@@ -31736,7 +32155,6 @@ var ts;
}
processImportedModules(file, basePath);
if (isDefaultLib) {
- file.isDefaultLib = true;
files.unshift(file);
}
else {
@@ -31809,6 +32227,9 @@ var ts;
commonPathComponents.length = sourcePathComponents.length;
}
});
+ if (!commonPathComponents) {
+ return currentDirectory;
+ }
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
@@ -31891,10 +32312,12 @@ var ts;
if (options.module === 5 && languageVersion < 2) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
+ if (outFile && options.module && !(options.module === 2 || options.module === 4)) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
+ }
if (options.outDir ||
options.sourceRoot ||
- (options.mapRoot &&
- (!outFile || firstExternalModuleSourceFile !== undefined))) {
+ options.mapRoot) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
@@ -32448,10 +32871,10 @@ var ts;
ts.forEach(program.getSourceFiles(), function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
var nameToDeclarations = sourceFile.getNamedDeclarations();
- for (var name_30 in nameToDeclarations) {
- var declarations = ts.getProperty(nameToDeclarations, name_30);
+ for (var name_32 in nameToDeclarations) {
+ var declarations = ts.getProperty(nameToDeclarations, name_32);
if (declarations) {
- var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_30);
+ var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_32);
if (!matches) {
continue;
}
@@ -32462,14 +32885,14 @@ var ts;
if (!containers) {
return undefined;
}
- matches = patternMatcher.getMatches(containers, name_30);
+ matches = patternMatcher.getMatches(containers, name_32);
if (!matches) {
continue;
}
}
var fileName = sourceFile.fileName;
var matchKind = bestMatchKind(matches);
- rawItems.push({ name: name_30, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
+ rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
}
}
}
@@ -32797,9 +33220,9 @@ var ts;
case 211:
case 163:
var variableDeclarationNode;
- var name_31;
+ var name_33;
if (node.kind === 163) {
- name_31 = node.name;
+ name_33 = node.name;
variableDeclarationNode = node;
while (variableDeclarationNode && variableDeclarationNode.kind !== 211) {
variableDeclarationNode = variableDeclarationNode.parent;
@@ -32809,16 +33232,16 @@ var ts;
else {
ts.Debug.assert(!ts.isBindingPattern(node.name));
variableDeclarationNode = node;
- name_31 = node.name;
+ name_33 = node.name;
}
if (ts.isConst(variableDeclarationNode)) {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.constElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement);
}
else if (ts.isLet(variableDeclarationNode)) {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.letElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement);
}
else {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.variableElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement);
}
case 144:
return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement);
@@ -33425,7 +33848,7 @@ var ts;
var resolvedSignature = typeChecker.getResolvedSignature(call, candidates);
cancellationToken.throwIfCancellationRequested();
if (!candidates.length) {
- if (ts.isJavaScript(sourceFile.fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
return createJavaScriptSignatureHelpItems(argumentInfo);
}
return undefined;
@@ -34941,9 +35364,9 @@ var ts;
}
Rules.prototype.getRuleName = function (rule) {
var o = this;
- for (var name_32 in o) {
- if (o[name_32] === rule) {
- return name_32;
+ for (var name_34 in o) {
+ if (o[name_34] === rule) {
+ return name_34;
}
}
throw new Error("Unknown rule");
@@ -35318,7 +35741,7 @@ var ts;
function TokenRangeAccess(from, to, except) {
this.tokens = [];
for (var token = from; token <= to; token++) {
- if (except.indexOf(token) < 0) {
+ if (ts.indexOf(except, token) < 0) {
this.tokens.push(token);
}
}
@@ -36706,13 +37129,18 @@ var ts;
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
- var node = new (ts.getNodeConstructor(kind))(pos, end);
+ var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
- function NodeObject() {
+ function NodeObject(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0;
+ this.parent = undefined;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -37151,8 +37579,8 @@ var ts;
})();
var SourceFileObject = (function (_super) {
__extends(SourceFileObject, _super);
- function SourceFileObject() {
- _super.apply(this, arguments);
+ function SourceFileObject(kind, pos, end) {
+ _super.call(this, kind, pos, end);
}
SourceFileObject.prototype.update = function (newText, textChangeRange) {
return ts.updateSourceFile(this, newText, textChangeRange);
@@ -37421,6 +37849,9 @@ var ts;
ClassificationTypeNames.typeAliasName = "type alias name";
ClassificationTypeNames.parameterName = "parameter name";
ClassificationTypeNames.docCommentTagName = "doc comment tag name";
+ ClassificationTypeNames.jsxOpenTagName = "jsx open tag name";
+ ClassificationTypeNames.jsxCloseTagName = "jsx close tag name";
+ ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name";
return ClassificationTypeNames;
})();
ts.ClassificationTypeNames = ClassificationTypeNames;
@@ -37740,8 +38171,9 @@ var ts;
};
}
ts.createDocumentRegistry = createDocumentRegistry;
- function preProcessFile(sourceText, readImportFiles) {
+ function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
+ if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
var referencedFiles = [];
var importedFiles = [];
var ambientExternalModules;
@@ -37775,93 +38207,53 @@ var ts;
end: pos + importPath.length
});
}
- function processImport() {
- scanner.setText(sourceText);
- var token = scanner.scan();
- while (token !== 1) {
- if (token === 122) {
- token = scanner.scan();
- if (token === 125) {
- token = scanner.scan();
- if (token === 9) {
- recordAmbientExternalModule();
- continue;
- }
- }
- }
- else if (token === 89) {
+ function tryConsumeDeclare() {
+ var token = scanner.getToken();
+ if (token === 122) {
+ token = scanner.scan();
+ if (token === 125) {
token = scanner.scan();
if (token === 9) {
- recordModuleName();
- continue;
- }
- else {
- if (token === 69 || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 133) {
- token = scanner.scan();
- if (token === 9) {
- recordModuleName();
- continue;
- }
- }
- else if (token === 56) {
- token = scanner.scan();
- if (token === 127) {
- token = scanner.scan();
- if (token === 17) {
- token = scanner.scan();
- if (token === 9) {
- recordModuleName();
- continue;
- }
- }
- }
- }
- else if (token === 24) {
- token = scanner.scan();
- }
- else {
- continue;
- }
- }
- if (token === 15) {
- token = scanner.scan();
- while (token !== 16) {
- token = scanner.scan();
- }
- if (token === 16) {
- token = scanner.scan();
- if (token === 133) {
- token = scanner.scan();
- if (token === 9) {
- recordModuleName();
- }
- }
- }
- }
- else if (token === 37) {
- token = scanner.scan();
- if (token === 116) {
- token = scanner.scan();
- if (token === 69 || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 133) {
- token = scanner.scan();
- if (token === 9) {
- recordModuleName();
- }
- }
- }
- }
- }
+ recordAmbientExternalModule();
}
}
- else if (token === 82) {
- token = scanner.scan();
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeImport() {
+ var token = scanner.getToken();
+ if (token === 89) {
+ token = scanner.scan();
+ if (token === 9) {
+ recordModuleName();
+ return true;
+ }
+ else {
+ if (token === 69 || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 133) {
+ token = scanner.scan();
+ if (token === 9) {
+ recordModuleName();
+ return true;
+ }
+ }
+ else if (token === 56) {
+ if (tryConsumeRequireCall(true)) {
+ return true;
+ }
+ }
+ else if (token === 24) {
+ token = scanner.scan();
+ }
+ else {
+ return true;
+ }
+ }
if (token === 15) {
token = scanner.scan();
- while (token !== 16) {
+ while (token !== 16 && token !== 1) {
token = scanner.scan();
}
if (token === 16) {
@@ -37875,6 +38267,35 @@ var ts;
}
}
else if (token === 37) {
+ token = scanner.scan();
+ if (token === 116) {
+ token = scanner.scan();
+ if (token === 69 || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 133) {
+ token = scanner.scan();
+ if (token === 9) {
+ recordModuleName();
+ }
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeExport() {
+ var token = scanner.getToken();
+ if (token === 82) {
+ token = scanner.scan();
+ if (token === 15) {
+ token = scanner.scan();
+ while (token !== 16 && token !== 1) {
+ token = scanner.scan();
+ }
+ if (token === 16) {
token = scanner.scan();
if (token === 133) {
token = scanner.scan();
@@ -37883,31 +38304,99 @@ var ts;
}
}
}
- else if (token === 89) {
+ }
+ else if (token === 37) {
+ token = scanner.scan();
+ if (token === 133) {
token = scanner.scan();
- if (token === 69 || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 56) {
- token = scanner.scan();
- if (token === 127) {
- token = scanner.scan();
- if (token === 17) {
- token = scanner.scan();
- if (token === 9) {
- recordModuleName();
- }
- }
- }
+ if (token === 9) {
+ recordModuleName();
+ }
+ }
+ }
+ else if (token === 89) {
+ token = scanner.scan();
+ if (token === 69 || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 56) {
+ if (tryConsumeRequireCall(true)) {
+ return true;
}
}
}
}
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeRequireCall(skipCurrentToken) {
+ var token = skipCurrentToken ? scanner.scan() : scanner.getToken();
+ if (token === 127) {
token = scanner.scan();
+ if (token === 17) {
+ token = scanner.scan();
+ if (token === 9) {
+ recordModuleName();
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeDefine() {
+ var token = scanner.getToken();
+ if (token === 69 && scanner.getTokenValue() === "define") {
+ token = scanner.scan();
+ if (token !== 17) {
+ return true;
+ }
+ token = scanner.scan();
+ if (token === 9) {
+ token = scanner.scan();
+ if (token === 24) {
+ token = scanner.scan();
+ }
+ else {
+ return true;
+ }
+ }
+ if (token !== 19) {
+ return true;
+ }
+ token = scanner.scan();
+ var i = 0;
+ while (token !== 20 && token !== 1) {
+ if (token === 9) {
+ recordModuleName();
+ i++;
+ }
+ token = scanner.scan();
+ }
+ return true;
+ }
+ return false;
+ }
+ function processImports() {
+ scanner.setText(sourceText);
+ scanner.scan();
+ while (true) {
+ if (scanner.getToken() === 1) {
+ break;
+ }
+ if (tryConsumeDeclare() ||
+ tryConsumeImport() ||
+ tryConsumeExport() ||
+ (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) {
+ continue;
+ }
+ else {
+ scanner.scan();
+ }
}
scanner.setText(undefined);
}
if (readImportFiles) {
- processImport();
+ processImports();
}
processTripleSlashDirectives();
return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules };
@@ -38250,7 +38739,7 @@ var ts;
function getSemanticDiagnostics(fileName) {
synchronizeHostData();
var targetSourceFile = getValidSourceFile(fileName);
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(targetSourceFile)) {
return getJavaScriptSemanticDiagnostics(targetSourceFile);
}
var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
@@ -38442,7 +38931,7 @@ var ts;
var typeChecker = program.getTypeChecker();
var syntacticStart = new Date().getTime();
var sourceFile = getValidSourceFile(fileName);
- var isJavaScriptFile = ts.isJavaScript(fileName);
+ var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile);
var isJsDocTagName = false;
var start = new Date().getTime();
var currentToken = ts.getTokenAtPosition(sourceFile, position);
@@ -38953,8 +39442,8 @@ var ts;
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
- var name_33 = element.propertyName || element.name;
- exisingImportsOrExports[name_33.text] = true;
+ var name_35 = element.propertyName || element.name;
+ exisingImportsOrExports[name_35.text] = true;
}
if (ts.isEmpty(exisingImportsOrExports)) {
return exportsOfModule;
@@ -38978,7 +39467,9 @@ var ts;
}
var existingName = void 0;
if (m.kind === 163 && m.propertyName) {
- existingName = m.propertyName.text;
+ if (m.propertyName.kind === 69) {
+ existingName = m.propertyName.text;
+ }
}
else {
existingName = m.name.text;
@@ -39008,44 +39499,41 @@ var ts;
return undefined;
}
var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName;
- var entries;
if (isJsDocTagName) {
return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() };
}
- if (isRightOfDot && ts.isJavaScript(fileName)) {
- entries = getCompletionEntriesFromSymbols(symbols);
- ts.addRange(entries, getJavaScriptCompletionEntries());
+ var sourceFile = getValidSourceFile(fileName);
+ var entries = [];
+ if (isRightOfDot && ts.isSourceFileJavaScript(sourceFile)) {
+ var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries);
+ ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, uniqueNames));
}
else {
if (!symbols || symbols.length === 0) {
return undefined;
}
- entries = getCompletionEntriesFromSymbols(symbols);
+ getCompletionEntriesFromSymbols(symbols, entries);
}
if (!isMemberCompletion && !isJsDocTagName) {
ts.addRange(entries, keywordCompletions);
}
return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
- function getJavaScriptCompletionEntries() {
+ function getJavaScriptCompletionEntries(sourceFile, uniqueNames) {
var entries = [];
- var allNames = {};
var target = program.getCompilerOptions().target;
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile = _a[_i];
- var nameTable = getNameTable(sourceFile);
- for (var name_34 in nameTable) {
- if (!allNames[name_34]) {
- allNames[name_34] = name_34;
- var displayName = getCompletionEntryDisplayName(name_34, target, true);
- if (displayName) {
- var entry = {
- name: displayName,
- kind: ScriptElementKind.warning,
- kindModifiers: "",
- sortText: "1"
- };
- entries.push(entry);
- }
+ var nameTable = getNameTable(sourceFile);
+ for (var name_36 in nameTable) {
+ if (!uniqueNames[name_36]) {
+ uniqueNames[name_36] = name_36;
+ var displayName = getCompletionEntryDisplayName(name_36, target, true);
+ if (displayName) {
+ var entry = {
+ name: displayName,
+ kind: ScriptElementKind.warning,
+ kindModifiers: "",
+ sortText: "1"
+ };
+ entries.push(entry);
}
}
}
@@ -39073,25 +39561,24 @@ var ts;
sortText: "0"
};
}
- function getCompletionEntriesFromSymbols(symbols) {
+ function getCompletionEntriesFromSymbols(symbols, entries) {
var start = new Date().getTime();
- var entries = [];
+ var uniqueNames = {};
if (symbols) {
- var nameToSymbol = {};
for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
var symbol = symbols_3[_i];
var entry = createCompletionEntry(symbol, location);
if (entry) {
var id = ts.escapeIdentifier(entry.name);
- if (!ts.lookUp(nameToSymbol, id)) {
+ if (!ts.lookUp(uniqueNames, id)) {
entries.push(entry);
- nameToSymbol[id] = symbol;
+ uniqueNames[id] = id;
}
}
}
}
log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start));
- return entries;
+ return uniqueNames;
}
}
function getCompletionEntryDetails(fileName, position, entryName) {
@@ -39272,16 +39759,16 @@ var ts;
case ScriptElementKind.letElement:
case ScriptElementKind.parameterElement:
case ScriptElementKind.localVariableElement:
- displayParts.push(ts.punctuationPart(54));
+ displayParts.push(ts.punctuationPart(ts.SyntaxKind.ColonToken));
displayParts.push(ts.spacePart());
if (useConstructSignatures) {
- displayParts.push(ts.keywordPart(92));
+ displayParts.push(ts.keywordPart(ts.SyntaxKind.NewKeyword));
displayParts.push(ts.spacePart());
}
- if (!(type.flags & 65536)) {
- ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1));
+ if (!(type.flags & ts.TypeFlags.Anonymous)) {
+ ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, ts.SymbolFormatFlags.WriteTypeParametersOrArguments));
}
- addSignatureDisplayParts(signature, allSignatures, 8);
+ addSignatureDisplayParts(signature, allSignatures, ts.TypeFormatFlags.WriteArrowStyleSignature);
break;
default:
addSignatureDisplayParts(signature, allSignatures);
@@ -40728,17 +41215,17 @@ var ts;
if (isNameOfPropertyAssignment(node)) {
var objectLiteral = node.parent.parent;
var contextualType = typeChecker.getContextualType(objectLiteral);
- var name_35 = node.text;
+ var name_37 = node.text;
if (contextualType) {
if (contextualType.flags & 16384) {
- var unionProperty = contextualType.getProperty(name_35);
+ var unionProperty = contextualType.getProperty(name_37);
if (unionProperty) {
return [unionProperty];
}
else {
var result_4 = [];
ts.forEach(contextualType.types, function (t) {
- var symbol = t.getProperty(name_35);
+ var symbol = t.getProperty(name_37);
if (symbol) {
result_4.push(symbol);
}
@@ -40747,7 +41234,7 @@ var ts;
}
}
else {
- var symbol_1 = contextualType.getProperty(name_35);
+ var symbol_1 = contextualType.getProperty(name_37);
if (symbol_1) {
return [symbol_1];
}
@@ -41105,6 +41592,9 @@ var ts;
case 16: return ClassificationTypeNames.typeAliasName;
case 17: return ClassificationTypeNames.parameterName;
case 18: return ClassificationTypeNames.docCommentTagName;
+ case 19: return ClassificationTypeNames.jsxOpenTagName;
+ case 20: return ClassificationTypeNames.jsxCloseTagName;
+ case 21: return ClassificationTypeNames.jsxSelfClosingTagName;
}
}
function convertClassifications(classifications) {
@@ -41344,6 +41834,21 @@ var ts;
return 17;
}
return;
+ case 235:
+ if (token.parent.tagName === token) {
+ return 19;
+ }
+ return;
+ case 237:
+ if (token.parent.tagName === token) {
+ return 20;
+ }
+ return;
+ case 234:
+ if (token.parent.tagName === token) {
+ return 21;
+ }
+ return;
}
}
return 2;
@@ -42053,18 +42558,8 @@ var ts;
ts.getDefaultLibFilePath = getDefaultLibFilePath;
function initializeServices() {
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0;
- this.parent = undefined;
- }
- var proto = kind === 248 ? new SourceFileObject() : new NodeObject();
- proto.kind = kind;
- Node.prototype = proto;
- return Node;
- },
+ getNodeConstructor: function () { return NodeObject; },
+ getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
getSignatureConstructor: function () { return SignatureObject; }
@@ -42959,8 +43454,8 @@ var ts;
};
Session.prototype.getDiagnosticsForProject = function (delay, fileName) {
var _this = this;
- var _a = this.getProjectInfo(fileName, true), configFileName = _a.configFileName, fileNamesInProject = _a.fileNames;
- fileNamesInProject = fileNamesInProject.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; });
+ var _a = this.getProjectInfo(fileName, true), configFileName = _a.configFileName, fileNames = _a.fileNames;
+ var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; });
var highPriorityFiles = [];
var mediumPriorityFiles = [];
var lowPriorityFiles = [];
@@ -43329,6 +43824,9 @@ var ts;
this.filenameToSourceFile = {};
this.updateGraphSeq = 0;
this.openRefCount = 0;
+ if (projectOptions && projectOptions.files) {
+ projectOptions.compilerOptions.allowNonTsExtensions = true;
+ }
this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
}
Project.prototype.addOpenRef = function () {
@@ -43399,6 +43897,7 @@ var ts;
Project.prototype.setProjectOptions = function (projectOptions) {
this.projectOptions = projectOptions;
if (projectOptions.compilerOptions) {
+ projectOptions.compilerOptions.allowNonTsExtensions = true;
this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
}
};
@@ -43824,7 +44323,6 @@ var ts;
}
}
if (content !== undefined) {
- var indentSize;
info = new ScriptInfo(this.host, fileName, content, openedByClient);
info.setFormatOptions(this.getFormatCodeOptions());
this.filenameToScriptInfo[fileName] = info;
@@ -44081,7 +44579,9 @@ var ts;
this.setCompilerOptions(opt);
}
else {
- this.setCompilerOptions(ts.getDefaultCompilerOptions());
+ var defaultOpts = ts.getDefaultCompilerOptions();
+ defaultOpts.allowNonTsExtensions = true;
+ this.setCompilerOptions(defaultOpts);
}
this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
this.classifier = ts.createClassifier();
@@ -45635,7 +46135,7 @@ var ts;
};
CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
- var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()));
+ var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), true, true);
var convertResult = {
referencedFiles: [],
importedFiles: [],
@@ -45696,7 +46196,7 @@ var ts;
TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
try {
if (this.documentRegistry === undefined) {
- this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
+ this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
}
var hostAdapter = new LanguageServiceShimHostAdapter(host);
var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry);
@@ -45728,7 +46228,7 @@ var ts;
};
TypeScriptServicesFactory.prototype.close = function () {
this._shims = [];
- this.documentRegistry = ts.createDocumentRegistry();
+ this.documentRegistry = undefined;
};
TypeScriptServicesFactory.prototype.registerShim = function (shim) {
this._shims.push(shim);
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index 972ebfa472d..32a6dee4623 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -387,6 +387,7 @@ declare namespace ts {
right: Identifier;
}
type EntityName = Identifier | QualifiedName;
+ type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
@@ -425,7 +426,7 @@ declare namespace ts {
initializer?: Expression;
}
interface BindingElement extends Declaration {
- propertyName?: Identifier;
+ propertyName?: PropertyName;
dotDotDotToken?: Node;
name: Identifier | BindingPattern;
initializer?: Expression;
@@ -452,7 +453,7 @@ declare namespace ts {
objectAssignmentInitializer?: Expression;
}
interface VariableLikeDeclaration extends Declaration {
- propertyName?: Identifier;
+ propertyName?: PropertyName;
dotDotDotToken?: Node;
name: DeclarationName;
questionToken?: Node;
@@ -581,7 +582,7 @@ declare namespace ts {
asteriskToken?: Node;
expression?: Expression;
}
- interface BinaryExpression extends Expression {
+ interface BinaryExpression extends Expression, Declaration {
left: Expression;
operatorToken: Node;
right: Expression;
@@ -625,7 +626,7 @@ declare namespace ts {
interface ObjectLiteralExpression extends PrimaryExpression, Declaration {
properties: NodeArray;
}
- interface PropertyAccessExpression extends MemberExpression {
+ interface PropertyAccessExpression extends MemberExpression, Declaration {
expression: LeftHandSideExpression;
dotToken: Node;
name: Identifier;
@@ -1220,6 +1221,7 @@ declare namespace ts {
ObjectLiteral = 524288,
ESSymbol = 16777216,
ThisType = 33554432,
+ ObjectLiteralPatternWithComputedProperties = 67108864,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
@@ -1537,7 +1539,6 @@ declare namespace ts {
function getTypeParameterOwner(d: Declaration): Declaration;
}
declare namespace ts {
- function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node;
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
@@ -2126,6 +2127,9 @@ declare namespace ts {
static typeAliasName: string;
static parameterName: string;
static docCommentTagName: string;
+ static jsxOpenTagName: string;
+ static jsxCloseTagName: string;
+ static jsxSelfClosingTagName: string;
}
enum ClassificationType {
comment = 1,
@@ -2146,6 +2150,9 @@ declare namespace ts {
typeAliasName = 16,
parameterName = 17,
docCommentTagName = 18,
+ jsxOpenTagName = 19,
+ jsxCloseTagName = 20,
+ jsxSelfClosingTagName = 21,
}
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
@@ -2171,7 +2178,7 @@ declare namespace ts {
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry;
- function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
+ function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
function createClassifier(): Classifier;
/**
diff --git a/lib/typescript.js b/lib/typescript.js
index 8b0ef04f96e..498ddc37860 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -622,6 +622,7 @@ var ts;
TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType";
TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol";
TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType";
+ TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties";
/* @internal */
TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic";
/* @internal */
@@ -1530,12 +1531,7 @@ var ts;
* List of supported extensions in order of file resolution precedence.
*/
ts.supportedExtensions = [".ts", ".tsx", ".d.ts"];
- /**
- * List of extensions that will be used to look for external modules.
- * This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation,
- * but still would like to load only TypeScript files as modules
- */
- ts.moduleFileExtensions = ts.supportedExtensions;
+ ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx");
function isSupportedSourceFileName(fileName) {
if (!fileName) {
return false;
@@ -1586,17 +1582,16 @@ var ts;
}
function Signature(checker) {
}
+ function Node(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0 /* None */;
+ this.parent = undefined;
+ }
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0 /* None */;
- this.parent = undefined;
- }
- Node.prototype = { kind: kind };
- return Node;
- },
+ getNodeConstructor: function () { return Node; },
+ getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
getSignatureConstructor: function () { return Signature; }
@@ -1913,7 +1908,16 @@ var ts;
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
- _fs.writeFileSync(fileName, data, "utf8");
+ var fd;
+ try {
+ fd = _fs.openSync(fileName, "w");
+ _fs.writeSync(fd, data, undefined, "utf8");
+ }
+ finally {
+ if (fd !== undefined) {
+ _fs.closeSync(fd);
+ }
+ }
}
function getCanonicalPath(path) {
return useCaseSensitiveFileNames ? path.toLowerCase() : path;
@@ -2614,6 +2618,7 @@ var ts;
Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." },
+ Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -3173,7 +3178,7 @@ var ts;
function getCommentRanges(text, pos, trailing) {
var result;
var collecting = trailing || pos === 0;
- while (true) {
+ while (pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
case 13 /* carriageReturn */:
@@ -3242,6 +3247,7 @@ var ts;
}
return result;
}
+ return result;
}
function getLeadingCommentRanges(text, pos) {
return getCommentRanges(text, pos, /*trailing*/ false);
@@ -3343,7 +3349,7 @@ var ts;
error(ts.Diagnostics.Digit_expected);
}
}
- return +(text.substring(start, end));
+ return "" + +(text.substring(start, end));
}
function scanOctalDigits() {
var start = pos;
@@ -3770,7 +3776,7 @@ var ts;
return pos++, token = 36 /* MinusToken */;
case 46 /* dot */:
if (isDigit(text.charCodeAt(pos + 1))) {
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8 /* NumericLiteral */;
}
if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
@@ -3873,7 +3879,7 @@ var ts;
case 55 /* _7 */:
case 56 /* _8 */:
case 57 /* _9 */:
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8 /* NumericLiteral */;
case 58 /* colon */:
return pos++, token = 54 /* ColonToken */;
@@ -4177,1321 +4183,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-///
-/* @internal */
-var ts;
-(function (ts) {
- ts.bindTime = 0;
- (function (ModuleInstanceState) {
- ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
- ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
- ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
- })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
- var ModuleInstanceState = ts.ModuleInstanceState;
- var Reachability;
- (function (Reachability) {
- Reachability[Reachability["Unintialized"] = 1] = "Unintialized";
- Reachability[Reachability["Reachable"] = 2] = "Reachable";
- Reachability[Reachability["Unreachable"] = 4] = "Unreachable";
- Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable";
- })(Reachability || (Reachability = {}));
- function or(state1, state2) {
- return (state1 | state2) & 2 /* Reachable */
- ? 2 /* Reachable */
- : (state1 & state2) & 8 /* ReportedUnreachable */
- ? 8 /* ReportedUnreachable */
- : 4 /* Unreachable */;
- }
- function getModuleInstanceState(node) {
- // A module is uninstantiated if it contains only
- // 1. interface declarations, type alias declarations
- if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) {
- return 0 /* NonInstantiated */;
- }
- else if (ts.isConstEnumDeclaration(node)) {
- return 2 /* ConstEnumOnly */;
- }
- else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) {
- return 0 /* NonInstantiated */;
- }
- else if (node.kind === 219 /* ModuleBlock */) {
- var state = 0 /* NonInstantiated */;
- ts.forEachChild(node, function (n) {
- switch (getModuleInstanceState(n)) {
- case 0 /* NonInstantiated */:
- // child is non-instantiated - continue searching
- return false;
- case 2 /* ConstEnumOnly */:
- // child is const enum only - record state and continue searching
- state = 2 /* ConstEnumOnly */;
- return false;
- case 1 /* Instantiated */:
- // child is instantiated - record state and stop
- state = 1 /* Instantiated */;
- return true;
- }
- });
- return state;
- }
- else if (node.kind === 218 /* ModuleDeclaration */) {
- return getModuleInstanceState(node.body);
- }
- else {
- return 1 /* Instantiated */;
- }
- }
- ts.getModuleInstanceState = getModuleInstanceState;
- var ContainerFlags;
- (function (ContainerFlags) {
- // The current node is not a container, and no container manipulation should happen before
- // recursing into it.
- ContainerFlags[ContainerFlags["None"] = 0] = "None";
- // The current node is a container. It should be set as the current container (and block-
- // container) before recursing into it. The current node does not have locals. Examples:
- //
- // Classes, ObjectLiterals, TypeLiterals, Interfaces...
- ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
- // The current node is a block-scoped-container. It should be set as the current block-
- // container before recursing into it. Examples:
- //
- // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
- ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
- ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals";
- // If the current node is a container that also container that also contains locals. Examples:
- //
- // Functions, Methods, Modules, Source-files.
- ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals";
- })(ContainerFlags || (ContainerFlags = {}));
- var binder = createBinder();
- function bindSourceFile(file, options) {
- var start = new Date().getTime();
- binder(file, options);
- ts.bindTime += new Date().getTime() - start;
- }
- ts.bindSourceFile = bindSourceFile;
- function createBinder() {
- var file;
- var options;
- var parent;
- var container;
- var blockScopeContainer;
- var lastContainer;
- var seenThisKeyword;
- // state used by reachability checks
- var hasExplicitReturn;
- var currentReachabilityState;
- var labelStack;
- var labelIndexMap;
- var implicitLabels;
- // If this file is an external module, then it is automatically in strict-mode according to
- // ES6. If it is not an external module, then we'll determine if it is in strict mode or
- // not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
- var inStrictMode;
- var symbolCount = 0;
- var Symbol;
- var classifiableNames;
- function bindSourceFile(f, opts) {
- file = f;
- options = opts;
- inStrictMode = !!file.externalModuleIndicator;
- classifiableNames = {};
- Symbol = ts.objectAllocator.getSymbolConstructor();
- if (!file.locals) {
- bind(file);
- file.symbolCount = symbolCount;
- file.classifiableNames = classifiableNames;
- }
- parent = undefined;
- container = undefined;
- blockScopeContainer = undefined;
- lastContainer = undefined;
- seenThisKeyword = false;
- hasExplicitReturn = false;
- labelStack = undefined;
- labelIndexMap = undefined;
- implicitLabels = undefined;
- }
- return bindSourceFile;
- function createSymbol(flags, name) {
- symbolCount++;
- return new Symbol(flags, name);
- }
- function addDeclarationToSymbol(symbol, node, symbolFlags) {
- symbol.flags |= symbolFlags;
- node.symbol = symbol;
- if (!symbol.declarations) {
- symbol.declarations = [];
- }
- symbol.declarations.push(node);
- if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) {
- symbol.exports = {};
- }
- if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) {
- symbol.members = {};
- }
- if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) {
- symbol.valueDeclaration = node;
- }
- }
- // Should not be called on a declaration with a computed property name,
- // unless it is a well known Symbol.
- function getDeclarationName(node) {
- if (node.name) {
- if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
- return "\"" + node.name.text + "\"";
- }
- if (node.name.kind === 136 /* ComputedPropertyName */) {
- var nameExpression = node.name.expression;
- ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
- return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
- }
- return node.name.text;
- }
- switch (node.kind) {
- case 144 /* Constructor */:
- return "__constructor";
- case 152 /* FunctionType */:
- case 147 /* CallSignature */:
- return "__call";
- case 153 /* ConstructorType */:
- case 148 /* ConstructSignature */:
- return "__new";
- case 149 /* IndexSignature */:
- return "__index";
- case 228 /* ExportDeclaration */:
- return "__export";
- case 227 /* ExportAssignment */:
- return node.isExportEquals ? "export=" : "default";
- case 213 /* FunctionDeclaration */:
- case 214 /* ClassDeclaration */:
- return node.flags & 512 /* Default */ ? "default" : undefined;
- }
- }
- function getDisplayName(node) {
- return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node);
- }
- /**
- * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
- * @param symbolTable - The symbol table which node will be added to.
- * @param parent - node's parent declaration.
- * @param node - The declaration to be added to the symbol table
- * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
- * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
- */
- function declareSymbol(symbolTable, parent, node, includes, excludes) {
- ts.Debug.assert(!ts.hasDynamicName(node));
- var isDefaultExport = node.flags & 512 /* Default */;
- // The exported symbol for an export default function/class node is always named "default"
- var name = isDefaultExport && parent ? "default" : getDeclarationName(node);
- var symbol;
- if (name !== undefined) {
- // Check and see if the symbol table already has a symbol with this name. If not,
- // create a new symbol with this name and add it to the table. Note that we don't
- // give the new symbol any flags *yet*. This ensures that it will not conflict
- // with the 'excludes' flags we pass in.
- //
- // If we do get an existing symbol, see if it conflicts with the new symbol we're
- // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
- // the same symbol table. If we have a conflict, report the issue on each
- // declaration we have for this symbol, and then create a new symbol for this
- // declaration.
- //
- // If we created a new symbol, either because we didn't have a symbol with this name
- // in the symbol table, or we conflicted with an existing symbol, then just add this
- // node as the sole declaration of the new symbol.
- //
- // Otherwise, we'll be merging into a compatible existing symbol (for example when
- // you have multiple 'vars' with the same name in the same container). In this case
- // just add this node into the declarations list of the symbol.
- symbol = ts.hasProperty(symbolTable, name)
- ? symbolTable[name]
- : (symbolTable[name] = createSymbol(0 /* None */, name));
- if (name && (includes & 788448 /* Classifiable */)) {
- classifiableNames[name] = name;
- }
- if (symbol.flags & excludes) {
- if (node.name) {
- node.name.parent = node;
- }
- // Report errors every position with duplicate declaration
- // Report errors on previous encountered declarations
- var message = symbol.flags & 2 /* BlockScopedVariable */
- ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
- : ts.Diagnostics.Duplicate_identifier_0;
- ts.forEach(symbol.declarations, function (declaration) {
- if (declaration.flags & 512 /* Default */) {
- message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
- }
- });
- ts.forEach(symbol.declarations, function (declaration) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
- });
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
- symbol = createSymbol(0 /* None */, name);
- }
- }
- else {
- symbol = createSymbol(0 /* None */, "__missing");
- }
- addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
- return symbol;
- }
- function declareModuleMember(node, symbolFlags, symbolExcludes) {
- var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */;
- if (symbolFlags & 8388608 /* Alias */) {
- if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) {
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- }
- else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- else {
- // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue,
- // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
- // on it. There are 2 main reasons:
- //
- // 1. We treat locals and exports of the same name as mutually exclusive within a container.
- // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
- // with the same name in the same container.
- // TODO: Make this a more specific error and decouple it from the exclusion logic.
- // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
- // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
- // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
- if (hasExportModifier || container.flags & 131072 /* ExportContext */) {
- var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) |
- (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) |
- (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0);
- var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
- local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- node.localSymbol = local;
- return local;
- }
- else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- }
- // All container nodes are kept on a linked list in declaration order. This list is used by
- // the getLocalNameOfContainer function in the type checker to validate that the local name
- // used for a container is unique.
- function bindChildren(node) {
- // Before we recurse into a node's chilren, we first save the existing parent, container
- // and block-container. Then after we pop out of processing the children, we restore
- // these saved values.
- var saveParent = parent;
- var saveContainer = container;
- var savedBlockScopeContainer = blockScopeContainer;
- // This node will now be set as the parent of all of its children as we recurse into them.
- parent = node;
- // Depending on what kind of node this is, we may have to adjust the current container
- // and block-container. If the current node is a container, then it is automatically
- // considered the current block-container as well. Also, for containers that we know
- // may contain locals, we proactively initialize the .locals field. We do this because
- // it's highly likely that the .locals will be needed to place some child in (for example,
- // a parameter, or variable declaration).
- //
- // However, we do not proactively create the .locals for block-containers because it's
- // totally normal and common for block-containers to never actually have a block-scoped
- // variable in them. We don't want to end up allocating an object for every 'block' we
- // run into when most of them won't be necessary.
- //
- // Finally, if this is a block-container, then we clear out any existing .locals object
- // it may contain within it. This happens in incremental scenarios. Because we can be
- // reusing a node from a previous compilation, that node may have had 'locals' created
- // for it. We must clear this so we don't accidently move any stale data forward from
- // a previous compilation.
- var containerFlags = getContainerFlags(node);
- if (containerFlags & 1 /* IsContainer */) {
- container = blockScopeContainer = node;
- if (containerFlags & 4 /* HasLocals */) {
- container.locals = {};
- }
- addToContainerChain(container);
- }
- else if (containerFlags & 2 /* IsBlockScopedContainer */) {
- blockScopeContainer = node;
- blockScopeContainer.locals = undefined;
- }
- var savedReachabilityState;
- var savedLabelStack;
- var savedLabels;
- var savedImplicitLabels;
- var savedHasExplicitReturn;
- var kind = node.kind;
- var flags = node.flags;
- // reset all reachability check related flags on node (for incremental scenarios)
- flags &= ~1572864 /* ReachabilityCheckFlags */;
- if (kind === 215 /* InterfaceDeclaration */) {
- seenThisKeyword = false;
- }
- var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind);
- if (saveState) {
- savedReachabilityState = currentReachabilityState;
- savedLabelStack = labelStack;
- savedLabels = labelIndexMap;
- savedImplicitLabels = implicitLabels;
- savedHasExplicitReturn = hasExplicitReturn;
- currentReachabilityState = 2 /* Reachable */;
- hasExplicitReturn = false;
- labelStack = labelIndexMap = implicitLabels = undefined;
- }
- bindReachableStatement(node);
- if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) {
- flags |= 524288 /* HasImplicitReturn */;
- if (hasExplicitReturn) {
- flags |= 1048576 /* HasExplicitReturn */;
- }
- }
- if (kind === 215 /* InterfaceDeclaration */) {
- flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */;
- }
- node.flags = flags;
- if (saveState) {
- hasExplicitReturn = savedHasExplicitReturn;
- currentReachabilityState = savedReachabilityState;
- labelStack = savedLabelStack;
- labelIndexMap = savedLabels;
- implicitLabels = savedImplicitLabels;
- }
- container = saveContainer;
- parent = saveParent;
- blockScopeContainer = savedBlockScopeContainer;
- }
- /**
- * Returns true if node and its subnodes were successfully traversed.
- * Returning false means that node was not examined and caller needs to dive into the node himself.
- */
- function bindReachableStatement(node) {
- if (checkUnreachable(node)) {
- ts.forEachChild(node, bind);
- return;
- }
- switch (node.kind) {
- case 198 /* WhileStatement */:
- bindWhileStatement(node);
- break;
- case 197 /* DoStatement */:
- bindDoStatement(node);
- break;
- case 199 /* ForStatement */:
- bindForStatement(node);
- break;
- case 200 /* ForInStatement */:
- case 201 /* ForOfStatement */:
- bindForInOrForOfStatement(node);
- break;
- case 196 /* IfStatement */:
- bindIfStatement(node);
- break;
- case 204 /* ReturnStatement */:
- case 208 /* ThrowStatement */:
- bindReturnOrThrow(node);
- break;
- case 203 /* BreakStatement */:
- case 202 /* ContinueStatement */:
- bindBreakOrContinueStatement(node);
- break;
- case 209 /* TryStatement */:
- bindTryStatement(node);
- break;
- case 206 /* SwitchStatement */:
- bindSwitchStatement(node);
- break;
- case 220 /* CaseBlock */:
- bindCaseBlock(node);
- break;
- case 207 /* LabeledStatement */:
- bindLabeledStatement(node);
- break;
- default:
- ts.forEachChild(node, bind);
- break;
- }
- }
- function bindWhileStatement(n) {
- var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- // bind expressions (don't affect reachability)
- bind(n.expression);
- currentReachabilityState = preWhileState;
- var postWhileLabel = pushImplicitLabel();
- bind(n.statement);
- popImplicitLabel(postWhileLabel, postWhileState);
- }
- function bindDoStatement(n) {
- var preDoState = currentReachabilityState;
- var postDoLabel = pushImplicitLabel();
- bind(n.statement);
- var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState;
- popImplicitLabel(postDoLabel, postDoState);
- // bind expressions (don't affect reachability)
- bind(n.expression);
- }
- function bindForStatement(n) {
- var preForState = currentReachabilityState;
- var postForLabel = pushImplicitLabel();
- // bind expressions (don't affect reachability)
- bind(n.initializer);
- bind(n.condition);
- bind(n.incrementor);
- bind(n.statement);
- // for statement is considered infinite when it condition is either omitted or is true keyword
- // - for(..;;..)
- // - for(..;true;..)
- var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */);
- var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState;
- popImplicitLabel(postForLabel, postForState);
- }
- function bindForInOrForOfStatement(n) {
- var preStatementState = currentReachabilityState;
- var postStatementLabel = pushImplicitLabel();
- // bind expressions (don't affect reachability)
- bind(n.initializer);
- bind(n.expression);
- bind(n.statement);
- popImplicitLabel(postStatementLabel, preStatementState);
- }
- function bindIfStatement(n) {
- // denotes reachability state when entering 'thenStatement' part of the if statement:
- // i.e. if condition is false then thenStatement is unreachable
- var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- // denotes reachability state when entering 'elseStatement':
- // i.e. if condition is true then elseStatement is unreachable
- var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- currentReachabilityState = ifTrueState;
- // bind expression (don't affect reachability)
- bind(n.expression);
- bind(n.thenStatement);
- if (n.elseStatement) {
- var preElseState = currentReachabilityState;
- currentReachabilityState = ifFalseState;
- bind(n.elseStatement);
- currentReachabilityState = or(currentReachabilityState, preElseState);
- }
- else {
- currentReachabilityState = or(currentReachabilityState, ifFalseState);
- }
- }
- function bindReturnOrThrow(n) {
- // bind expression (don't affect reachability)
- bind(n.expression);
- if (n.kind === 204 /* ReturnStatement */) {
- hasExplicitReturn = true;
- }
- currentReachabilityState = 4 /* Unreachable */;
- }
- function bindBreakOrContinueStatement(n) {
- // call bind on label (don't affect reachability)
- bind(n.label);
- // for continue case touch label so it will be marked a used
- var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */);
- if (isValidJump) {
- currentReachabilityState = 4 /* Unreachable */;
- }
- }
- function bindTryStatement(n) {
- // catch\finally blocks has the same reachability as try block
- var preTryState = currentReachabilityState;
- bind(n.tryBlock);
- var postTryState = currentReachabilityState;
- currentReachabilityState = preTryState;
- bind(n.catchClause);
- var postCatchState = currentReachabilityState;
- currentReachabilityState = preTryState;
- bind(n.finallyBlock);
- // post catch/finally state is reachable if
- // - post try state is reachable - control flow can fall out of try block
- // - post catch state is reachable - control flow can fall out of catch block
- currentReachabilityState = or(postTryState, postCatchState);
- }
- function bindSwitchStatement(n) {
- var preSwitchState = currentReachabilityState;
- var postSwitchLabel = pushImplicitLabel();
- // bind expression (don't affect reachability)
- bind(n.expression);
- bind(n.caseBlock);
- var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; });
- // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case
- var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState;
- popImplicitLabel(postSwitchLabel, postSwitchState);
- }
- function bindCaseBlock(n) {
- var startState = currentReachabilityState;
- for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) {
- var clause = _a[_i];
- currentReachabilityState = startState;
- bind(clause);
- if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) {
- errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
- }
- }
- }
- function bindLabeledStatement(n) {
- // call bind on label (don't affect reachability)
- bind(n.label);
- var ok = pushNamedLabel(n.label);
- bind(n.statement);
- if (ok) {
- popNamedLabel(n.label, currentReachabilityState);
- }
- }
- function getContainerFlags(node) {
- switch (node.kind) {
- case 186 /* ClassExpression */:
- case 214 /* ClassDeclaration */:
- case 215 /* InterfaceDeclaration */:
- case 217 /* EnumDeclaration */:
- case 155 /* TypeLiteral */:
- case 165 /* ObjectLiteralExpression */:
- return 1 /* IsContainer */;
- case 147 /* CallSignature */:
- case 148 /* ConstructSignature */:
- case 149 /* IndexSignature */:
- case 143 /* MethodDeclaration */:
- case 142 /* MethodSignature */:
- case 213 /* FunctionDeclaration */:
- case 144 /* Constructor */:
- case 145 /* GetAccessor */:
- case 146 /* SetAccessor */:
- case 152 /* FunctionType */:
- case 153 /* ConstructorType */:
- case 173 /* FunctionExpression */:
- case 174 /* ArrowFunction */:
- case 218 /* ModuleDeclaration */:
- case 248 /* SourceFile */:
- case 216 /* TypeAliasDeclaration */:
- return 5 /* IsContainerWithLocals */;
- case 244 /* CatchClause */:
- case 199 /* ForStatement */:
- case 200 /* ForInStatement */:
- case 201 /* ForOfStatement */:
- case 220 /* CaseBlock */:
- return 2 /* IsBlockScopedContainer */;
- case 192 /* Block */:
- // do not treat blocks directly inside a function as a block-scoped-container.
- // Locals that reside in this block should go to the function locals. Othewise 'x'
- // would not appear to be a redeclaration of a block scoped local in the following
- // example:
- //
- // function foo() {
- // var x;
- // let x;
- // }
- //
- // If we placed 'var x' into the function locals and 'let x' into the locals of
- // the block, then there would be no collision.
- //
- // By not creating a new block-scoped-container here, we ensure that both 'var x'
- // and 'let x' go into the Function-container's locals, and we do get a collision
- // conflict.
- return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
- }
- return 0 /* None */;
- }
- function addToContainerChain(next) {
- if (lastContainer) {
- lastContainer.nextContainer = next;
- }
- lastContainer = next;
- }
- function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
- // Just call this directly so that the return type of this function stays "void".
- declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes);
- }
- function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) {
- switch (container.kind) {
- // Modules, source files, and classes need specialized handling for how their
- // members are declared (for example, a member of a class will go into a specific
- // symbol table depending on if it is static or not). We defer to specialized
- // handlers to take care of declaring these child members.
- case 218 /* ModuleDeclaration */:
- return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 248 /* SourceFile */:
- return declareSourceFileMember(node, symbolFlags, symbolExcludes);
- case 186 /* ClassExpression */:
- case 214 /* ClassDeclaration */:
- return declareClassMember(node, symbolFlags, symbolExcludes);
- case 217 /* EnumDeclaration */:
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- case 155 /* TypeLiteral */:
- case 165 /* ObjectLiteralExpression */:
- case 215 /* InterfaceDeclaration */:
- // Interface/Object-types always have their children added to the 'members' of
- // their container. They are only accessible through an instance of their
- // container, and are never in scope otherwise (even inside the body of the
- // object / type / interface declaring them). An exception is type parameters,
- // which are in scope without qualification (similar to 'locals').
- return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- case 152 /* FunctionType */:
- case 153 /* ConstructorType */:
- case 147 /* CallSignature */:
- case 148 /* ConstructSignature */:
- case 149 /* IndexSignature */:
- case 143 /* MethodDeclaration */:
- case 142 /* MethodSignature */:
- case 144 /* Constructor */:
- case 145 /* GetAccessor */:
- case 146 /* SetAccessor */:
- case 213 /* FunctionDeclaration */:
- case 173 /* FunctionExpression */:
- case 174 /* ArrowFunction */:
- case 216 /* TypeAliasDeclaration */:
- // All the children of these container types are never visible through another
- // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
- // they're only accessed 'lexically' (i.e. from code that exists underneath
- // their container in the tree. To accomplish this, we simply add their declared
- // symbol to the 'locals' of the container. These symbols can then be found as
- // the type checker walks up the containers, checking them for matching names.
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- function declareClassMember(node, symbolFlags, symbolExcludes) {
- return node.flags & 64 /* Static */
- ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
- : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- }
- function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
- return ts.isExternalModule(file)
- ? declareModuleMember(node, symbolFlags, symbolExcludes)
- : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- function hasExportDeclarations(node) {
- var body = node.kind === 248 /* SourceFile */ ? node : node.body;
- if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) {
- for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
- var stat = _a[_i];
- if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) {
- return true;
- }
- }
- }
- return false;
- }
- function setExportContextFlag(node) {
- // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
- // declarations with export modifiers) is an export context in which declarations are implicitly exported.
- if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) {
- node.flags |= 131072 /* ExportContext */;
- }
- else {
- node.flags &= ~131072 /* ExportContext */;
- }
- }
- function bindModuleDeclaration(node) {
- setExportContextFlag(node);
- if (node.name.kind === 9 /* StringLiteral */) {
- declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- }
- else {
- var state = getModuleInstanceState(node);
- if (state === 0 /* NonInstantiated */) {
- declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
- // if module was already merged with some function, class or non-const enum
- // treat is a non-const-enum-only
- node.symbol.constEnumOnlyModule = false;
- }
- else {
- var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */;
- if (node.symbol.constEnumOnlyModule === undefined) {
- // non-merged case - use the current state
- node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
- }
- else {
- // merged case: module is const enum only if all its pieces are non-instantiated or const enum
- node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
- }
- }
- }
- }
- }
- function bindFunctionOrConstructorType(node) {
- // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
- // to the one we would get for: { <...>(...): T }
- //
- // We do that by making an anonymous type literal symbol, and then setting the function
- // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
- // from an actual type literal symbol you would have gotten had you used the long form.
- var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node));
- addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
- var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type");
- addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
- typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a);
- var _a;
- }
- function bindObjectLiteralExpression(node) {
- var ElementKind;
- (function (ElementKind) {
- ElementKind[ElementKind["Property"] = 1] = "Property";
- ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
- })(ElementKind || (ElementKind = {}));
- if (inStrictMode) {
- var seen = {};
- for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
- var prop = _a[_i];
- if (prop.name.kind !== 69 /* Identifier */) {
- continue;
- }
- var identifier = prop.name;
- // ECMA-262 11.1.5 Object Initialiser
- // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
- // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
- // IsDataDescriptor(propId.descriptor) is true.
- // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
- // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
- // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
- // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
- var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */
- ? 1 /* Property */
- : 2 /* Accessor */;
- var existingKind = seen[identifier.text];
- if (!existingKind) {
- seen[identifier.text] = currentKind;
- continue;
- }
- if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
- var span = ts.getErrorSpanForNode(file, identifier);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
- }
- }
- }
- return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object");
- }
- function bindAnonymousDeclaration(node, symbolFlags, name) {
- var symbol = createSymbol(symbolFlags, name);
- addDeclarationToSymbol(symbol, node, symbolFlags);
- }
- function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
- switch (blockScopeContainer.kind) {
- case 218 /* ModuleDeclaration */:
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- case 248 /* SourceFile */:
- if (ts.isExternalModule(container)) {
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- }
- // fall through.
- default:
- if (!blockScopeContainer.locals) {
- blockScopeContainer.locals = {};
- addToContainerChain(blockScopeContainer);
- }
- declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- function bindBlockScopedVariableDeclaration(node) {
- bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */);
- }
- // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
- // check for reserved words used as identifiers in strict mode code.
- function checkStrictModeIdentifier(node) {
- if (inStrictMode &&
- node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ &&
- node.originalKeywordKind <= 114 /* LastFutureReservedWord */ &&
- !ts.isIdentifierName(node)) {
- // Report error only if there are no parse errors in file
- if (!file.parseDiagnostics.length) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
- }
- }
- }
- function getStrictModeIdentifierMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
- }
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
- }
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
- }
- function checkStrictModeBinaryExpression(node) {
- if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
- // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
- // Assignment operator(11.13) or of a PostfixExpression(11.3)
- checkStrictModeEvalOrArguments(node, node.left);
- }
- }
- function checkStrictModeCatchClause(node) {
- // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
- // Catch production is eval or arguments
- if (inStrictMode && node.variableDeclaration) {
- checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
- }
- }
- function checkStrictModeDeleteExpression(node) {
- // Grammar checking
- if (inStrictMode && node.expression.kind === 69 /* Identifier */) {
- // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
- // UnaryExpression is a direct reference to a variable, function argument, or function name
- var span = ts.getErrorSpanForNode(file, node.expression);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
- }
- }
- function isEvalOrArgumentsIdentifier(node) {
- return node.kind === 69 /* Identifier */ &&
- (node.text === "eval" || node.text === "arguments");
- }
- function checkStrictModeEvalOrArguments(contextNode, name) {
- if (name && name.kind === 69 /* Identifier */) {
- var identifier = name;
- if (isEvalOrArgumentsIdentifier(identifier)) {
- // We check first if the name is inside class declaration or class expression; if so give explicit message
- // otherwise report generic error message.
- var span = ts.getErrorSpanForNode(file, name);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));
- }
- }
- }
- function getStrictModeEvalOrArgumentsMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
- }
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
- }
- return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
- }
- function checkStrictModeFunctionName(node) {
- if (inStrictMode) {
- // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
- checkStrictModeEvalOrArguments(node, node.name);
- }
- }
- function checkStrictModeNumericLiteral(node) {
- if (inStrictMode && node.flags & 32768 /* OctalLiteral */) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
- }
- }
- function checkStrictModePostfixUnaryExpression(node) {
- // Grammar checking
- // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
- // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
- // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.operand);
- }
- }
- function checkStrictModePrefixUnaryExpression(node) {
- // Grammar checking
- if (inStrictMode) {
- if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) {
- checkStrictModeEvalOrArguments(node, node.operand);
- }
- }
- }
- function checkStrictModeWithStatement(node) {
- // Grammar checking for withStatement
- if (inStrictMode) {
- errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
- }
- }
- function errorOnFirstToken(node, message, arg0, arg1, arg2) {
- var span = ts.getSpanOfTokenAtPosition(file, node.pos);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
- }
- function getDestructuringParameterName(node) {
- return "__" + ts.indexOf(node.parent.parameters, node);
- }
- function bind(node) {
- if (!node) {
- return;
- }
- node.parent = parent;
- var savedInStrictMode = inStrictMode;
- if (!savedInStrictMode) {
- updateStrictMode(node);
- }
- // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
- // and then potentially add the symbol to an appropriate symbol table. Possible
- // destination symbol tables are:
- //
- // 1) The 'exports' table of the current container's symbol.
- // 2) The 'members' table of the current container's symbol.
- // 3) The 'locals' table of the current container.
- //
- // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
- // (like TypeLiterals for example) will not be put in any table.
- bindWorker(node);
- // Then we recurse into the children of the node to bind them as well. For certain
- // symbols we do specialized work when we recurse. For example, we'll keep track of
- // the current 'container' node when it changes. This helps us know which symbol table
- // a local should go into for example.
- bindChildren(node);
- inStrictMode = savedInStrictMode;
- }
- function updateStrictMode(node) {
- switch (node.kind) {
- case 248 /* SourceFile */:
- case 219 /* ModuleBlock */:
- updateStrictModeStatementList(node.statements);
- return;
- case 192 /* Block */:
- if (ts.isFunctionLike(node.parent)) {
- updateStrictModeStatementList(node.statements);
- }
- return;
- case 214 /* ClassDeclaration */:
- case 186 /* ClassExpression */:
- // All classes are automatically in strict mode in ES6.
- inStrictMode = true;
- return;
- }
- }
- function updateStrictModeStatementList(statements) {
- for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
- var statement = statements_1[_i];
- if (!ts.isPrologueDirective(statement)) {
- return;
- }
- if (isUseStrictPrologueDirective(statement)) {
- inStrictMode = true;
- return;
- }
- }
- }
- /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
- function isUseStrictPrologueDirective(node) {
- var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression);
- // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
- // string to contain unicode escapes (as per ES5).
- return nodeText === "\"use strict\"" || nodeText === "'use strict'";
- }
- function bindWorker(node) {
- switch (node.kind) {
- case 69 /* Identifier */:
- return checkStrictModeIdentifier(node);
- case 181 /* BinaryExpression */:
- return checkStrictModeBinaryExpression(node);
- case 244 /* CatchClause */:
- return checkStrictModeCatchClause(node);
- case 175 /* DeleteExpression */:
- return checkStrictModeDeleteExpression(node);
- case 8 /* NumericLiteral */:
- return checkStrictModeNumericLiteral(node);
- case 180 /* PostfixUnaryExpression */:
- return checkStrictModePostfixUnaryExpression(node);
- case 179 /* PrefixUnaryExpression */:
- return checkStrictModePrefixUnaryExpression(node);
- case 205 /* WithStatement */:
- return checkStrictModeWithStatement(node);
- case 97 /* ThisKeyword */:
- seenThisKeyword = true;
- return;
- case 137 /* TypeParameter */:
- return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */);
- case 138 /* Parameter */:
- return bindParameter(node);
- case 211 /* VariableDeclaration */:
- case 163 /* BindingElement */:
- return bindVariableDeclarationOrBindingElement(node);
- case 141 /* PropertyDeclaration */:
- case 140 /* PropertySignature */:
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */);
- case 245 /* PropertyAssignment */:
- case 246 /* ShorthandPropertyAssignment */:
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */);
- case 247 /* EnumMember */:
- return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */);
- case 147 /* CallSignature */:
- case 148 /* ConstructSignature */:
- case 149 /* IndexSignature */:
- return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
- case 143 /* MethodDeclaration */:
- case 142 /* MethodSignature */:
- // If this is an ObjectLiteralExpression method, then it sits in the same space
- // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
- // so that it will conflict with any other object literal members with the same
- // name.
- return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */);
- case 213 /* FunctionDeclaration */:
- checkStrictModeFunctionName(node);
- return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */);
- case 144 /* Constructor */:
- return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
- case 145 /* GetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */);
- case 146 /* SetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */);
- case 152 /* FunctionType */:
- case 153 /* ConstructorType */:
- return bindFunctionOrConstructorType(node);
- case 155 /* TypeLiteral */:
- return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type");
- case 165 /* ObjectLiteralExpression */:
- return bindObjectLiteralExpression(node);
- case 173 /* FunctionExpression */:
- case 174 /* ArrowFunction */:
- checkStrictModeFunctionName(node);
- var bindingName = node.name ? node.name.text : "__function";
- return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
- case 186 /* ClassExpression */:
- case 214 /* ClassDeclaration */:
- return bindClassLikeDeclaration(node);
- case 215 /* InterfaceDeclaration */:
- return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */);
- case 216 /* TypeAliasDeclaration */:
- return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */);
- case 217 /* EnumDeclaration */:
- return bindEnumDeclaration(node);
- case 218 /* ModuleDeclaration */:
- return bindModuleDeclaration(node);
- case 221 /* ImportEqualsDeclaration */:
- case 224 /* NamespaceImport */:
- case 226 /* ImportSpecifier */:
- case 230 /* ExportSpecifier */:
- return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
- case 223 /* ImportClause */:
- return bindImportClause(node);
- case 228 /* ExportDeclaration */:
- return bindExportDeclaration(node);
- case 227 /* ExportAssignment */:
- return bindExportAssignment(node);
- case 248 /* SourceFile */:
- return bindSourceFileIfExternalModule();
- }
- }
- function bindSourceFileIfExternalModule() {
- setExportContextFlag(file);
- if (ts.isExternalModule(file)) {
- bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
- }
- }
- function bindExportAssignment(node) {
- if (!container.symbol || !container.symbol.exports) {
- // Export assignment in some sort of block construct
- bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node));
- }
- else if (node.expression.kind === 69 /* Identifier */) {
- // An export default clause with an identifier exports all meanings of that identifier
- declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
- }
- else {
- // An export default clause with an expression exports a value
- declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
- }
- }
- function bindExportDeclaration(node) {
- if (!container.symbol || !container.symbol.exports) {
- // Export * in some sort of block construct
- bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node));
- }
- else if (!node.exportClause) {
- // All export * declarations are collected in an __export symbol
- declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */);
- }
- }
- function bindImportClause(node) {
- if (node.name) {
- declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
- }
- }
- function bindClassLikeDeclaration(node) {
- if (node.kind === 214 /* ClassDeclaration */) {
- bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */);
- }
- else {
- var bindingName = node.name ? node.name.text : "__class";
- bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
- // Add name of class expression into the map for semantic classifier
- if (node.name) {
- classifiableNames[node.name.text] = node.name.text;
- }
- }
- var symbol = node.symbol;
- // TypeScript 1.0 spec (April 2014): 8.4
- // Every class automatically contains a static property member named 'prototype', the
- // type of which is an instantiation of the class type with type Any supplied as a type
- // argument for each type parameter. It is an error to explicitly declare a static
- // property member with the name 'prototype'.
- //
- // Note: we check for this here because this class may be merging into a module. The
- // module might have an exported variable called 'prototype'. We can't allow that as
- // that would clash with the built-in 'prototype' for the class.
- var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype");
- if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) {
- if (node.name) {
- node.name.parent = node;
- }
- file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
- }
- symbol.exports[prototypeSymbol.name] = prototypeSymbol;
- prototypeSymbol.parent = symbol;
- }
- function bindEnumDeclaration(node) {
- return ts.isConst(node)
- ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
- : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
- }
- function bindVariableDeclarationOrBindingElement(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.name);
- }
- if (!ts.isBindingPattern(node.name)) {
- if (ts.isBlockOrCatchScoped(node)) {
- bindBlockScopedVariableDeclaration(node);
- }
- else if (ts.isParameterDeclaration(node)) {
- // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration
- // because its parent chain has already been set up, since parents are set before descending into children.
- //
- // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
- // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
- // For example:
- // function foo([a,a]) {} // Duplicate Identifier error
- // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
- // // which correctly set excluded symbols
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */);
- }
- }
- }
- function bindParameter(node) {
- if (inStrictMode) {
- // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
- // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
- checkStrictModeEvalOrArguments(node, node.name);
- }
- if (ts.isBindingPattern(node.name)) {
- bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node));
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
- }
- // If this is a property-parameter, then also declare the property symbol into the
- // containing class.
- if (node.flags & 56 /* AccessibilityModifier */ &&
- node.parent.kind === 144 /* Constructor */ &&
- ts.isClassLike(node.parent.parent)) {
- var classDeclaration = node.parent.parent;
- declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */);
- }
- }
- function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
- return ts.hasDynamicName(node)
- ? bindAnonymousDeclaration(node, symbolFlags, "__computed")
- : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
- }
- // reachability checks
- function pushNamedLabel(name) {
- initializeReachabilityStateIfNecessary();
- if (ts.hasProperty(labelIndexMap, name.text)) {
- return false;
- }
- labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1;
- return true;
- }
- function pushImplicitLabel() {
- initializeReachabilityStateIfNecessary();
- var index = labelStack.push(1 /* Unintialized */) - 1;
- implicitLabels.push(index);
- return index;
- }
- function popNamedLabel(label, outerState) {
- var index = labelIndexMap[label.text];
- ts.Debug.assert(index !== undefined);
- ts.Debug.assert(labelStack.length == index + 1);
- labelIndexMap[label.text] = undefined;
- setCurrentStateAtLabel(labelStack.pop(), outerState, label);
- }
- function popImplicitLabel(implicitLabelIndex, outerState) {
- if (labelStack.length !== implicitLabelIndex + 1) {
- ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex);
- }
- var i = implicitLabels.pop();
- if (implicitLabelIndex !== i) {
- ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex);
- }
- setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined);
- }
- function setCurrentStateAtLabel(innerMergedState, outerState, label) {
- if (innerMergedState === 1 /* Unintialized */) {
- if (label && !options.allowUnusedLabels) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label));
- }
- currentReachabilityState = outerState;
- }
- else {
- currentReachabilityState = or(innerMergedState, outerState);
- }
- }
- function jumpToLabel(label, outerState) {
- initializeReachabilityStateIfNecessary();
- var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels);
- if (index === undefined) {
- // reference to unknown label or
- // break/continue used outside of loops
- return false;
- }
- var stateAtLabel = labelStack[index];
- labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState);
- return true;
- }
- function checkUnreachable(node) {
- switch (currentReachabilityState) {
- case 4 /* Unreachable */:
- var reportError =
- // report error on all statements
- ts.isStatement(node) ||
- // report error on class declarations
- node.kind === 214 /* ClassDeclaration */ ||
- // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
- (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
- // report error on regular enums and const enums if preserveConstEnums is set
- (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
- if (reportError) {
- currentReachabilityState = 8 /* ReportedUnreachable */;
- // unreachable code is reported if
- // - user has explicitly asked about it AND
- // - statement is in not ambient context (statements in ambient context is already an error
- // so we should not report extras) AND
- // - node is not variable statement OR
- // - node is block scoped variable statement OR
- // - node is not block scoped variable statement and at least one variable declaration has initializer
- // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
- // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
- var reportUnreachableCode = !options.allowUnreachableCode &&
- !ts.isInAmbientContext(node) &&
- (node.kind !== 193 /* VariableStatement */ ||
- ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ ||
- ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
- if (reportUnreachableCode) {
- errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected);
- }
- }
- case 8 /* ReportedUnreachable */:
- return true;
- default:
- return false;
- }
- function shouldReportErrorOnModuleDeclaration(node) {
- var instanceState = getModuleInstanceState(node);
- return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums);
- }
- }
- function initializeReachabilityStateIfNecessary() {
- if (labelIndexMap) {
- return;
- }
- currentReachabilityState = 2 /* Reachable */;
- labelIndexMap = {};
- labelStack = [];
- implicitLabels = [];
- }
- }
-})(ts || (ts = {}));
-///
///
/* @internal */
var ts;
@@ -5812,6 +4503,10 @@ var ts;
return file.externalModuleIndicator !== undefined;
}
ts.isExternalModule = isExternalModule;
+ function isExternalOrCommonJsModule(file) {
+ return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
+ }
+ ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
function isDeclarationFile(file) {
return (file.flags & 4096 /* DeclarationFile */) !== 0;
}
@@ -5865,19 +4560,27 @@ var ts;
return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
+ function getLeadingCommentRangesOfNodeFromText(node, text) {
+ return ts.getLeadingCommentRanges(text, node.pos);
+ }
+ ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText;
function getJsDocComments(node, sourceFileOfNode) {
+ return getJsDocCommentsFromText(node, sourceFileOfNode.text);
+ }
+ ts.getJsDocComments = getJsDocComments;
+ function getJsDocCommentsFromText(node, text) {
var commentRanges = (node.kind === 138 /* Parameter */ || node.kind === 137 /* TypeParameter */) ?
- ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
- getLeadingCommentRangesOfNode(node, sourceFileOfNode);
+ ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
+ getLeadingCommentRangesOfNodeFromText(node, text);
return ts.filter(commentRanges, isJsDocComment);
function isJsDocComment(comment) {
// True if the comment starts with '/**' but not if it is '/**/'
- return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
+ return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
}
}
- ts.getJsDocComments = getJsDocComments;
+ ts.getJsDocCommentsFromText = getJsDocCommentsFromText;
ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/;
ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
function isTypeNode(node) {
@@ -6464,6 +5167,57 @@ var ts;
return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */;
}
ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
+ function isSourceFileJavaScript(file) {
+ return isInJavaScriptFile(file);
+ }
+ ts.isSourceFileJavaScript = isSourceFileJavaScript;
+ function isInJavaScriptFile(node) {
+ return node && !!(node.parserContextFlags & 32 /* JavaScriptFile */);
+ }
+ ts.isInJavaScriptFile = isInJavaScriptFile;
+ /**
+ * Returns true if the node is a CallExpression to the identifier 'require' with
+ * exactly one string literal argument.
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isRequireCall(expression) {
+ // of the form 'require("name")'
+ return expression.kind === 168 /* CallExpression */ &&
+ expression.expression.kind === 69 /* Identifier */ &&
+ expression.expression.text === "require" &&
+ expression.arguments.length === 1 &&
+ expression.arguments[0].kind === 9 /* StringLiteral */;
+ }
+ ts.isRequireCall = isRequireCall;
+ /**
+ * Returns true if the node is an assignment to a property on the identifier 'exports'.
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isExportsPropertyAssignment(expression) {
+ // of the form 'exports.name = expr' where 'name' and 'expr' are arbitrary
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181 /* BinaryExpression */) &&
+ (expression.operatorToken.kind === 56 /* EqualsToken */) &&
+ (expression.left.kind === 166 /* PropertyAccessExpression */) &&
+ (expression.left.expression.kind === 69 /* Identifier */) &&
+ ((expression.left.expression).text === "exports");
+ }
+ ts.isExportsPropertyAssignment = isExportsPropertyAssignment;
+ /**
+ * Returns true if the node is an assignment to the property access expression 'module.exports'.
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isModuleExportsAssignment(expression) {
+ // of the form 'module.exports = expr' where 'expr' is arbitrary
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181 /* BinaryExpression */) &&
+ (expression.operatorToken.kind === 56 /* EqualsToken */) &&
+ (expression.left.kind === 166 /* PropertyAccessExpression */) &&
+ (expression.left.expression.kind === 69 /* Identifier */) &&
+ ((expression.left.expression).text === "module") &&
+ (expression.left.name.text === "exports");
+ }
+ ts.isModuleExportsAssignment = isModuleExportsAssignment;
function getExternalModuleName(node) {
if (node.kind === 222 /* ImportDeclaration */) {
return node.moduleSpecifier;
@@ -6791,8 +5545,8 @@ var ts;
function getFileReferenceFromReferencePath(comment, commentRange) {
var simpleReferenceRegEx = /^\/\/\/\s*/gim;
- if (simpleReferenceRegEx.exec(comment)) {
- if (isNoDefaultLibRegEx.exec(comment)) {
+ if (simpleReferenceRegEx.test(comment)) {
+ if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
@@ -6834,6 +5588,10 @@ var ts;
return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node);
}
ts.isAsyncFunctionLike = isAsyncFunctionLike;
+ function isStringOrNumericLiteral(kind) {
+ return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */;
+ }
+ ts.isStringOrNumericLiteral = isStringOrNumericLiteral;
/**
* A declaration has a dynamic name if both of the following are true:
* 1. The declaration has a computed property name
@@ -6842,11 +5600,15 @@ var ts;
* Symbol.
*/
function hasDynamicName(declaration) {
- return declaration.name &&
- declaration.name.kind === 136 /* ComputedPropertyName */ &&
- !isWellKnownSymbolSyntactically(declaration.name.expression);
+ return declaration.name && isDynamicName(declaration.name);
}
ts.hasDynamicName = hasDynamicName;
+ function isDynamicName(name) {
+ return name.kind === 136 /* ComputedPropertyName */ &&
+ !isStringOrNumericLiteral(name.expression.kind) &&
+ !isWellKnownSymbolSyntactically(name.expression);
+ }
+ ts.isDynamicName = isDynamicName;
/**
* Checks if the expression is of the form:
* Symbol.name
@@ -7087,11 +5849,11 @@ var ts;
}
ts.getIndentSize = getIndentSize;
function createTextWriter(newLine) {
- var output = "";
- var indent = 0;
- var lineStart = true;
- var lineCount = 0;
- var linePos = 0;
+ var output;
+ var indent;
+ var lineStart;
+ var lineCount;
+ var linePos;
function write(s) {
if (s && s.length) {
if (lineStart) {
@@ -7101,6 +5863,13 @@ var ts;
output += s;
}
}
+ function reset() {
+ output = "";
+ indent = 0;
+ lineStart = true;
+ lineCount = 0;
+ linePos = 0;
+ }
function rawWrite(s) {
if (s !== undefined) {
if (lineStart) {
@@ -7127,9 +5896,10 @@ var ts;
lineStart = true;
}
}
- function writeTextOfNode(sourceFile, node) {
- write(getSourceTextOfNodeFromSourceFile(sourceFile, node));
+ function writeTextOfNode(text, node) {
+ write(getTextOfNodeFromSourceText(text, node));
}
+ reset();
return {
write: write,
rawWrite: rawWrite,
@@ -7142,10 +5912,20 @@ var ts;
getTextPos: function () { return output.length; },
getLine: function () { return lineCount + 1; },
getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; },
- getText: function () { return output; }
+ getText: function () { return output; },
+ reset: reset
};
}
ts.createTextWriter = createTextWriter;
+ /**
+ * Resolves a local path to a path which is absolute to the base of the emit
+ */
+ function getExternalModuleNameFromPath(host, fileName) {
+ var dir = host.getCurrentDirectory();
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, /*isAbsolutePathAnUrl*/ false);
+ return ts.removeFileExtension(relativePath);
+ }
+ ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
var compilerOptions = host.getCompilerOptions();
var emitOutputFilePathWithoutExtension;
@@ -7174,6 +5954,10 @@ var ts;
return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
ts.getLineOfLocalPosition = getLineOfLocalPosition;
+ function getLineOfLocalPositionFromLineMap(lineMap, pos) {
+ return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
+ }
+ ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
function getFirstConstructorWithBody(node) {
return ts.forEach(node.members, function (member) {
if (member.kind === 144 /* Constructor */ && nodeIsPresent(member.body)) {
@@ -7246,22 +6030,22 @@ var ts;
};
}
ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
- function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) {
+ function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
// If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
- getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) {
+ getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
}
}
ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
- function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) {
+ function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) {
var emitLeadingSpace = !trailingSeparator;
ts.forEach(comments, function (comment) {
if (emitLeadingSpace) {
writer.write(" ");
emitLeadingSpace = false;
}
- writeComment(currentSourceFile, writer, comment, newLine);
+ writeComment(text, lineMap, writer, comment, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
@@ -7279,7 +6063,7 @@ var ts;
* Detached comment is a comment at the top of file or function body that is separated from
* the next statement by space.
*/
- function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) {
+ function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
var leadingComments;
var currentDetachedCommentInfo;
if (removeComments) {
@@ -7289,12 +6073,12 @@ var ts;
//
// var x = 10;
if (node.pos === 0) {
- leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment);
+ leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment);
}
}
else {
// removeComments is false, just get detached as normal and bypass the process to filter comment
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ leadingComments = ts.getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
var detachedComments = [];
@@ -7302,8 +6086,8 @@ var ts;
for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
var comment = leadingComments_1[_i];
if (lastComment) {
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end);
- var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos);
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
+ var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
if (commentLine >= lastCommentLine + 2) {
// There was a blank line between the last comment and this comment. This
// comment is not part of the copyright comments. Return what we have so
@@ -7318,36 +6102,36 @@ var ts;
// All comments look like they could have been part of the copyright header. Make
// sure there is at least one blank line between it and the node. If not, it's not
// a copyright header.
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end);
- var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end);
+ var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
// Valid detachedComments
- emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
- emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
+ emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
+ emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end };
}
}
}
return currentDetachedCommentInfo;
function isPinnedComment(comment) {
- return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;
+ return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;
}
}
ts.emitDetachedComments = emitDetachedComments;
- function writeCommentRange(currentSourceFile, writer, comment, newLine) {
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) {
- var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
- var lineCount = ts.getLineStarts(currentSourceFile).length;
+ function writeCommentRange(text, lineMap, writer, comment, newLine) {
+ if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) {
+ var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos);
+ var lineCount = lineMap.length;
var firstCommentLineIndent;
for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
var nextLineStart = (currentLine + 1) === lineCount
- ? currentSourceFile.text.length + 1
- : getStartPositionOfLine(currentLine + 1, currentSourceFile);
+ ? text.length + 1
+ : lineMap[currentLine + 1];
if (pos !== comment.pos) {
// If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
- firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
+ firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos);
}
// These are number of spaces writer is going to write at current indent
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
@@ -7365,7 +6149,7 @@ var ts;
// More right indented comment */ --4 = 8 - 4 + 11
// class c { }
// }
- var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
+ var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
@@ -7383,45 +6167,45 @@ var ts;
}
}
// Write the comment line text
- writeTrimmedCurrentLine(pos, nextLineStart);
+ writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
// Single line comment of style //....
- writer.write(currentSourceFile.text.substring(comment.pos, comment.end));
- }
- function writeTrimmedCurrentLine(pos, nextLineStart) {
- var end = Math.min(comment.end, nextLineStart - 1);
- var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
- if (currentLineText) {
- // trimmed forward and ending spaces text
- writer.write(currentLineText);
- if (end !== comment.end) {
- writer.writeLine();
- }
- }
- else {
- // Empty string - make sure we write empty line
- writer.writeLiteral(newLine);
- }
- }
- function calculateIndent(pos, end) {
- var currentLineIndent = 0;
- for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
- if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) {
- // Tabs = TabSize = indent size and go to next tabStop
- currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
- }
- else {
- // Single space
- currentLineIndent++;
- }
- }
- return currentLineIndent;
+ writer.write(text.substring(comment.pos, comment.end));
}
}
ts.writeCommentRange = writeCommentRange;
+ function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) {
+ var end = Math.min(comment.end, nextLineStart - 1);
+ var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
+ if (currentLineText) {
+ // trimmed forward and ending spaces text
+ writer.write(currentLineText);
+ if (end !== comment.end) {
+ writer.writeLine();
+ }
+ }
+ else {
+ // Empty string - make sure we write empty line
+ writer.writeLiteral(newLine);
+ }
+ }
+ function calculateIndent(text, pos, end) {
+ var currentLineIndent = 0;
+ for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) {
+ if (text.charCodeAt(pos) === 9 /* tab */) {
+ // Tabs = TabSize = indent size and go to next tabStop
+ currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
+ }
+ else {
+ // Single space
+ currentLineIndent++;
+ }
+ }
+ return currentLineIndent;
+ }
function modifierToFlag(token) {
switch (token) {
case 113 /* StaticKeyword */: return 64 /* Static */;
@@ -7517,14 +6301,14 @@ var ts;
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
- function isJavaScript(fileName) {
- return ts.fileExtensionIs(fileName, ".js");
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isJavaScript = isJavaScript;
- function isTsx(fileName) {
- return ts.fileExtensionIs(fileName, ".tsx");
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function allowsJsxExpressions(fileName) {
+ return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isTsx = isTsx;
+ ts.allowsJsxExpressions = allowsJsxExpressions;
/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* representing the UTF-8 encoding of the character, and return the expanded char code list.
@@ -7835,18 +6619,20 @@ var ts;
}
ts.getTypeParameterOwner = getTypeParameterOwner;
})(ts || (ts = {}));
-///
///
+///
var ts;
(function (ts) {
- var nodeConstructors = new Array(272 /* Count */);
/* @internal */ ts.parseTime = 0;
- function getNodeConstructor(kind) {
- return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind));
- }
- ts.getNodeConstructor = getNodeConstructor;
+ var NodeConstructor;
+ var SourceFileConstructor;
function createNode(kind, pos, end) {
- return new (getNodeConstructor(kind))(pos, end);
+ if (kind === 248 /* SourceFile */) {
+ return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
+ }
+ else {
+ return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
+ }
}
ts.createNode = createNode;
function visitNode(cbNode, node) {
@@ -8269,6 +7055,9 @@ var ts;
// up by avoiding the cost of creating/compiling scanners over and over again.
var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 1 /* DisallowIn */ | 4 /* Decorator */;
+ // capture constructors in 'initializeState' to avoid null checks
+ var NodeConstructor;
+ var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
var syntaxCursor;
@@ -8354,13 +7143,16 @@ var ts;
// attached to the EOF token.
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) {
- initializeState(fileName, _sourceText, languageVersion, _syntaxCursor);
+ var isJavaScriptFile = ts.hasJavaScriptFileExtension(fileName) || _sourceText.lastIndexOf("// @language=javascript", 0) === 0;
+ initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes);
clearState();
return result;
}
Parser.parseSourceFile = parseSourceFile;
- function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) {
+ function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) {
+ NodeConstructor = ts.objectAllocator.getNodeConstructor();
+ SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
parseDiagnostics = [];
@@ -8368,13 +7160,13 @@ var ts;
identifiers = {};
identifierCount = 0;
nodeCount = 0;
- contextFlags = ts.isJavaScript(fileName) ? 32 /* JavaScriptFile */ : 0 /* None */;
+ contextFlags = isJavaScriptFile ? 32 /* JavaScriptFile */ : 0 /* None */;
parseErrorBeforeNextFinishedNode = false;
// Initialize and prime the scanner before parsing the source elements.
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
- scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 /* JSX */ : 0 /* Standard */);
+ scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 /* JSX */ : 0 /* Standard */);
}
function clearState() {
// Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
@@ -8389,6 +7181,9 @@ var ts;
}
function parseSourceFileWorker(fileName, languageVersion, setParentNodes) {
sourceFile = createSourceFile(fileName, languageVersion);
+ if (contextFlags & 32 /* JavaScriptFile */) {
+ sourceFile.parserContextFlags = 32 /* JavaScriptFile */;
+ }
// Prime the scanner.
token = nextToken();
processReferenceComments(sourceFile);
@@ -8406,7 +7201,7 @@ var ts;
// If this is a javascript file, proactively see if we can get JSDoc comments for
// relevant nodes in the file. We'll use these to provide typing informaion if they're
// available.
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
addJSDocComments();
}
return sourceFile;
@@ -8461,15 +7256,16 @@ var ts;
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion) {
- var sourceFile = createNode(248 /* SourceFile */, /*pos*/ 0);
- sourceFile.pos = 0;
- sourceFile.end = sourceText.length;
+ // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
+ // this is quite rare comparing to other nodes and createNode should be as fast as possible
+ var sourceFile = new SourceFileConstructor(248 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = ts.normalizePath(fileName);
sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0;
- sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */;
+ sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */;
return sourceFile;
}
function setContextFlag(val, flag) {
@@ -8734,12 +7530,13 @@ var ts;
return parseExpected(23 /* SemicolonToken */);
}
}
+ // note: this function creates only node
function createNode(kind, pos) {
nodeCount++;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
- return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos);
+ return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -8904,7 +7701,7 @@ var ts;
case 12 /* ObjectLiteralMembers */:
return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName();
case 9 /* ObjectBindingElements */:
- return isLiteralPropertyName();
+ return token === 19 /* OpenBracketToken */ || isLiteralPropertyName();
case 7 /* HeritageClauseElement */:
// If we see { } then only consume it as an expression if it is followed by , or {
// That way we won't consume the body of a class in its heritage clause.
@@ -9584,9 +8381,7 @@ var ts;
}
function parseParameterType() {
if (parseOptional(54 /* ColonToken */)) {
- return token === 9 /* StringLiteral */
- ? parseLiteralNode(/*internName*/ true)
- : parseType();
+ return parseType();
}
return undefined;
}
@@ -9917,6 +8712,8 @@ var ts;
// If these are followed by a dot, then parse these out as a dotted type reference instead.
var node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
+ case 9 /* StringLiteral */:
+ return parseLiteralNode(/*internName*/ true);
case 103 /* VoidKeyword */:
case 97 /* ThisKeyword */:
return parseTokenNode();
@@ -9946,6 +8743,7 @@ var ts;
case 19 /* OpenBracketToken */:
case 25 /* LessThanToken */:
case 92 /* NewKeyword */:
+ case 9 /* StringLiteral */:
return true;
case 17 /* OpenParenToken */:
// Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
@@ -10362,7 +9160,7 @@ var ts;
return 1 /* True */;
}
// This *could* be a parenthesized arrow function.
- // Return Unknown to let the caller know.
+ // Return Unknown to const the caller know.
return 2 /* Unknown */;
}
else {
@@ -10448,7 +9246,7 @@ var ts;
// user meant to supply a block. For example, if the user wrote:
//
// a =>
- // let v = 0;
+ // const v = 0;
// }
//
// they may be missing an open brace. Check to see if that's the case so we can
@@ -10664,7 +9462,6 @@ var ts;
var unaryOperator = token;
var simpleUnaryExpression = parseSimpleUnaryExpression();
if (token === 38 /* AsteriskAsteriskToken */) {
- var diagnostic;
var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) {
parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
@@ -11868,7 +10665,6 @@ var ts;
}
function parseObjectBindingElement() {
var node = createNode(163 /* BindingElement */);
- // TODO(andersh): Handle computed properties
var tokenIsIdentifier = isIdentifier();
var propertyName = parsePropertyName();
if (tokenIsIdentifier && token !== 54 /* ColonToken */) {
@@ -12691,7 +11487,7 @@ var ts;
}
JSDocParser.isJSDocType = isJSDocType;
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined);
+ initializeState("file.js", content, 2 /* Latest */, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined);
var jsDocTypeExpression = parseJSDocTypeExpression(start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -12786,6 +11582,7 @@ var ts;
case 103 /* VoidKeyword */:
return parseTokenNode();
}
+ // TODO (drosen): Parse string literal types in JSDoc as well.
return parseJSDocTypeReference();
}
function parseJSDocThisType() {
@@ -12957,7 +11754,7 @@ var ts;
}
}
function parseIsolatedJSDocComment(content, start, length) {
- initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined);
+ initializeState("file.js", content, 2 /* Latest */, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined);
var jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -13682,6 +12479,1372 @@ var ts;
})(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
})(ts || (ts = {}));
+///
+///
+/* @internal */
+var ts;
+(function (ts) {
+ ts.bindTime = 0;
+ (function (ModuleInstanceState) {
+ ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
+ ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
+ ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
+ })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
+ var ModuleInstanceState = ts.ModuleInstanceState;
+ var Reachability;
+ (function (Reachability) {
+ Reachability[Reachability["Unintialized"] = 1] = "Unintialized";
+ Reachability[Reachability["Reachable"] = 2] = "Reachable";
+ Reachability[Reachability["Unreachable"] = 4] = "Unreachable";
+ Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable";
+ })(Reachability || (Reachability = {}));
+ function or(state1, state2) {
+ return (state1 | state2) & 2 /* Reachable */
+ ? 2 /* Reachable */
+ : (state1 & state2) & 8 /* ReportedUnreachable */
+ ? 8 /* ReportedUnreachable */
+ : 4 /* Unreachable */;
+ }
+ function getModuleInstanceState(node) {
+ // A module is uninstantiated if it contains only
+ // 1. interface declarations, type alias declarations
+ if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) {
+ return 0 /* NonInstantiated */;
+ }
+ else if (ts.isConstEnumDeclaration(node)) {
+ return 2 /* ConstEnumOnly */;
+ }
+ else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) {
+ return 0 /* NonInstantiated */;
+ }
+ else if (node.kind === 219 /* ModuleBlock */) {
+ var state = 0 /* NonInstantiated */;
+ ts.forEachChild(node, function (n) {
+ switch (getModuleInstanceState(n)) {
+ case 0 /* NonInstantiated */:
+ // child is non-instantiated - continue searching
+ return false;
+ case 2 /* ConstEnumOnly */:
+ // child is const enum only - record state and continue searching
+ state = 2 /* ConstEnumOnly */;
+ return false;
+ case 1 /* Instantiated */:
+ // child is instantiated - record state and stop
+ state = 1 /* Instantiated */;
+ return true;
+ }
+ });
+ return state;
+ }
+ else if (node.kind === 218 /* ModuleDeclaration */) {
+ return getModuleInstanceState(node.body);
+ }
+ else {
+ return 1 /* Instantiated */;
+ }
+ }
+ ts.getModuleInstanceState = getModuleInstanceState;
+ var ContainerFlags;
+ (function (ContainerFlags) {
+ // The current node is not a container, and no container manipulation should happen before
+ // recursing into it.
+ ContainerFlags[ContainerFlags["None"] = 0] = "None";
+ // The current node is a container. It should be set as the current container (and block-
+ // container) before recursing into it. The current node does not have locals. Examples:
+ //
+ // Classes, ObjectLiterals, TypeLiterals, Interfaces...
+ ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
+ // The current node is a block-scoped-container. It should be set as the current block-
+ // container before recursing into it. Examples:
+ //
+ // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
+ ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
+ ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals";
+ // If the current node is a container that also container that also contains locals. Examples:
+ //
+ // Functions, Methods, Modules, Source-files.
+ ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals";
+ })(ContainerFlags || (ContainerFlags = {}));
+ var binder = createBinder();
+ function bindSourceFile(file, options) {
+ var start = new Date().getTime();
+ binder(file, options);
+ ts.bindTime += new Date().getTime() - start;
+ }
+ ts.bindSourceFile = bindSourceFile;
+ function createBinder() {
+ var file;
+ var options;
+ var parent;
+ var container;
+ var blockScopeContainer;
+ var lastContainer;
+ var seenThisKeyword;
+ // state used by reachability checks
+ var hasExplicitReturn;
+ var currentReachabilityState;
+ var labelStack;
+ var labelIndexMap;
+ var implicitLabels;
+ // If this file is an external module, then it is automatically in strict-mode according to
+ // ES6. If it is not an external module, then we'll determine if it is in strict mode or
+ // not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
+ var inStrictMode;
+ var symbolCount = 0;
+ var Symbol;
+ var classifiableNames;
+ function bindSourceFile(f, opts) {
+ file = f;
+ options = opts;
+ inStrictMode = !!file.externalModuleIndicator;
+ classifiableNames = {};
+ Symbol = ts.objectAllocator.getSymbolConstructor();
+ if (!file.locals) {
+ bind(file);
+ file.symbolCount = symbolCount;
+ file.classifiableNames = classifiableNames;
+ }
+ parent = undefined;
+ container = undefined;
+ blockScopeContainer = undefined;
+ lastContainer = undefined;
+ seenThisKeyword = false;
+ hasExplicitReturn = false;
+ labelStack = undefined;
+ labelIndexMap = undefined;
+ implicitLabels = undefined;
+ }
+ return bindSourceFile;
+ function createSymbol(flags, name) {
+ symbolCount++;
+ return new Symbol(flags, name);
+ }
+ function addDeclarationToSymbol(symbol, node, symbolFlags) {
+ symbol.flags |= symbolFlags;
+ node.symbol = symbol;
+ if (!symbol.declarations) {
+ symbol.declarations = [];
+ }
+ symbol.declarations.push(node);
+ if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) {
+ symbol.exports = {};
+ }
+ if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) {
+ symbol.members = {};
+ }
+ if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) {
+ symbol.valueDeclaration = node;
+ }
+ }
+ // Should not be called on a declaration with a computed property name,
+ // unless it is a well known Symbol.
+ function getDeclarationName(node) {
+ if (node.name) {
+ if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
+ return "\"" + node.name.text + "\"";
+ }
+ if (node.name.kind === 136 /* ComputedPropertyName */) {
+ var nameExpression = node.name.expression;
+ // treat computed property names where expression is string/numeric literal as just string/numeric literal
+ if (ts.isStringOrNumericLiteral(nameExpression.kind)) {
+ return nameExpression.text;
+ }
+ ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
+ return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
+ }
+ return node.name.text;
+ }
+ switch (node.kind) {
+ case 144 /* Constructor */:
+ return "__constructor";
+ case 152 /* FunctionType */:
+ case 147 /* CallSignature */:
+ return "__call";
+ case 153 /* ConstructorType */:
+ case 148 /* ConstructSignature */:
+ return "__new";
+ case 149 /* IndexSignature */:
+ return "__index";
+ case 228 /* ExportDeclaration */:
+ return "__export";
+ case 227 /* ExportAssignment */:
+ return node.isExportEquals ? "export=" : "default";
+ case 181 /* BinaryExpression */:
+ // Binary expression case is for JS module 'module.exports = expr'
+ return "export=";
+ case 213 /* FunctionDeclaration */:
+ case 214 /* ClassDeclaration */:
+ return node.flags & 512 /* Default */ ? "default" : undefined;
+ }
+ }
+ function getDisplayName(node) {
+ return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node);
+ }
+ /**
+ * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
+ * @param symbolTable - The symbol table which node will be added to.
+ * @param parent - node's parent declaration.
+ * @param node - The declaration to be added to the symbol table
+ * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
+ * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
+ */
+ function declareSymbol(symbolTable, parent, node, includes, excludes) {
+ ts.Debug.assert(!ts.hasDynamicName(node));
+ var isDefaultExport = node.flags & 512 /* Default */;
+ // The exported symbol for an export default function/class node is always named "default"
+ var name = isDefaultExport && parent ? "default" : getDeclarationName(node);
+ var symbol;
+ if (name !== undefined) {
+ // Check and see if the symbol table already has a symbol with this name. If not,
+ // create a new symbol with this name and add it to the table. Note that we don't
+ // give the new symbol any flags *yet*. This ensures that it will not conflict
+ // with the 'excludes' flags we pass in.
+ //
+ // If we do get an existing symbol, see if it conflicts with the new symbol we're
+ // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
+ // the same symbol table. If we have a conflict, report the issue on each
+ // declaration we have for this symbol, and then create a new symbol for this
+ // declaration.
+ //
+ // If we created a new symbol, either because we didn't have a symbol with this name
+ // in the symbol table, or we conflicted with an existing symbol, then just add this
+ // node as the sole declaration of the new symbol.
+ //
+ // Otherwise, we'll be merging into a compatible existing symbol (for example when
+ // you have multiple 'vars' with the same name in the same container). In this case
+ // just add this node into the declarations list of the symbol.
+ symbol = ts.hasProperty(symbolTable, name)
+ ? symbolTable[name]
+ : (symbolTable[name] = createSymbol(0 /* None */, name));
+ if (name && (includes & 788448 /* Classifiable */)) {
+ classifiableNames[name] = name;
+ }
+ if (symbol.flags & excludes) {
+ if (node.name) {
+ node.name.parent = node;
+ }
+ // Report errors every position with duplicate declaration
+ // Report errors on previous encountered declarations
+ var message = symbol.flags & 2 /* BlockScopedVariable */
+ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
+ : ts.Diagnostics.Duplicate_identifier_0;
+ ts.forEach(symbol.declarations, function (declaration) {
+ if (declaration.flags & 512 /* Default */) {
+ message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
+ }
+ });
+ ts.forEach(symbol.declarations, function (declaration) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
+ });
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
+ symbol = createSymbol(0 /* None */, name);
+ }
+ }
+ else {
+ symbol = createSymbol(0 /* None */, "__missing");
+ }
+ addDeclarationToSymbol(symbol, node, includes);
+ symbol.parent = parent;
+ return symbol;
+ }
+ function declareModuleMember(node, symbolFlags, symbolExcludes) {
+ var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */;
+ if (symbolFlags & 8388608 /* Alias */) {
+ if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) {
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ else {
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ else {
+ // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue,
+ // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
+ // on it. There are 2 main reasons:
+ //
+ // 1. We treat locals and exports of the same name as mutually exclusive within a container.
+ // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
+ // with the same name in the same container.
+ // TODO: Make this a more specific error and decouple it from the exclusion logic.
+ // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
+ // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
+ // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
+ if (hasExportModifier || container.flags & 131072 /* ExportContext */) {
+ var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) |
+ (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) |
+ (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0);
+ var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
+ local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ node.localSymbol = local;
+ return local;
+ }
+ else {
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ }
+ // All container nodes are kept on a linked list in declaration order. This list is used by
+ // the getLocalNameOfContainer function in the type checker to validate that the local name
+ // used for a container is unique.
+ function bindChildren(node) {
+ // Before we recurse into a node's chilren, we first save the existing parent, container
+ // and block-container. Then after we pop out of processing the children, we restore
+ // these saved values.
+ var saveParent = parent;
+ var saveContainer = container;
+ var savedBlockScopeContainer = blockScopeContainer;
+ // This node will now be set as the parent of all of its children as we recurse into them.
+ parent = node;
+ // Depending on what kind of node this is, we may have to adjust the current container
+ // and block-container. If the current node is a container, then it is automatically
+ // considered the current block-container as well. Also, for containers that we know
+ // may contain locals, we proactively initialize the .locals field. We do this because
+ // it's highly likely that the .locals will be needed to place some child in (for example,
+ // a parameter, or variable declaration).
+ //
+ // However, we do not proactively create the .locals for block-containers because it's
+ // totally normal and common for block-containers to never actually have a block-scoped
+ // variable in them. We don't want to end up allocating an object for every 'block' we
+ // run into when most of them won't be necessary.
+ //
+ // Finally, if this is a block-container, then we clear out any existing .locals object
+ // it may contain within it. This happens in incremental scenarios. Because we can be
+ // reusing a node from a previous compilation, that node may have had 'locals' created
+ // for it. We must clear this so we don't accidently move any stale data forward from
+ // a previous compilation.
+ var containerFlags = getContainerFlags(node);
+ if (containerFlags & 1 /* IsContainer */) {
+ container = blockScopeContainer = node;
+ if (containerFlags & 4 /* HasLocals */) {
+ container.locals = {};
+ }
+ addToContainerChain(container);
+ }
+ else if (containerFlags & 2 /* IsBlockScopedContainer */) {
+ blockScopeContainer = node;
+ blockScopeContainer.locals = undefined;
+ }
+ var savedReachabilityState;
+ var savedLabelStack;
+ var savedLabels;
+ var savedImplicitLabels;
+ var savedHasExplicitReturn;
+ var kind = node.kind;
+ var flags = node.flags;
+ // reset all reachability check related flags on node (for incremental scenarios)
+ flags &= ~1572864 /* ReachabilityCheckFlags */;
+ if (kind === 215 /* InterfaceDeclaration */) {
+ seenThisKeyword = false;
+ }
+ var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind);
+ if (saveState) {
+ savedReachabilityState = currentReachabilityState;
+ savedLabelStack = labelStack;
+ savedLabels = labelIndexMap;
+ savedImplicitLabels = implicitLabels;
+ savedHasExplicitReturn = hasExplicitReturn;
+ currentReachabilityState = 2 /* Reachable */;
+ hasExplicitReturn = false;
+ labelStack = labelIndexMap = implicitLabels = undefined;
+ }
+ bindReachableStatement(node);
+ if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) {
+ flags |= 524288 /* HasImplicitReturn */;
+ if (hasExplicitReturn) {
+ flags |= 1048576 /* HasExplicitReturn */;
+ }
+ }
+ if (kind === 215 /* InterfaceDeclaration */) {
+ flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */;
+ }
+ node.flags = flags;
+ if (saveState) {
+ hasExplicitReturn = savedHasExplicitReturn;
+ currentReachabilityState = savedReachabilityState;
+ labelStack = savedLabelStack;
+ labelIndexMap = savedLabels;
+ implicitLabels = savedImplicitLabels;
+ }
+ container = saveContainer;
+ parent = saveParent;
+ blockScopeContainer = savedBlockScopeContainer;
+ }
+ /**
+ * Returns true if node and its subnodes were successfully traversed.
+ * Returning false means that node was not examined and caller needs to dive into the node himself.
+ */
+ function bindReachableStatement(node) {
+ if (checkUnreachable(node)) {
+ ts.forEachChild(node, bind);
+ return;
+ }
+ switch (node.kind) {
+ case 198 /* WhileStatement */:
+ bindWhileStatement(node);
+ break;
+ case 197 /* DoStatement */:
+ bindDoStatement(node);
+ break;
+ case 199 /* ForStatement */:
+ bindForStatement(node);
+ break;
+ case 200 /* ForInStatement */:
+ case 201 /* ForOfStatement */:
+ bindForInOrForOfStatement(node);
+ break;
+ case 196 /* IfStatement */:
+ bindIfStatement(node);
+ break;
+ case 204 /* ReturnStatement */:
+ case 208 /* ThrowStatement */:
+ bindReturnOrThrow(node);
+ break;
+ case 203 /* BreakStatement */:
+ case 202 /* ContinueStatement */:
+ bindBreakOrContinueStatement(node);
+ break;
+ case 209 /* TryStatement */:
+ bindTryStatement(node);
+ break;
+ case 206 /* SwitchStatement */:
+ bindSwitchStatement(node);
+ break;
+ case 220 /* CaseBlock */:
+ bindCaseBlock(node);
+ break;
+ case 207 /* LabeledStatement */:
+ bindLabeledStatement(node);
+ break;
+ default:
+ ts.forEachChild(node, bind);
+ break;
+ }
+ }
+ function bindWhileStatement(n) {
+ var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ // bind expressions (don't affect reachability)
+ bind(n.expression);
+ currentReachabilityState = preWhileState;
+ var postWhileLabel = pushImplicitLabel();
+ bind(n.statement);
+ popImplicitLabel(postWhileLabel, postWhileState);
+ }
+ function bindDoStatement(n) {
+ var preDoState = currentReachabilityState;
+ var postDoLabel = pushImplicitLabel();
+ bind(n.statement);
+ var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState;
+ popImplicitLabel(postDoLabel, postDoState);
+ // bind expressions (don't affect reachability)
+ bind(n.expression);
+ }
+ function bindForStatement(n) {
+ var preForState = currentReachabilityState;
+ var postForLabel = pushImplicitLabel();
+ // bind expressions (don't affect reachability)
+ bind(n.initializer);
+ bind(n.condition);
+ bind(n.incrementor);
+ bind(n.statement);
+ // for statement is considered infinite when it condition is either omitted or is true keyword
+ // - for(..;;..)
+ // - for(..;true;..)
+ var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */);
+ var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState;
+ popImplicitLabel(postForLabel, postForState);
+ }
+ function bindForInOrForOfStatement(n) {
+ var preStatementState = currentReachabilityState;
+ var postStatementLabel = pushImplicitLabel();
+ // bind expressions (don't affect reachability)
+ bind(n.initializer);
+ bind(n.expression);
+ bind(n.statement);
+ popImplicitLabel(postStatementLabel, preStatementState);
+ }
+ function bindIfStatement(n) {
+ // denotes reachability state when entering 'thenStatement' part of the if statement:
+ // i.e. if condition is false then thenStatement is unreachable
+ var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ // denotes reachability state when entering 'elseStatement':
+ // i.e. if condition is true then elseStatement is unreachable
+ var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ currentReachabilityState = ifTrueState;
+ // bind expression (don't affect reachability)
+ bind(n.expression);
+ bind(n.thenStatement);
+ if (n.elseStatement) {
+ var preElseState = currentReachabilityState;
+ currentReachabilityState = ifFalseState;
+ bind(n.elseStatement);
+ currentReachabilityState = or(currentReachabilityState, preElseState);
+ }
+ else {
+ currentReachabilityState = or(currentReachabilityState, ifFalseState);
+ }
+ }
+ function bindReturnOrThrow(n) {
+ // bind expression (don't affect reachability)
+ bind(n.expression);
+ if (n.kind === 204 /* ReturnStatement */) {
+ hasExplicitReturn = true;
+ }
+ currentReachabilityState = 4 /* Unreachable */;
+ }
+ function bindBreakOrContinueStatement(n) {
+ // call bind on label (don't affect reachability)
+ bind(n.label);
+ // for continue case touch label so it will be marked a used
+ var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */);
+ if (isValidJump) {
+ currentReachabilityState = 4 /* Unreachable */;
+ }
+ }
+ function bindTryStatement(n) {
+ // catch\finally blocks has the same reachability as try block
+ var preTryState = currentReachabilityState;
+ bind(n.tryBlock);
+ var postTryState = currentReachabilityState;
+ currentReachabilityState = preTryState;
+ bind(n.catchClause);
+ var postCatchState = currentReachabilityState;
+ currentReachabilityState = preTryState;
+ bind(n.finallyBlock);
+ // post catch/finally state is reachable if
+ // - post try state is reachable - control flow can fall out of try block
+ // - post catch state is reachable - control flow can fall out of catch block
+ currentReachabilityState = or(postTryState, postCatchState);
+ }
+ function bindSwitchStatement(n) {
+ var preSwitchState = currentReachabilityState;
+ var postSwitchLabel = pushImplicitLabel();
+ // bind expression (don't affect reachability)
+ bind(n.expression);
+ bind(n.caseBlock);
+ var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; });
+ // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case
+ var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState;
+ popImplicitLabel(postSwitchLabel, postSwitchState);
+ }
+ function bindCaseBlock(n) {
+ var startState = currentReachabilityState;
+ for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) {
+ var clause = _a[_i];
+ currentReachabilityState = startState;
+ bind(clause);
+ if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) {
+ errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
+ }
+ }
+ }
+ function bindLabeledStatement(n) {
+ // call bind on label (don't affect reachability)
+ bind(n.label);
+ var ok = pushNamedLabel(n.label);
+ bind(n.statement);
+ if (ok) {
+ popNamedLabel(n.label, currentReachabilityState);
+ }
+ }
+ function getContainerFlags(node) {
+ switch (node.kind) {
+ case 186 /* ClassExpression */:
+ case 214 /* ClassDeclaration */:
+ case 215 /* InterfaceDeclaration */:
+ case 217 /* EnumDeclaration */:
+ case 155 /* TypeLiteral */:
+ case 165 /* ObjectLiteralExpression */:
+ return 1 /* IsContainer */;
+ case 147 /* CallSignature */:
+ case 148 /* ConstructSignature */:
+ case 149 /* IndexSignature */:
+ case 143 /* MethodDeclaration */:
+ case 142 /* MethodSignature */:
+ case 213 /* FunctionDeclaration */:
+ case 144 /* Constructor */:
+ case 145 /* GetAccessor */:
+ case 146 /* SetAccessor */:
+ case 152 /* FunctionType */:
+ case 153 /* ConstructorType */:
+ case 173 /* FunctionExpression */:
+ case 174 /* ArrowFunction */:
+ case 218 /* ModuleDeclaration */:
+ case 248 /* SourceFile */:
+ case 216 /* TypeAliasDeclaration */:
+ return 5 /* IsContainerWithLocals */;
+ case 244 /* CatchClause */:
+ case 199 /* ForStatement */:
+ case 200 /* ForInStatement */:
+ case 201 /* ForOfStatement */:
+ case 220 /* CaseBlock */:
+ return 2 /* IsBlockScopedContainer */;
+ case 192 /* Block */:
+ // do not treat blocks directly inside a function as a block-scoped-container.
+ // Locals that reside in this block should go to the function locals. Othewise 'x'
+ // would not appear to be a redeclaration of a block scoped local in the following
+ // example:
+ //
+ // function foo() {
+ // var x;
+ // let x;
+ // }
+ //
+ // If we placed 'var x' into the function locals and 'let x' into the locals of
+ // the block, then there would be no collision.
+ //
+ // By not creating a new block-scoped-container here, we ensure that both 'var x'
+ // and 'let x' go into the Function-container's locals, and we do get a collision
+ // conflict.
+ return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
+ }
+ return 0 /* None */;
+ }
+ function addToContainerChain(next) {
+ if (lastContainer) {
+ lastContainer.nextContainer = next;
+ }
+ lastContainer = next;
+ }
+ function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
+ // Just call this directly so that the return type of this function stays "void".
+ declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes);
+ }
+ function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) {
+ switch (container.kind) {
+ // Modules, source files, and classes need specialized handling for how their
+ // members are declared (for example, a member of a class will go into a specific
+ // symbol table depending on if it is static or not). We defer to specialized
+ // handlers to take care of declaring these child members.
+ case 218 /* ModuleDeclaration */:
+ return declareModuleMember(node, symbolFlags, symbolExcludes);
+ case 248 /* SourceFile */:
+ return declareSourceFileMember(node, symbolFlags, symbolExcludes);
+ case 186 /* ClassExpression */:
+ case 214 /* ClassDeclaration */:
+ return declareClassMember(node, symbolFlags, symbolExcludes);
+ case 217 /* EnumDeclaration */:
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ case 155 /* TypeLiteral */:
+ case 165 /* ObjectLiteralExpression */:
+ case 215 /* InterfaceDeclaration */:
+ // Interface/Object-types always have their children added to the 'members' of
+ // their container. They are only accessible through an instance of their
+ // container, and are never in scope otherwise (even inside the body of the
+ // object / type / interface declaring them). An exception is type parameters,
+ // which are in scope without qualification (similar to 'locals').
+ return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ case 152 /* FunctionType */:
+ case 153 /* ConstructorType */:
+ case 147 /* CallSignature */:
+ case 148 /* ConstructSignature */:
+ case 149 /* IndexSignature */:
+ case 143 /* MethodDeclaration */:
+ case 142 /* MethodSignature */:
+ case 144 /* Constructor */:
+ case 145 /* GetAccessor */:
+ case 146 /* SetAccessor */:
+ case 213 /* FunctionDeclaration */:
+ case 173 /* FunctionExpression */:
+ case 174 /* ArrowFunction */:
+ case 216 /* TypeAliasDeclaration */:
+ // All the children of these container types are never visible through another
+ // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
+ // they're only accessed 'lexically' (i.e. from code that exists underneath
+ // their container in the tree. To accomplish this, we simply add their declared
+ // symbol to the 'locals' of the container. These symbols can then be found as
+ // the type checker walks up the containers, checking them for matching names.
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function declareClassMember(node, symbolFlags, symbolExcludes) {
+ return node.flags & 64 /* Static */
+ ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
+ : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
+ return ts.isExternalModule(file)
+ ? declareModuleMember(node, symbolFlags, symbolExcludes)
+ : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ function hasExportDeclarations(node) {
+ var body = node.kind === 248 /* SourceFile */ ? node : node.body;
+ if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) {
+ for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
+ var stat = _a[_i];
+ if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ function setExportContextFlag(node) {
+ // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
+ // declarations with export modifiers) is an export context in which declarations are implicitly exported.
+ if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) {
+ node.flags |= 131072 /* ExportContext */;
+ }
+ else {
+ node.flags &= ~131072 /* ExportContext */;
+ }
+ }
+ function bindModuleDeclaration(node) {
+ setExportContextFlag(node);
+ if (node.name.kind === 9 /* StringLiteral */) {
+ declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
+ }
+ else {
+ var state = getModuleInstanceState(node);
+ if (state === 0 /* NonInstantiated */) {
+ declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
+ if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
+ // if module was already merged with some function, class or non-const enum
+ // treat is a non-const-enum-only
+ node.symbol.constEnumOnlyModule = false;
+ }
+ else {
+ var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */;
+ if (node.symbol.constEnumOnlyModule === undefined) {
+ // non-merged case - use the current state
+ node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
+ }
+ else {
+ // merged case: module is const enum only if all its pieces are non-instantiated or const enum
+ node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
+ }
+ }
+ }
+ }
+ }
+ function bindFunctionOrConstructorType(node) {
+ // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
+ // to the one we would get for: { <...>(...): T }
+ //
+ // We do that by making an anonymous type literal symbol, and then setting the function
+ // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
+ // from an actual type literal symbol you would have gotten had you used the long form.
+ var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node));
+ addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
+ var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type");
+ addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
+ typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a);
+ var _a;
+ }
+ function bindObjectLiteralExpression(node) {
+ var ElementKind;
+ (function (ElementKind) {
+ ElementKind[ElementKind["Property"] = 1] = "Property";
+ ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
+ })(ElementKind || (ElementKind = {}));
+ if (inStrictMode) {
+ var seen = {};
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (prop.name.kind !== 69 /* Identifier */) {
+ continue;
+ }
+ var identifier = prop.name;
+ // ECMA-262 11.1.5 Object Initialiser
+ // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
+ // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
+ // IsDataDescriptor(propId.descriptor) is true.
+ // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
+ // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
+ // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
+ // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
+ var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */
+ ? 1 /* Property */
+ : 2 /* Accessor */;
+ var existingKind = seen[identifier.text];
+ if (!existingKind) {
+ seen[identifier.text] = currentKind;
+ continue;
+ }
+ if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
+ var span = ts.getErrorSpanForNode(file, identifier);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
+ }
+ }
+ }
+ return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object");
+ }
+ function bindAnonymousDeclaration(node, symbolFlags, name) {
+ var symbol = createSymbol(symbolFlags, name);
+ addDeclarationToSymbol(symbol, node, symbolFlags);
+ }
+ function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
+ switch (blockScopeContainer.kind) {
+ case 218 /* ModuleDeclaration */:
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ case 248 /* SourceFile */:
+ if (ts.isExternalModule(container)) {
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ }
+ // fall through.
+ default:
+ if (!blockScopeContainer.locals) {
+ blockScopeContainer.locals = {};
+ addToContainerChain(blockScopeContainer);
+ }
+ declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function bindBlockScopedVariableDeclaration(node) {
+ bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */);
+ }
+ // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
+ // check for reserved words used as identifiers in strict mode code.
+ function checkStrictModeIdentifier(node) {
+ if (inStrictMode &&
+ node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ &&
+ node.originalKeywordKind <= 114 /* LastFutureReservedWord */ &&
+ !ts.isIdentifierName(node)) {
+ // Report error only if there are no parse errors in file
+ if (!file.parseDiagnostics.length) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
+ }
+ }
+ }
+ function getStrictModeIdentifierMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
+ }
+ function checkStrictModeBinaryExpression(node) {
+ if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
+ // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
+ // Assignment operator(11.13) or of a PostfixExpression(11.3)
+ checkStrictModeEvalOrArguments(node, node.left);
+ }
+ }
+ function checkStrictModeCatchClause(node) {
+ // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
+ // Catch production is eval or arguments
+ if (inStrictMode && node.variableDeclaration) {
+ checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
+ }
+ }
+ function checkStrictModeDeleteExpression(node) {
+ // Grammar checking
+ if (inStrictMode && node.expression.kind === 69 /* Identifier */) {
+ // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
+ // UnaryExpression is a direct reference to a variable, function argument, or function name
+ var span = ts.getErrorSpanForNode(file, node.expression);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
+ }
+ }
+ function isEvalOrArgumentsIdentifier(node) {
+ return node.kind === 69 /* Identifier */ &&
+ (node.text === "eval" || node.text === "arguments");
+ }
+ function checkStrictModeEvalOrArguments(contextNode, name) {
+ if (name && name.kind === 69 /* Identifier */) {
+ var identifier = name;
+ if (isEvalOrArgumentsIdentifier(identifier)) {
+ // We check first if the name is inside class declaration or class expression; if so give explicit message
+ // otherwise report generic error message.
+ var span = ts.getErrorSpanForNode(file, name);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));
+ }
+ }
+ }
+ function getStrictModeEvalOrArgumentsMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
+ }
+ function checkStrictModeFunctionName(node) {
+ if (inStrictMode) {
+ // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ }
+ function checkStrictModeNumericLiteral(node) {
+ if (inStrictMode && node.flags & 32768 /* OctalLiteral */) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
+ }
+ }
+ function checkStrictModePostfixUnaryExpression(node) {
+ // Grammar checking
+ // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
+ // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
+ // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
+ }
+ function checkStrictModePrefixUnaryExpression(node) {
+ // Grammar checking
+ if (inStrictMode) {
+ if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
+ }
+ }
+ function checkStrictModeWithStatement(node) {
+ // Grammar checking for withStatement
+ if (inStrictMode) {
+ errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
+ }
+ }
+ function errorOnFirstToken(node, message, arg0, arg1, arg2) {
+ var span = ts.getSpanOfTokenAtPosition(file, node.pos);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
+ }
+ function getDestructuringParameterName(node) {
+ return "__" + ts.indexOf(node.parent.parameters, node);
+ }
+ function bind(node) {
+ if (!node) {
+ return;
+ }
+ node.parent = parent;
+ var savedInStrictMode = inStrictMode;
+ if (!savedInStrictMode) {
+ updateStrictMode(node);
+ }
+ // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
+ // and then potentially add the symbol to an appropriate symbol table. Possible
+ // destination symbol tables are:
+ //
+ // 1) The 'exports' table of the current container's symbol.
+ // 2) The 'members' table of the current container's symbol.
+ // 3) The 'locals' table of the current container.
+ //
+ // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
+ // (like TypeLiterals for example) will not be put in any table.
+ bindWorker(node);
+ // Then we recurse into the children of the node to bind them as well. For certain
+ // symbols we do specialized work when we recurse. For example, we'll keep track of
+ // the current 'container' node when it changes. This helps us know which symbol table
+ // a local should go into for example.
+ bindChildren(node);
+ inStrictMode = savedInStrictMode;
+ }
+ function updateStrictMode(node) {
+ switch (node.kind) {
+ case 248 /* SourceFile */:
+ case 219 /* ModuleBlock */:
+ updateStrictModeStatementList(node.statements);
+ return;
+ case 192 /* Block */:
+ if (ts.isFunctionLike(node.parent)) {
+ updateStrictModeStatementList(node.statements);
+ }
+ return;
+ case 214 /* ClassDeclaration */:
+ case 186 /* ClassExpression */:
+ // All classes are automatically in strict mode in ES6.
+ inStrictMode = true;
+ return;
+ }
+ }
+ function updateStrictModeStatementList(statements) {
+ for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
+ var statement = statements_1[_i];
+ if (!ts.isPrologueDirective(statement)) {
+ return;
+ }
+ if (isUseStrictPrologueDirective(statement)) {
+ inStrictMode = true;
+ return;
+ }
+ }
+ }
+ /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
+ function isUseStrictPrologueDirective(node) {
+ var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression);
+ // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
+ // string to contain unicode escapes (as per ES5).
+ return nodeText === "\"use strict\"" || nodeText === "'use strict'";
+ }
+ function bindWorker(node) {
+ switch (node.kind) {
+ /* Strict mode checks */
+ case 69 /* Identifier */:
+ return checkStrictModeIdentifier(node);
+ case 181 /* BinaryExpression */:
+ if (ts.isInJavaScriptFile(node)) {
+ if (ts.isExportsPropertyAssignment(node)) {
+ bindExportsPropertyAssignment(node);
+ }
+ else if (ts.isModuleExportsAssignment(node)) {
+ bindModuleExportsAssignment(node);
+ }
+ }
+ return checkStrictModeBinaryExpression(node);
+ case 244 /* CatchClause */:
+ return checkStrictModeCatchClause(node);
+ case 175 /* DeleteExpression */:
+ return checkStrictModeDeleteExpression(node);
+ case 8 /* NumericLiteral */:
+ return checkStrictModeNumericLiteral(node);
+ case 180 /* PostfixUnaryExpression */:
+ return checkStrictModePostfixUnaryExpression(node);
+ case 179 /* PrefixUnaryExpression */:
+ return checkStrictModePrefixUnaryExpression(node);
+ case 205 /* WithStatement */:
+ return checkStrictModeWithStatement(node);
+ case 97 /* ThisKeyword */:
+ seenThisKeyword = true;
+ return;
+ case 137 /* TypeParameter */:
+ return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */);
+ case 138 /* Parameter */:
+ return bindParameter(node);
+ case 211 /* VariableDeclaration */:
+ case 163 /* BindingElement */:
+ return bindVariableDeclarationOrBindingElement(node);
+ case 141 /* PropertyDeclaration */:
+ case 140 /* PropertySignature */:
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */);
+ case 245 /* PropertyAssignment */:
+ case 246 /* ShorthandPropertyAssignment */:
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */);
+ case 247 /* EnumMember */:
+ return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */);
+ case 147 /* CallSignature */:
+ case 148 /* ConstructSignature */:
+ case 149 /* IndexSignature */:
+ return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
+ case 143 /* MethodDeclaration */:
+ case 142 /* MethodSignature */:
+ // If this is an ObjectLiteralExpression method, then it sits in the same space
+ // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
+ // so that it will conflict with any other object literal members with the same
+ // name.
+ return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */);
+ case 213 /* FunctionDeclaration */:
+ checkStrictModeFunctionName(node);
+ return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */);
+ case 144 /* Constructor */:
+ return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
+ case 145 /* GetAccessor */:
+ return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */);
+ case 146 /* SetAccessor */:
+ return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */);
+ case 152 /* FunctionType */:
+ case 153 /* ConstructorType */:
+ return bindFunctionOrConstructorType(node);
+ case 155 /* TypeLiteral */:
+ return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type");
+ case 165 /* ObjectLiteralExpression */:
+ return bindObjectLiteralExpression(node);
+ case 173 /* FunctionExpression */:
+ case 174 /* ArrowFunction */:
+ checkStrictModeFunctionName(node);
+ var bindingName = node.name ? node.name.text : "__function";
+ return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
+ case 168 /* CallExpression */:
+ if (ts.isInJavaScriptFile(node)) {
+ bindCallExpression(node);
+ }
+ break;
+ // Members of classes, interfaces, and modules
+ case 186 /* ClassExpression */:
+ case 214 /* ClassDeclaration */:
+ return bindClassLikeDeclaration(node);
+ case 215 /* InterfaceDeclaration */:
+ return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */);
+ case 216 /* TypeAliasDeclaration */:
+ return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */);
+ case 217 /* EnumDeclaration */:
+ return bindEnumDeclaration(node);
+ case 218 /* ModuleDeclaration */:
+ return bindModuleDeclaration(node);
+ // Imports and exports
+ case 221 /* ImportEqualsDeclaration */:
+ case 224 /* NamespaceImport */:
+ case 226 /* ImportSpecifier */:
+ case 230 /* ExportSpecifier */:
+ return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
+ case 223 /* ImportClause */:
+ return bindImportClause(node);
+ case 228 /* ExportDeclaration */:
+ return bindExportDeclaration(node);
+ case 227 /* ExportAssignment */:
+ return bindExportAssignment(node);
+ case 248 /* SourceFile */:
+ return bindSourceFileIfExternalModule();
+ }
+ }
+ function bindSourceFileIfExternalModule() {
+ setExportContextFlag(file);
+ if (ts.isExternalModule(file)) {
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindSourceFileAsExternalModule() {
+ bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
+ }
+ function bindExportAssignment(node) {
+ var boundExpression = node.kind === 227 /* ExportAssignment */ ? node.expression : node.right;
+ if (!container.symbol || !container.symbol.exports) {
+ // Export assignment in some sort of block construct
+ bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node));
+ }
+ else if (boundExpression.kind === 69 /* Identifier */) {
+ // An export default clause with an identifier exports all meanings of that identifier
+ declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
+ }
+ else {
+ // An export default clause with an expression exports a value
+ declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
+ }
+ }
+ function bindExportDeclaration(node) {
+ if (!container.symbol || !container.symbol.exports) {
+ // Export * in some sort of block construct
+ bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node));
+ }
+ else if (!node.exportClause) {
+ // All export * declarations are collected in an __export symbol
+ declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */);
+ }
+ }
+ function bindImportClause(node) {
+ if (node.name) {
+ declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
+ }
+ }
+ function setCommonJsModuleIndicator(node) {
+ if (!file.commonJsModuleIndicator) {
+ file.commonJsModuleIndicator = node;
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindExportsPropertyAssignment(node) {
+ // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
+ // expression is the declaration
+ setCommonJsModuleIndicator(node);
+ declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */);
+ }
+ function bindModuleExportsAssignment(node) {
+ // 'module.exports = expr' assignment
+ setCommonJsModuleIndicator(node);
+ bindExportAssignment(node);
+ }
+ function bindCallExpression(node) {
+ // 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 && ts.isRequireCall(node)) {
+ setCommonJsModuleIndicator(node);
+ }
+ }
+ function bindClassLikeDeclaration(node) {
+ if (node.kind === 214 /* ClassDeclaration */) {
+ bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */);
+ }
+ else {
+ var bindingName = node.name ? node.name.text : "__class";
+ bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
+ // Add name of class expression into the map for semantic classifier
+ if (node.name) {
+ classifiableNames[node.name.text] = node.name.text;
+ }
+ }
+ var symbol = node.symbol;
+ // TypeScript 1.0 spec (April 2014): 8.4
+ // Every class automatically contains a static property member named 'prototype', the
+ // type of which is an instantiation of the class type with type Any supplied as a type
+ // argument for each type parameter. It is an error to explicitly declare a static
+ // property member with the name 'prototype'.
+ //
+ // Note: we check for this here because this class may be merging into a module. The
+ // module might have an exported variable called 'prototype'. We can't allow that as
+ // that would clash with the built-in 'prototype' for the class.
+ var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype");
+ if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) {
+ if (node.name) {
+ node.name.parent = node;
+ }
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
+ }
+ symbol.exports[prototypeSymbol.name] = prototypeSymbol;
+ prototypeSymbol.parent = symbol;
+ }
+ function bindEnumDeclaration(node) {
+ return ts.isConst(node)
+ ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
+ : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
+ }
+ function bindVariableDeclarationOrBindingElement(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (!ts.isBindingPattern(node.name)) {
+ if (ts.isBlockOrCatchScoped(node)) {
+ bindBlockScopedVariableDeclaration(node);
+ }
+ else if (ts.isParameterDeclaration(node)) {
+ // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration
+ // because its parent chain has already been set up, since parents are set before descending into children.
+ //
+ // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
+ // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
+ // For example:
+ // function foo([a,a]) {} // Duplicate Identifier error
+ // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
+ // // which correctly set excluded symbols
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */);
+ }
+ }
+ }
+ function bindParameter(node) {
+ if (inStrictMode) {
+ // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
+ // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (ts.isBindingPattern(node.name)) {
+ bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node));
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
+ }
+ // If this is a property-parameter, then also declare the property symbol into the
+ // containing class.
+ if (node.flags & 56 /* AccessibilityModifier */ &&
+ node.parent.kind === 144 /* Constructor */ &&
+ ts.isClassLike(node.parent.parent)) {
+ var classDeclaration = node.parent.parent;
+ declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */);
+ }
+ }
+ function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
+ return ts.hasDynamicName(node)
+ ? bindAnonymousDeclaration(node, symbolFlags, "__computed")
+ : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ }
+ // reachability checks
+ function pushNamedLabel(name) {
+ initializeReachabilityStateIfNecessary();
+ if (ts.hasProperty(labelIndexMap, name.text)) {
+ return false;
+ }
+ labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1;
+ return true;
+ }
+ function pushImplicitLabel() {
+ initializeReachabilityStateIfNecessary();
+ var index = labelStack.push(1 /* Unintialized */) - 1;
+ implicitLabels.push(index);
+ return index;
+ }
+ function popNamedLabel(label, outerState) {
+ var index = labelIndexMap[label.text];
+ ts.Debug.assert(index !== undefined);
+ ts.Debug.assert(labelStack.length == index + 1);
+ labelIndexMap[label.text] = undefined;
+ setCurrentStateAtLabel(labelStack.pop(), outerState, label);
+ }
+ function popImplicitLabel(implicitLabelIndex, outerState) {
+ if (labelStack.length !== implicitLabelIndex + 1) {
+ ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex);
+ }
+ var i = implicitLabels.pop();
+ if (implicitLabelIndex !== i) {
+ ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex);
+ }
+ setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined);
+ }
+ function setCurrentStateAtLabel(innerMergedState, outerState, label) {
+ if (innerMergedState === 1 /* Unintialized */) {
+ if (label && !options.allowUnusedLabels) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label));
+ }
+ currentReachabilityState = outerState;
+ }
+ else {
+ currentReachabilityState = or(innerMergedState, outerState);
+ }
+ }
+ function jumpToLabel(label, outerState) {
+ initializeReachabilityStateIfNecessary();
+ var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels);
+ if (index === undefined) {
+ // reference to unknown label or
+ // break/continue used outside of loops
+ return false;
+ }
+ var stateAtLabel = labelStack[index];
+ labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState);
+ return true;
+ }
+ function checkUnreachable(node) {
+ switch (currentReachabilityState) {
+ case 4 /* Unreachable */:
+ var reportError =
+ // report error on all statements except empty ones
+ (ts.isStatement(node) && node.kind !== 194 /* EmptyStatement */) ||
+ // report error on class declarations
+ node.kind === 214 /* ClassDeclaration */ ||
+ // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
+ (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
+ // report error on regular enums and const enums if preserveConstEnums is set
+ (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
+ if (reportError) {
+ currentReachabilityState = 8 /* ReportedUnreachable */;
+ // unreachable code is reported if
+ // - user has explicitly asked about it AND
+ // - statement is in not ambient context (statements in ambient context is already an error
+ // so we should not report extras) AND
+ // - node is not variable statement OR
+ // - node is block scoped variable statement OR
+ // - node is not block scoped variable statement and at least one variable declaration has initializer
+ // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
+ // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
+ var reportUnreachableCode = !options.allowUnreachableCode &&
+ !ts.isInAmbientContext(node) &&
+ (node.kind !== 193 /* VariableStatement */ ||
+ ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ ||
+ ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
+ if (reportUnreachableCode) {
+ errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected);
+ }
+ }
+ case 8 /* ReportedUnreachable */:
+ return true;
+ default:
+ return false;
+ }
+ function shouldReportErrorOnModuleDeclaration(node) {
+ var instanceState = getModuleInstanceState(node);
+ return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums);
+ }
+ }
+ function initializeReachabilityStateIfNecessary() {
+ if (labelIndexMap) {
+ return;
+ }
+ currentReachabilityState = 2 /* Reachable */;
+ labelIndexMap = {};
+ labelStack = [];
+ implicitLabels = [];
+ }
+ }
+})(ts || (ts = {}));
///
/* @internal */
var ts;
@@ -13755,7 +13918,7 @@ var ts;
symbolToString: symbolToString,
getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
getRootSymbols: getRootSymbols,
- getContextualType: getContextualType,
+ getContextualType: getApparentTypeOfContextualType,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: getResolvedSignature,
getConstantValue: getConstantValue,
@@ -14025,7 +14188,7 @@ var ts;
return ts.getAncestor(node, 248 /* SourceFile */);
}
function isGlobalSourceFile(node) {
- return node.kind === 248 /* SourceFile */ && !ts.isExternalModule(node);
+ return node.kind === 248 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning && ts.hasProperty(symbols, name)) {
@@ -14127,15 +14290,24 @@ var ts;
}
switch (location.kind) {
case 248 /* SourceFile */:
- if (!ts.isExternalModule(location))
+ if (!ts.isExternalOrCommonJsModule(location))
break;
case 218 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
if (location.kind === 248 /* SourceFile */ ||
(location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) {
- // It's an external module. Because of module/namespace merging, a module's exports are in scope,
- // yet we never want to treat an export specifier as putting a member in scope. Therefore,
- // if the name we find is purely an export specifier, it is not actually considered in scope.
+ // It's an external module. First see if the module has an export default and if the local
+ // name of that export default matches.
+ if (result = moduleExports["default"]) {
+ var localSymbol = ts.getLocalSymbolForExportDefault(result);
+ if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
+ break loop;
+ }
+ result = undefined;
+ }
+ // Because of module/namespace merging, a module's exports are in scope,
+ // yet we never want to treat an export specifier as putting a member in scope.
+ // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
// Two things to note about this:
// 1. We have to check this without calling getSymbol. The problem with calling getSymbol
// on an export specifier is that it might find the export specifier itself, and try to
@@ -14149,12 +14321,6 @@ var ts;
ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) {
break;
}
- result = moduleExports["default"];
- var localSymbol = ts.getLocalSymbolForExportDefault(result);
- if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) {
- break loop;
- }
- result = undefined;
}
if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) {
break loop;
@@ -14297,7 +14463,7 @@ var ts;
// declare module foo {
// interface bar {}
// }
- // let foo/*1*/: foo/*2*/.bar;
+ // const foo/*1*/: foo/*2*/.bar;
// The foo at /*1*/ and /*2*/ will share same symbol with two meaning
// block - scope variable and namespace module. However, only when we
// try to resolve name in /*1*/ which is used in variable position,
@@ -14601,6 +14767,9 @@ var ts;
if (moduleName === undefined) {
return;
}
+ if (moduleName.indexOf("!") >= 0) {
+ moduleName = moduleName.substr(0, moduleName.indexOf("!"));
+ }
var isRelative = ts.isExternalModuleNameRelative(moduleName);
if (!isRelative) {
var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */);
@@ -14788,7 +14957,7 @@ var ts;
}
switch (location_1.kind) {
case 248 /* SourceFile */:
- if (!ts.isExternalModule(location_1)) {
+ if (!ts.isExternalOrCommonJsModule(location_1)) {
break;
}
case 218 /* ModuleDeclaration */:
@@ -14910,7 +15079,7 @@ var ts;
// export class c {
// }
// }
- // let x: typeof m.c
+ // const x: typeof m.c
// In the above example when we start with checking if typeof m.c symbol is accessible,
// we are going to see if c can be accessed in scope directly.
// But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
@@ -14949,7 +15118,7 @@ var ts;
}
function hasExternalModuleSymbol(declaration) {
return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) ||
- (declaration.kind === 248 /* SourceFile */ && ts.isExternalModule(declaration));
+ (declaration.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol) {
var aliasesToMakeVisible;
@@ -15100,7 +15269,7 @@ var ts;
parentSymbol = symbol;
appendSymbolNameOnly(symbol, writer);
}
- // Let the writer know we just wrote out a symbol. The declaration emitter writer uses
+ // const the writer know we just wrote out a symbol. The declaration emitter writer uses
// this to determine if an import it has previously seen (and not written out) needs
// to be written to the file once the walk of the tree is complete.
//
@@ -15181,7 +15350,7 @@ var ts;
writeAnonymousType(type, flags);
}
else if (type.flags & 256 /* StringLiteral */) {
- writer.writeStringLiteral(type.text);
+ writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\"");
}
else {
// Should never get here
@@ -15568,7 +15737,7 @@ var ts;
}
}
else if (node.kind === 248 /* SourceFile */) {
- return ts.isExternalModule(node) ? node : undefined;
+ return ts.isExternalOrCommonJsModule(node) ? node : undefined;
}
}
ts.Debug.fail("getContainingModule cant reach here");
@@ -15650,7 +15819,7 @@ var ts;
// Private/protected properties/methods are not visible
return false;
}
- // Public properties/methods are visible if its parents are visible, so let it fall into next case statement
+ // Public properties/methods are visible if its parents are visible, so const it fall into next case statement
case 144 /* Constructor */:
case 148 /* ConstructSignature */:
case 147 /* CallSignature */:
@@ -15678,7 +15847,7 @@ var ts;
// Source file is always visible
case 248 /* SourceFile */:
return true;
- // Export assignements do not create name bindings outside the module
+ // Export assignments do not create name bindings outside the module
case 227 /* ExportAssignment */:
return false;
default:
@@ -15814,6 +15983,23 @@ var ts;
var symbol = getSymbolOfNode(node);
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);
}
+ function getTextOfPropertyName(name) {
+ switch (name.kind) {
+ case 69 /* Identifier */:
+ return name.text;
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ return name.text;
+ case 136 /* ComputedPropertyName */:
+ if (ts.isStringOrNumericLiteral(name.expression.kind)) {
+ return name.expression.text;
+ }
+ }
+ return undefined;
+ }
+ function isComputedNonLiteralName(name) {
+ return name.kind === 136 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind);
+ }
// Return the inferred type for a binding element
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
@@ -15835,10 +16021,15 @@ var ts;
if (pattern.kind === 161 /* ObjectBindingPattern */) {
// Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
var name_10 = declaration.propertyName || declaration.name;
+ if (isComputedNonLiteralName(name_10)) {
+ // computed properties with non-literal names are treated as 'any'
+ return anyType;
+ }
// Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
// or otherwise the type of the string index signature.
- type = getTypeOfPropertyOfType(parentType, name_10.text) ||
- isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
+ var text = getTextOfPropertyName(name_10);
+ type = getTypeOfPropertyOfType(parentType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
getIndexTypeOfType(parentType, 0 /* String */);
if (!type) {
error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10));
@@ -15938,10 +16129,17 @@ var ts;
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType) {
var members = {};
+ var hasComputedProperties = false;
ts.forEach(pattern.elements, function (e) {
- var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);
var name = e.propertyName || e.name;
- var symbol = createSymbol(flags, name.text);
+ if (isComputedNonLiteralName(name)) {
+ // do not include computed properties in the implied type
+ hasComputedProperties = true;
+ return;
+ }
+ var text = getTextOfPropertyName(name);
+ var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);
+ var symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType);
symbol.bindingElement = e;
members[symbol.name] = symbol;
@@ -15950,6 +16148,9 @@ var ts;
if (includePatternInType) {
result.pattern = pattern;
}
+ if (hasComputedProperties) {
+ result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */;
+ }
return result;
}
// Return the type implied by an array binding pattern
@@ -16026,6 +16227,14 @@ var ts;
if (declaration.kind === 227 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
+ // Handle module.exports = expr
+ if (declaration.kind === 181 /* BinaryExpression */) {
+ return links.type = checkExpression(declaration.right);
+ }
+ // Handle exports.p = expr
+ if (declaration.kind === 166 /* PropertyAccessExpression */) {
+ return checkExpressionCached(declaration.parent.right);
+ }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
return unknownType;
@@ -16304,23 +16513,25 @@ var ts;
}
function resolveBaseTypesOfClass(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
- var baseContructorType = getBaseConstructorTypeOfClass(type);
- if (!(baseContructorType.flags & 80896 /* ObjectType */)) {
+ var baseConstructorType = getBaseConstructorTypeOfClass(type);
+ if (!(baseConstructorType.flags & 80896 /* ObjectType */)) {
return;
}
var baseTypeNode = getBaseTypeNodeOfClass(type);
var baseType;
- if (baseContructorType.symbol && baseContructorType.symbol.flags & 32 /* Class */) {
- // When base constructor type is a class we know that the constructors all have the same type parameters as the
+ var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
+ if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
+ areAllOuterTypeParametersApplied(originalBaseType)) {
+ // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the
// class and all return the instance type of the class. There is no need for further checks and we can apply the
// type arguments in the same manner as a type reference to get the same error reporting experience.
- baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol);
+ baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
}
else {
// The class derives from a "class-like" constructor function, check that we have at least one construct signature
// with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
// we check that all instantiated signatures return the same type.
- var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments);
+ var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments);
if (!constructors.length) {
error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
return;
@@ -16345,6 +16556,17 @@ var ts;
type.resolvedBaseTypes.push(baseType);
}
}
+ function areAllOuterTypeParametersApplied(type) {
+ // An unapplied type parameter has its symbol still the same as the matching argument symbol.
+ // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
+ var outerTypeParameters = type.outerTypeParameters;
+ if (outerTypeParameters) {
+ var last = outerTypeParameters.length - 1;
+ var typeArguments = type.typeArguments;
+ return outerTypeParameters[last].symbol !== typeArguments[last].symbol;
+ }
+ return true;
+ }
function resolveBaseTypesOfInterface(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
@@ -16424,7 +16646,7 @@ var ts;
type.typeArguments = type.typeParameters;
type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */);
type.thisType.symbol = symbol;
- type.thisType.constraint = getTypeWithThisArgument(type);
+ type.thisType.constraint = type;
}
}
return links.declaredType;
@@ -16939,6 +17161,20 @@ var ts;
type = getApparentType(type);
return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
}
+ /**
+ * The apparent type of a type parameter is the base constraint instantiated with the type parameter
+ * as the type argument for the 'this' type.
+ */
+ function getApparentTypeOfTypeParameter(type) {
+ if (!type.resolvedApparentType) {
+ var constraintType = getConstraintOfTypeParameter(type);
+ while (constraintType && constraintType.flags & 512 /* TypeParameter */) {
+ constraintType = getConstraintOfTypeParameter(constraintType);
+ }
+ type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
+ }
+ return type.resolvedApparentType;
+ }
/**
* For a type parameter, return the base constraint of the type parameter. For the string, number,
* boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
@@ -16946,12 +17182,7 @@ var ts;
*/
function getApparentType(type) {
if (type.flags & 512 /* TypeParameter */) {
- do {
- type = getConstraintOfTypeParameter(type);
- } while (type && type.flags & 512 /* TypeParameter */);
- if (!type) {
- type = emptyObjectType;
- }
+ type = getApparentTypeOfTypeParameter(type);
}
if (type.flags & 258 /* StringLike */) {
type = globalStringType;
@@ -17116,7 +17347,7 @@ var ts;
if (node.initializer) {
var signatureDeclaration = node.parent;
var signature = getSignatureFromDeclaration(signatureDeclaration);
- var parameterIndex = signatureDeclaration.parameters.indexOf(node);
+ var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node);
ts.Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
@@ -17217,6 +17448,16 @@ var ts;
}
return result;
}
+ function resolveExternalModuleTypeByLiteral(name) {
+ var moduleSym = resolveExternalModuleName(name, name);
+ if (moduleSym) {
+ var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
+ if (resolvedModuleSymbol) {
+ return getTypeOfSymbol(resolvedModuleSymbol);
+ }
+ }
+ return anyType;
+ }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -17740,11 +17981,12 @@ var ts;
return links.resolvedType;
}
function getStringLiteralType(node) {
- if (ts.hasProperty(stringLiteralTypes, node.text)) {
- return stringLiteralTypes[node.text];
+ var text = node.text;
+ if (ts.hasProperty(stringLiteralTypes, text)) {
+ return stringLiteralTypes[text];
}
- var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */);
- type.text = ts.getTextOfNode(node);
+ var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */);
+ type.text = text;
return type;
}
function getTypeFromStringLiteral(node) {
@@ -18265,7 +18507,7 @@ var ts;
return false;
}
function hasExcessProperties(source, target, reportErrors) {
- if (someConstituentTypeHasKind(target, 80896 /* ObjectType */)) {
+ if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && someConstituentTypeHasKind(target, 80896 /* ObjectType */)) {
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
if (!isKnownProperty(target, prop.name)) {
@@ -18358,9 +18600,6 @@ var ts;
return result;
}
function typeParameterIdenticalTo(source, target) {
- if (source.symbol.name !== target.symbol.name) {
- return 0 /* False */;
- }
// covers case when both type parameters does not have constraint (both equal to noConstraintType)
if (source.constraint === target.constraint) {
return -1 /* True */;
@@ -18852,18 +19091,29 @@ var ts;
}
return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
}
+ function isMatchingSignature(source, target, partialMatch) {
+ // A source signature matches a target signature if the two signatures have the same number of required,
+ // optional, and rest parameters.
+ if (source.parameters.length === target.parameters.length &&
+ source.minArgumentCount === target.minArgumentCount &&
+ source.hasRestParameter === target.hasRestParameter) {
+ return true;
+ }
+ // A source signature partially matches a target signature if the target signature has no fewer required
+ // parameters and no more overall parameters than the source signature (where a signature with a rest
+ // parameter is always considered to have more overall parameters than one without).
+ if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter ||
+ source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) {
+ return true;
+ }
+ return false;
+ }
function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) {
if (source === target) {
return -1 /* True */;
}
- if (source.parameters.length !== target.parameters.length ||
- source.minArgumentCount !== target.minArgumentCount ||
- source.hasRestParameter !== target.hasRestParameter) {
- if (!partialMatch ||
- source.parameters.length < target.parameters.length && !source.hasRestParameter ||
- source.minArgumentCount > target.minArgumentCount) {
- return 0 /* False */;
- }
+ if (!(isMatchingSignature(source, target, partialMatch))) {
+ return 0 /* False */;
}
var result = -1 /* True */;
if (source.typeParameters && target.typeParameters) {
@@ -18957,6 +19207,9 @@ var ts;
function isTupleLikeType(type) {
return !!getPropertyOfType(type, "0");
}
+ function isStringLiteralType(type) {
+ return type.flags & 256 /* StringLiteral */;
+ }
/**
* Check if a Type was written as a tuple type literal.
* Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
@@ -19629,7 +19882,7 @@ var ts;
}
function narrowTypeByInstanceof(type, expr, assumeTrue) {
// Check that type is not any, assumed result is true, and we have variable symbol on the left
- if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) {
+ if (isTypeAny(type) || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) {
return type;
}
// Check that right operand is a function type with a prototype property
@@ -19660,6 +19913,12 @@ var ts;
}
}
if (targetType) {
+ if (!assumeTrue) {
+ if (type.flags & 16384 /* Union */) {
+ return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); }));
+ }
+ return type;
+ }
return getNarrowedType(type, targetType);
}
return type;
@@ -20129,6 +20388,9 @@ var ts;
function getIndexTypeOfContextualType(type, kind) {
return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); });
}
+ function contextualTypeIsStringLiteralType(type) {
+ return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type));
+ }
// Return true if the given contextual type is a tuple-like type
function contextualTypeIsTupleLikeType(type) {
return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type));
@@ -20150,7 +20412,7 @@ var ts;
}
function getContextualTypeForObjectLiteralElement(element) {
var objectLiteral = element.parent;
- var type = getContextualType(objectLiteral);
+ var type = getApparentTypeOfContextualType(objectLiteral);
if (type) {
if (!ts.hasDynamicName(element)) {
// For a (non-symbol) computed property, there is no reason to look up the name
@@ -20173,7 +20435,7 @@ var ts;
// type of T.
function getContextualTypeForElementExpression(node) {
var arrayLiteral = node.parent;
- var type = getContextualType(arrayLiteral);
+ var type = getApparentTypeOfContextualType(arrayLiteral);
if (type) {
var index = ts.indexOf(arrayLiteral.elements, node);
return getTypeOfPropertyOfContextualType(type, "" + index)
@@ -20206,11 +20468,28 @@ var ts;
}
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
- function getContextualType(node) {
- var type = getContextualTypeWorker(node);
+ function getApparentTypeOfContextualType(node) {
+ var type = getContextualType(node);
return type && getApparentType(type);
}
- function getContextualTypeWorker(node) {
+ /**
+ * Woah! Do you really want to use this function?
+ *
+ * Unless you're trying to get the *non-apparent* type for a
+ * value-literal type or you're authoring relevant portions of this algorithm,
+ * you probably meant to use 'getApparentTypeOfContextualType'.
+ * Otherwise this may not be very useful.
+ *
+ * In cases where you *are* working on this function, you should understand
+ * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContetxualType'.
+ *
+ * - Use 'getContextualType' when you are simply going to propagate the result to the expression.
+ * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
+ *
+ * @param node the expression whose contextual type will be returned.
+ * @returns the contextual type of an expression.
+ */
+ function getContextualType(node) {
if (isInsideWithStatementBody(node)) {
// We cannot answer semantic questions within a with block, do not proceed any further
return undefined;
@@ -20285,7 +20564,7 @@ var ts;
ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
var type = ts.isObjectLiteralMethod(node)
? getContextualTypeForObjectLiteralMethod(node)
- : getContextualType(node);
+ : getApparentTypeOfContextualType(node);
if (!type) {
return undefined;
}
@@ -20411,7 +20690,7 @@ var ts;
type.pattern = node;
return type;
}
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
var pattern = contextualType.pattern;
// If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
@@ -20494,10 +20773,11 @@ var ts;
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
var propertiesTable = {};
var propertiesArray = [];
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */);
var typeFlags = 0;
+ var patternWithComputedProperties = false;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var memberDecl = _a[_i];
var member = memberDecl.symbol;
@@ -20525,8 +20805,11 @@ var ts;
if (isOptional) {
prop.flags |= 536870912 /* Optional */;
}
+ if (ts.hasDynamicName(memberDecl)) {
+ patternWithComputedProperties = true;
+ }
}
- else if (contextualTypeHasPattern) {
+ else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) {
// If object literal is contextually typed by the implied type of a binding pattern, and if the
// binding pattern specifies a default value for the property, make the property optional.
var impliedProp = getPropertyOfType(contextualType, member.name);
@@ -20578,7 +20861,7 @@ var ts;
var numberIndexType = getIndexType(1 /* Number */);
var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType);
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */;
- result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */);
+ result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0);
if (inDestructuringPattern) {
result.pattern = node;
}
@@ -21289,7 +21572,7 @@ var ts;
// so order how inherited signatures are processed is still preserved.
// interface A { (x: string): void }
// interface B extends A { (x: 'foo'): string }
- // let b: B;
+ // const b: B;
// b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
function reorderCandidates(signatures, result) {
var lastParent;
@@ -22247,6 +22530,10 @@ var ts;
return anyType;
}
}
+ // In JavaScript files, calls to any identifier 'require' are treated as external module imports
+ if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node)) {
+ return resolveExternalModuleTypeByLiteral(node.arguments[0]);
+ }
return getReturnTypeOfSignature(signature);
}
function checkTaggedTemplateExpression(node) {
@@ -22257,7 +22544,10 @@ var ts;
var targetType = getTypeFromTypeNode(node.type);
if (produceDiagnostics && targetType !== unknownType) {
var widenedType = getWidenedType(exprType);
- if (!(isTypeAssignableTo(targetType, widenedType))) {
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ var bothAreStringLike = someConstituentTypeHasKind(targetType, 258 /* StringLike */) &&
+ someConstituentTypeHasKind(widenedType, 258 /* StringLike */);
+ if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) {
checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other);
}
}
@@ -22801,19 +23091,26 @@ var ts;
for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
var p = properties_3[_i];
if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) {
- // TODO(andersh): Computed property support
var name_13 = p.name;
+ if (name_13.kind === 136 /* ComputedPropertyName */) {
+ checkComputedPropertyName(name_13);
+ }
+ if (isComputedNonLiteralName(name_13)) {
+ continue;
+ }
+ var text = getTextOfPropertyName(name_13);
var type = isTypeAny(sourceType)
? sourceType
- : getTypeOfPropertyOfType(sourceType, name_13.text) ||
- isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1 /* Number */) ||
+ : getTypeOfPropertyOfType(sourceType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) ||
getIndexTypeOfType(sourceType, 0 /* String */);
if (type) {
if (p.kind === 246 /* ShorthandPropertyAssignment */) {
checkDestructuringAssignment(p, type);
}
else {
- checkDestructuringAssignment(p.initializer || name_13, type);
+ // non-shorthand property assignments should always have initializers
+ checkDestructuringAssignment(p.initializer, type);
}
}
else {
@@ -23014,6 +23311,10 @@ var ts;
case 31 /* ExclamationEqualsToken */:
case 32 /* EqualsEqualsEqualsToken */:
case 33 /* ExclamationEqualsEqualsToken */:
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ if (someConstituentTypeHasKind(leftType, 258 /* StringLike */) && someConstituentTypeHasKind(rightType, 258 /* StringLike */)) {
+ return booleanType;
+ }
if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) {
reportOperatorError();
}
@@ -23137,6 +23438,13 @@ var ts;
var type2 = checkExpression(node.whenFalse, contextualMapper);
return getUnionType([type1, type2]);
}
+ function checkStringLiteralExpression(node) {
+ var contextualType = getContextualType(node);
+ if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
+ return getStringLiteralType(node);
+ }
+ return stringType;
+ }
function checkTemplateExpression(node) {
// We just want to check each expressions, but we are unconcerned with
// the type of each expression, as any value may be coerced into a string.
@@ -23187,7 +23495,7 @@ var ts;
if (isInferentialContext(contextualMapper)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(contextualType);
if (contextualSignature && !contextualSignature.typeParameters) {
@@ -23251,6 +23559,7 @@ var ts;
case 183 /* TemplateExpression */:
return checkTemplateExpression(node);
case 9 /* StringLiteral */:
+ return checkStringLiteralExpression(node);
case 11 /* NoSubstitutionTemplateLiteral */:
return stringType;
case 10 /* RegularExpressionLiteral */:
@@ -24580,7 +24889,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 248 /* SourceFile */ && ts.isExternalModule(parent)) {
+ if (parent.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -24598,15 +24907,15 @@ var ts;
// A non-initialized declaration is a no-op as the block declaration will resolve before the var
// declaration. the problem is if the declaration has an initializer. this will act as a write to the
// block declared value. this is fine for let, but not const.
- // Only consider declarations with initializers, uninitialized let declarations will not
+ // Only consider declarations with initializers, uninitialized const declarations will not
// step on a let/const variable.
- // Do not consider let and const declarations, as duplicate block-scoped declarations
+ // Do not consider const and const declarations, as duplicate block-scoped declarations
// are handled by the binder.
- // We are only looking for let declarations that step on let\const declarations from a
+ // We are only looking for const declarations that step on let\const declarations from a
// different scope. e.g.:
// {
// const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
- // let x = 0; // symbol for this declaration will be 'symbol'
+ // const x = 0; // symbol for this declaration will be 'symbol'
// }
// skip block-scoped variables and parameters
if ((ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
@@ -24693,6 +25002,12 @@ var ts;
checkExpressionCached(node.initializer);
}
}
+ if (node.kind === 163 /* BindingElement */) {
+ // check computed properties inside property names of binding elements
+ if (node.propertyName && node.propertyName.kind === 136 /* ComputedPropertyName */) {
+ checkComputedPropertyName(node.propertyName);
+ }
+ }
// For a binding pattern, check contained binding elements
if (ts.isBindingPattern(node.name)) {
ts.forEach(node.name.elements, checkSourceElement);
@@ -25176,6 +25491,7 @@ var ts;
var firstDefaultClause;
var hasDuplicateDefaultClause = false;
var expressionType = checkExpression(node.expression);
+ var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258 /* StringLike */);
ts.forEach(node.caseBlock.clauses, function (clause) {
// Grammar check for duplicate default clauses, skip if we already report duplicate default clause
if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) {
@@ -25195,6 +25511,10 @@ var ts;
// TypeScript 1.0 spec (April 2014):5.9
// In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression.
var caseType = checkExpression(caseClause.expression);
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) {
+ return;
+ }
if (!isTypeAssignableTo(expressionType, caseType)) {
// check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined);
@@ -25659,11 +25979,14 @@ var ts;
var enumIsConst = ts.isConst(node);
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.name.kind === 136 /* ComputedPropertyName */) {
+ if (isComputedNonLiteralName(member.name)) {
error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
}
- else if (isNumericLiteralName(member.name.text)) {
- error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ else {
+ var text = getTextOfPropertyName(member.name);
+ if (isNumericLiteralName(text)) {
+ error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ }
}
var previousEnumMemberIsNonConstant = autoValue === undefined;
var initializer = member.initializer;
@@ -26305,8 +26628,8 @@ var ts;
}
// Function and class expression bodies are checked after all statements in the enclosing body. This is
// to ensure constructs like the following are permitted:
- // let foo = function () {
- // let s = foo();
+ // const foo = function () {
+ // const s = foo();
// return "hello";
// }
// Here, performing a full type check of the body of the function expression whilst in the process of
@@ -26421,8 +26744,12 @@ var ts;
if (!(links.flags & 1 /* TypeChecked */)) {
// Check whether the file has declared it is the default lib,
// and whether the user has specifically chosen to avoid checking it.
- if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) {
- return;
+ if (compilerOptions.skipDefaultLibCheck) {
+ // If the user specified '--noLib' and a file has a '/// ',
+ // then we should treat that file as a default lib.
+ if (node.hasNoDefaultLib) {
+ return;
+ }
}
// Grammar checking
checkGrammarSourceFile(node);
@@ -26432,7 +26759,7 @@ var ts;
potentialThisCollisions.length = 0;
ts.forEach(node.statements, checkSourceElement);
checkFunctionAndClassExpressionBodies(node);
- if (ts.isExternalModule(node)) {
+ if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
if (potentialThisCollisions.length) {
@@ -26515,7 +26842,7 @@ var ts;
}
switch (location.kind) {
case 248 /* SourceFile */:
- if (!ts.isExternalModule(location)) {
+ if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
case 218 /* ModuleDeclaration */:
@@ -27153,9 +27480,18 @@ var ts;
getReferencedValueDeclaration: getReferencedValueDeclaration,
getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
isOptionalParameter: isOptionalParameter,
- isArgumentsLocalBinding: isArgumentsLocalBinding
+ isArgumentsLocalBinding: isArgumentsLocalBinding,
+ getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration
};
}
+ function getExternalModuleFileFromDeclaration(declaration) {
+ var specifier = ts.getExternalModuleName(declaration);
+ var moduleSymbol = getSymbolAtLocation(specifier);
+ if (!moduleSymbol) {
+ return undefined;
+ }
+ return ts.getDeclarationOfKind(moduleSymbol, 248 /* SourceFile */);
+ }
function initializeTypeChecker() {
// Bind all source files and propagate errors
ts.forEach(host.getSourceFiles(), function (file) {
@@ -27163,11 +27499,10 @@ var ts;
});
// Initialize global symbol table
ts.forEach(host.getSourceFiles(), function (file) {
- if (!ts.isExternalModule(file)) {
+ if (!ts.isExternalOrCommonJsModule(file)) {
mergeSymbolTable(globals, file.locals);
}
});
- // Initialize special symbols
getSymbolLinks(undefinedSymbol).type = undefinedType;
getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments");
getSymbolLinks(unknownSymbol).type = unknownType;
@@ -27866,7 +28201,7 @@ var ts;
}
}
function checkGrammarForNonSymbolComputedProperty(node, message) {
- if (node.kind === 136 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) {
+ if (ts.isDynamicName(node)) {
return grammarErrorOnNode(node, message);
}
}
@@ -28225,11 +28560,15 @@ var ts;
var writeTextOfNode;
var writer = createAndSetNewTextWriterWithSymbolWriter();
var enclosingDeclaration;
- var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentIdentifiers;
+ var isCurrentFileExternalModule;
var reportedDeclarationError = false;
var errorNameNode;
var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments;
var emit = compilerOptions.stripInternal ? stripInternal : emitNode;
+ var noDeclare = !root;
var moduleElementDeclarationEmitInfo = [];
var asynchronousSubModuleDeclarationEmitInfo;
// Contains the reference paths that needs to go in the declaration file.
@@ -28272,23 +28611,56 @@ var ts;
else {
// Emit references corresponding to this file
var emittedReferencedFiles = [];
+ var prevModuleElementDeclarationEmitInfo = [];
ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ if (!ts.isDeclarationFile(sourceFile)) {
// Check what references need to be added
if (!compilerOptions.noResolve) {
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
- // If the reference file is a declaration file or an external module, emit that reference
- if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) &&
+ // If the reference file is a declaration file, emit that reference
+ if (referencedFile && (ts.isDeclarationFile(referencedFile) &&
!ts.contains(emittedReferencedFiles, referencedFile))) {
writeReferencePath(referencedFile);
emittedReferencedFiles.push(referencedFile);
}
});
}
+ }
+ if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ noDeclare = false;
emitSourceFile(sourceFile);
}
+ else if (ts.isExternalModule(sourceFile)) {
+ noDeclare = true;
+ write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {");
+ writeLine();
+ increaseIndent();
+ emitSourceFile(sourceFile);
+ decreaseIndent();
+ write("}");
+ writeLine();
+ // create asynchronous output for the importDeclarations
+ if (moduleElementDeclarationEmitInfo.length) {
+ var oldWriter = writer;
+ ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) {
+ if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
+ ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */);
+ createAndSetNewTextWriterWithSymbolWriter();
+ ts.Debug.assert(aliasEmitInfo.indent === 1);
+ increaseIndent();
+ writeImportDeclaration(aliasEmitInfo.node);
+ aliasEmitInfo.asynchronousOutput = writer.getText();
+ decreaseIndent();
+ }
+ });
+ setWriter(oldWriter);
+ }
+ prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
+ moduleElementDeclarationEmitInfo = [];
+ }
});
+ moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo);
}
return {
reportedDeclarationError: reportedDeclarationError,
@@ -28297,13 +28669,12 @@ var ts;
referencePathsOutput: referencePathsOutput
};
function hasInternalAnnotation(range) {
- var text = currentSourceFile.text;
- var comment = text.substring(range.pos, range.end);
+ var comment = currentText.substring(range.pos, range.end);
return comment.indexOf("@internal") >= 0;
}
function stripInternal(node) {
if (node) {
- var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos);
if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
return;
}
@@ -28395,7 +28766,7 @@ var ts;
var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
- diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
+ diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
}
else {
diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
@@ -28461,10 +28832,10 @@ var ts;
}
function writeJsDocComments(declaration) {
if (declaration) {
- var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile);
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments);
+ var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
- ts.emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange);
+ ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange);
}
}
function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) {
@@ -28481,7 +28852,7 @@ var ts;
case 103 /* VoidKeyword */:
case 97 /* ThisKeyword */:
case 9 /* StringLiteral */:
- return writeTextOfNode(currentSourceFile, type);
+ return writeTextOfNode(currentText, type);
case 188 /* ExpressionWithTypeArguments */:
return emitExpressionWithTypeArguments(type);
case 151 /* TypeReference */:
@@ -28512,14 +28883,14 @@ var ts;
}
function writeEntityName(entityName) {
if (entityName.kind === 69 /* Identifier */) {
- writeTextOfNode(currentSourceFile, entityName);
+ writeTextOfNode(currentText, entityName);
}
else {
var left = entityName.kind === 135 /* QualifiedName */ ? entityName.left : entityName.expression;
var right = entityName.kind === 135 /* QualifiedName */ ? entityName.right : entityName.name;
writeEntityName(left);
write(".");
- writeTextOfNode(currentSourceFile, right);
+ writeTextOfNode(currentText, right);
}
}
function emitEntityName(entityName) {
@@ -28549,7 +28920,7 @@ var ts;
}
}
function emitTypePredicate(type) {
- writeTextOfNode(currentSourceFile, type.parameterName);
+ writeTextOfNode(currentText, type.parameterName);
write(" is ");
emitType(type.type);
}
@@ -28590,9 +28961,12 @@ var ts;
}
}
function emitSourceFile(node) {
- currentSourceFile = node;
+ currentText = node.text;
+ currentLineMap = ts.getLineStarts(node);
+ currentIdentifiers = node.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(node);
enclosingDeclaration = node;
- ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true /* remove comments */);
+ ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true /* remove comments */);
emitLines(node.statements);
}
// Return a temp variable name to be used in `export default` statements.
@@ -28601,13 +28975,13 @@ var ts;
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName() {
var baseName = "_default";
- if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) {
+ if (!ts.hasProperty(currentIdentifiers, baseName)) {
return baseName;
}
var count = 0;
while (true) {
var name_18 = baseName + "_" + (++count);
- if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) {
+ if (!ts.hasProperty(currentIdentifiers, name_18)) {
return name_18;
}
}
@@ -28615,7 +28989,7 @@ var ts;
function emitExportAssignment(node) {
if (node.expression.kind === 69 /* Identifier */) {
write(node.isExportEquals ? "export = " : "export default ");
- writeTextOfNode(currentSourceFile, node.expression);
+ writeTextOfNode(currentText, node.expression);
}
else {
// Expression
@@ -28653,7 +29027,7 @@ var ts;
writeModuleElement(node);
}
else if (node.kind === 221 /* ImportEqualsDeclaration */ ||
- (node.parent.kind === 248 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) {
+ (node.parent.kind === 248 /* SourceFile */ && isCurrentFileExternalModule)) {
var isVisible;
if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) {
// Import declaration of another module that is visited async so lets put it in right spot
@@ -28707,7 +29081,7 @@ var ts;
}
function emitModuleElementDeclarationFlags(node) {
// If the node is parented in the current source file we need to emit export declare or just export
- if (node.parent === currentSourceFile) {
+ if (node.parent.kind === 248 /* SourceFile */) {
// If the node is exported
if (node.flags & 2 /* Export */) {
write("export ");
@@ -28715,7 +29089,7 @@ var ts;
if (node.flags & 512 /* Default */) {
write("default ");
}
- else if (node.kind !== 215 /* InterfaceDeclaration */) {
+ else if (node.kind !== 215 /* InterfaceDeclaration */ && !noDeclare) {
write("declare ");
}
}
@@ -28742,7 +29116,7 @@ var ts;
write("export ");
}
write("import ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" = ");
if (ts.isInternalModuleImportEqualsDeclaration(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError);
@@ -28750,7 +29124,7 @@ var ts;
}
else {
write("require(");
- writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node));
+ writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node));
write(");");
}
writer.writeLine();
@@ -28785,7 +29159,7 @@ var ts;
if (node.importClause) {
var currentWriterPos = writer.getTextPos();
if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) {
- writeTextOfNode(currentSourceFile, node.importClause.name);
+ writeTextOfNode(currentText, node.importClause.name);
}
if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) {
if (currentWriterPos !== writer.getTextPos()) {
@@ -28794,7 +29168,7 @@ var ts;
}
if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) {
write("* as ");
- writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name);
+ writeTextOfNode(currentText, node.importClause.namedBindings.name);
}
else {
write("{ ");
@@ -28804,16 +29178,28 @@ var ts;
}
write(" from ");
}
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
write(";");
writer.writeLine();
}
+ function emitExternalModuleSpecifier(moduleSpecifier) {
+ if (moduleSpecifier.kind === 9 /* StringLiteral */ && (!root) && (compilerOptions.out || compilerOptions.outFile)) {
+ var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent);
+ if (moduleName) {
+ write("\"");
+ write(moduleName);
+ write("\"");
+ return;
+ }
+ }
+ writeTextOfNode(currentText, moduleSpecifier);
+ }
function emitImportOrExportSpecifier(node) {
if (node.propertyName) {
- writeTextOfNode(currentSourceFile, node.propertyName);
+ writeTextOfNode(currentText, node.propertyName);
write(" as ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
function emitExportSpecifier(node) {
emitImportOrExportSpecifier(node);
@@ -28835,7 +29221,7 @@ var ts;
}
if (node.moduleSpecifier) {
write(" from ");
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
}
write(";");
writer.writeLine();
@@ -28849,11 +29235,11 @@ var ts;
else {
write("module ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
while (node.body.kind !== 219 /* ModuleBlock */) {
node = node.body;
write(".");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
@@ -28872,7 +29258,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
@@ -28894,7 +29280,7 @@ var ts;
write("const ");
}
write("enum ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" {");
writeLine();
increaseIndent();
@@ -28905,7 +29291,7 @@ var ts;
}
function emitEnumMemberDeclaration(node) {
emitJsDocComments(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
@@ -28922,7 +29308,7 @@ var ts;
increaseIndent();
emitJsDocComments(node);
decreaseIndent();
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
// If there is constraint present and this is not a type parameter of the private method emit the constraint
if (node.constraint && !isPrivateMethodTypeParameter(node)) {
write(" extends ");
@@ -29037,7 +29423,7 @@ var ts;
write("abstract ");
}
write("class ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -29060,7 +29446,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("interface ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -29095,7 +29481,7 @@ var ts;
// If this node is a computed name, it can only be a symbol, because we've already skipped
// it if it's not a well known symbol. In that case, the text of the name will be exactly
// what we want, namely the name expression enclosed in brackets.
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
// If optional property emit ?
if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && ts.hasQuestionToken(node)) {
write("?");
@@ -29177,7 +29563,7 @@ var ts;
emitBindingPattern(bindingElement.name);
}
else {
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError);
}
}
@@ -29221,7 +29607,7 @@ var ts;
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (!(node.flags & 16 /* Private */)) {
accessorWithTypeAnnotation = node;
var type = getTypeAnnotationFromAccessor(node);
@@ -29307,13 +29693,13 @@ var ts;
}
if (node.kind === 213 /* FunctionDeclaration */) {
write("function ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
else if (node.kind === 144 /* Constructor */) {
write("constructor");
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (ts.hasQuestionToken(node)) {
write("?");
}
@@ -29437,7 +29823,7 @@ var ts;
emitBindingPattern(node.name);
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
if (resolver.isOptionalParameter(node)) {
write("?");
@@ -29552,7 +29938,7 @@ var ts;
// Example:
// original: function foo({y: [a,b,c]}) {}
// emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void;
- writeTextOfNode(currentSourceFile, bindingElement.propertyName);
+ writeTextOfNode(currentText, bindingElement.propertyName);
write(": ");
}
if (bindingElement.name) {
@@ -29575,7 +29961,7 @@ var ts;
if (bindingElement.dotDotDotToken) {
write("...");
}
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
}
}
}
@@ -29667,6 +30053,18 @@ var ts;
return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile);
}
ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile;
+ function getResolvedExternalModuleName(host, file) {
+ return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName);
+ }
+ ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
+ function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
+ var file = resolver.getExternalModuleFileFromDeclaration(declaration);
+ if (!file || ts.isDeclarationFile(file)) {
+ return undefined;
+ }
+ return getResolvedExternalModuleName(host, file);
+ }
+ ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
var Jump;
(function (Jump) {
Jump[Jump["Break"] = 2] = "Break";
@@ -29954,15 +30352,19 @@ var ts;
var newLine = host.getNewLine();
var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */;
var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); };
+ var outFile = compilerOptions.outFile || compilerOptions.out;
+ var emitJavaScript = createFileEmitter();
if (targetSourceFile === undefined) {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
- var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
- emitFile(jsFilePath, sourceFile);
- }
- });
- if (compilerOptions.outFile || compilerOptions.out) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ if (outFile) {
+ emitFile(outFile);
+ }
+ else {
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
+ var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
+ emitFile(jsFilePath, sourceFile);
+ }
+ });
}
}
else {
@@ -29971,8 +30373,8 @@ var ts;
var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
- else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ else if (!ts.isDeclarationFile(targetSourceFile) && outFile) {
+ emitFile(outFile);
}
}
// Sort and make the unique list of diagnostics
@@ -30024,10 +30426,16 @@ var ts;
}
}
}
- function emitJavaScript(jsFilePath, root) {
+ function createFileEmitter() {
var writer = ts.createTextWriter(newLine);
var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;
var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentFileIdentifiers;
+ var renamedDependencies;
+ var isEs6Module;
+ var isCurrentFileExternalModule;
// name of an exporter function if file is a System external module
// System.register([...], function () {...})
// exporting in System modules looks like:
@@ -30035,15 +30443,15 @@ var ts;
// =>
// var x;... exporter("x", x = 1)
var exportFunctionForFile;
- var generatedNameSet = {};
- var nodeToGeneratedName = [];
+ var generatedNameSet;
+ var nodeToGeneratedName;
var computedPropertyNamesToGeneratedNames;
var convertedLoopState;
- var extendsEmitted = false;
- var decorateEmitted = false;
- var paramEmitted = false;
- var awaiterEmitted = false;
- var tempFlags = 0;
+ var extendsEmitted;
+ var decorateEmitted;
+ var paramEmitted;
+ var awaiterEmitted;
+ var tempFlags;
var tempVariables;
var tempParameters;
var externalImports;
@@ -30075,6 +30483,8 @@ var ts;
var scopeEmitEnd = function () { };
/** Sourcemap data that will get encoded */
var sourceMapData;
+ /** The root file passed to the emit function (if present) */
+ var root;
/** If removeComments is true, no leading-comments needed to be emitted **/
var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker;
var moduleEmitDelegates = (_a = {},
@@ -30085,31 +30495,77 @@ var ts;
_a[1 /* CommonJS */] = emitCommonJSModule,
_a
);
- if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
- initializeEmitterWithSourceMaps();
- }
- if (root) {
- // Do not call emit directly. It does not set the currentSourceFile.
- emitSourceFile(root);
- }
- else {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!isExternalModuleOrDeclarationFile(sourceFile)) {
- emitSourceFile(sourceFile);
+ var bundleEmitDelegates = (_b = {},
+ _b[5 /* ES6 */] = function () { },
+ _b[2 /* AMD */] = emitAMDModule,
+ _b[4 /* System */] = emitSystemModule,
+ _b[3 /* UMD */] = function () { },
+ _b[1 /* CommonJS */] = function () { },
+ _b
+ );
+ return doEmit;
+ function doEmit(jsFilePath, rootFile) {
+ // reset the state
+ writer.reset();
+ currentSourceFile = undefined;
+ currentText = undefined;
+ currentLineMap = undefined;
+ exportFunctionForFile = undefined;
+ generatedNameSet = {};
+ nodeToGeneratedName = [];
+ computedPropertyNamesToGeneratedNames = undefined;
+ convertedLoopState = undefined;
+ extendsEmitted = false;
+ decorateEmitted = false;
+ paramEmitted = false;
+ awaiterEmitted = false;
+ tempFlags = 0;
+ tempVariables = undefined;
+ tempParameters = undefined;
+ externalImports = undefined;
+ exportSpecifiers = undefined;
+ exportEquals = undefined;
+ hasExportStars = undefined;
+ detachedCommentsInfo = undefined;
+ sourceMapData = undefined;
+ isEs6Module = false;
+ renamedDependencies = undefined;
+ isCurrentFileExternalModule = false;
+ root = rootFile;
+ if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
+ initializeEmitterWithSourceMaps(jsFilePath, root);
+ }
+ if (root) {
+ // Do not call emit directly. It does not set the currentSourceFile.
+ emitSourceFile(root);
+ }
+ else {
+ if (modulekind) {
+ ts.forEach(host.getSourceFiles(), emitEmitHelpers);
}
- });
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) {
+ emitSourceFile(sourceFile);
+ }
+ });
+ }
+ writeLine();
+ writeEmittedFiles(writer.getText(), jsFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM);
}
- writeLine();
- writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);
- return;
function emitSourceFile(sourceFile) {
currentSourceFile = sourceFile;
+ currentText = sourceFile.text;
+ currentLineMap = ts.getLineStarts(sourceFile);
exportFunctionForFile = undefined;
+ isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"];
+ renamedDependencies = sourceFile.renamedDependencies;
+ currentFileIdentifiers = sourceFile.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(sourceFile);
emit(sourceFile);
}
function isUniqueName(name) {
return !resolver.hasGlobalName(name) &&
- !ts.hasProperty(currentSourceFile.identifiers, name) &&
+ !ts.hasProperty(currentFileIdentifiers, name) &&
!ts.hasProperty(generatedNameSet, name);
}
// Return the next available name in the pattern _a ... _z, _0, _1, ...
@@ -30192,7 +30648,7 @@ var ts;
var id = ts.getNodeId(node);
return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node)));
}
- function initializeEmitterWithSourceMaps() {
+ function initializeEmitterWithSourceMaps(jsFilePath, root) {
var sourceMapDir; // The directory in which sourcemap will be
// Current source map file and its index in the sources list
var sourceMapSourceIndex = -1;
@@ -30280,7 +30736,7 @@ var ts;
}
}
function recordSourceMapSpan(pos) {
- var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos);
+ var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos);
// Convert the location to be one-based.
sourceLinePos.line++;
sourceLinePos.character++;
@@ -30314,13 +30770,13 @@ var ts;
}
function recordEmitNodeStartSpan(node) {
// Get the token pos after skipping to the token (ignoring the leading trivia)
- recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos));
+ recordSourceMapSpan(ts.skipTrivia(currentText, node.pos));
}
function recordEmitNodeEndSpan(node) {
recordSourceMapSpan(node.end);
}
function writeTextWithSpanRecord(tokenKind, startPos, emitFn) {
- var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);
+ var tokenStartPos = ts.skipTrivia(currentText, startPos);
recordSourceMapSpan(tokenStartPos);
var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);
recordSourceMapSpan(tokenEndPos);
@@ -30402,9 +30858,9 @@ var ts;
sourceMapNameIndices.pop();
}
;
- function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) {
+ function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) {
recordSourceMapSpan(comment.pos);
- ts.writeCommentRange(currentSourceFile, writer, comment, newLine);
+ ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine);
recordSourceMapSpan(comment.end);
}
function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) {
@@ -30434,7 +30890,7 @@ var ts;
return output;
}
}
- function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) {
encodeLastRecordedSourceMapSpan();
var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent);
sourceMapDataList.push(sourceMapData);
@@ -30450,7 +30906,7 @@ var ts;
sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL;
}
// Write sourcemap url to the js file and write the js file
- writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);
+ writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark);
}
// Initialize source map data
var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath));
@@ -30522,7 +30978,7 @@ var ts;
scopeEmitEnd = recordScopeNameEnd;
writeComment = writeCommentRangeWithMap;
}
- function writeJavaScriptFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) {
ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
// Create a temporary variable with a unique unused name.
@@ -30702,7 +31158,7 @@ var ts;
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (node.parent) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ return ts.getTextOfNodeFromSourceText(currentText, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
@@ -30729,7 +31185,7 @@ var ts;
// Find original source text, since we need to emit the raw strings of the tagged template.
// The raw strings contain the (escaped) strings of what the user wrote.
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node);
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
// thus we need to remove those characters.
// First template piece starts with "`", others with "}"
@@ -31146,7 +31602,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
write("\"");
}
@@ -31246,7 +31702,7 @@ var ts;
// Identifier references named import
write(getGeneratedNameForNode(declaration.parent.parent.parent));
var name_23 = declaration.propertyName || declaration.name;
- var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23);
+ var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23);
if (languageVersion === 0 /* ES3 */ && identifier === "default") {
write("[\"default\"]");
}
@@ -31270,7 +31726,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function isNameOfNestedRedeclaration(node) {
@@ -31308,7 +31764,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function emitThis(node) {
@@ -31712,7 +32168,7 @@ var ts;
function emitShorthandPropertyAssignment(node) {
// The name property of a short-hand property assignment is considered an expression position, so here
// we manually emit the identifier to avoid rewriting.
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
// If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier,
// we emit a normal property assignment. For example:
// module m {
@@ -31722,7 +32178,7 @@ var ts;
// let obj = { y };
// }
// Here we need to emit obj = { y : m.y } regardless of the output target.
- if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) {
+ if (modulekind !== 5 /* ES6 */ || isNamespaceExportReference(node.name)) {
// Emit identifier as an identifier
write(": ");
emit(node.name);
@@ -31779,11 +32235,11 @@ var ts;
var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
// 1 .toString is a valid property access, emit a space after the literal
// Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal
- var shouldEmitSpace;
+ var shouldEmitSpace = false;
if (!indentedBeforeDot) {
if (node.expression.kind === 8 /* NumericLiteral */) {
// check if numeric literal was originally written with a dot
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node.expression);
shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0;
}
else {
@@ -32962,16 +33418,16 @@ var ts;
emitToken(16 /* CloseBraceToken */, node.clauses.end);
}
function nodeStartPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function nodeEndPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, node2.end);
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end);
}
function nodeEndIsOnSameLineAsNodeStart(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function emitCaseOrDefaultClause(node) {
if (node.kind === 241 /* CaseClause */) {
@@ -33077,7 +33533,7 @@ var ts;
ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */);
// only allow export default at a source file level
if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) {
- if (!currentSourceFile.symbol.exports["___esModule"]) {
+ if (!isEs6Module) {
if (languageVersion === 1 /* ES5 */) {
// default value of configurable, enumerable, writable are `false`.
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
@@ -33272,14 +33728,20 @@ var ts;
return node;
}
function createPropertyAccessForDestructuringProperty(object, propName) {
- // We create a synthetic copy of the identifier in order to avoid the rewriting that might
- // otherwise occur when the identifier is emitted.
- var syntheticName = ts.createSynthesizedNode(propName.kind);
- syntheticName.text = propName.text;
- if (syntheticName.kind !== 69 /* Identifier */) {
- return createElementAccessExpression(object, syntheticName);
+ var index;
+ var nameIsComputed = propName.kind === 136 /* ComputedPropertyName */;
+ if (nameIsComputed) {
+ index = ensureIdentifier(propName.expression, /* reuseIdentifierExpression */ false);
}
- return createPropertyAccessExpression(object, syntheticName);
+ else {
+ // We create a synthetic copy of the identifier in order to avoid the rewriting that might
+ // otherwise occur when the identifier is emitted.
+ index = ts.createSynthesizedNode(propName.kind);
+ index.text = propName.text;
+ }
+ return !nameIsComputed && index.kind === 69 /* Identifier */
+ ? createPropertyAccessExpression(object, index)
+ : createElementAccessExpression(object, index);
}
function createSliceCall(value, sliceIndex) {
var call = ts.createSynthesizedNode(168 /* CallExpression */);
@@ -33742,7 +34204,6 @@ var ts;
var promiseConstructor = ts.getEntityNameFromTypeNode(node.type);
var isArrowFunction = node.kind === 174 /* ArrowFunction */;
var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0;
- var args;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
@@ -35197,8 +35658,8 @@ var ts;
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName) {
- if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
- return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\"";
+ if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) {
+ return "\"" + renamedDependencies[moduleName.text] + "\"";
}
return undefined;
}
@@ -35351,7 +35812,7 @@ var ts;
// - current file is not external module
// - import declaration is top level and target is value imported by entity name
if (resolver.isReferencedAliasDeclaration(node) ||
- (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
+ (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
emitLeadingComments(node);
emitStart(node);
// variable declaration for import-equals declaration can be hoisted in system modules
@@ -35579,7 +36040,7 @@ var ts;
function getLocalNameForExternalImport(node) {
var namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);
+ return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name);
}
if (node.kind === 222 /* ImportDeclaration */ && node.importClause) {
return getGeneratedNameForNode(node);
@@ -35884,7 +36345,7 @@ var ts;
ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */;
}
function isCurrentFileSystemExternalModule() {
- return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile);
+ return modulekind === 4 /* System */ && isCurrentFileExternalModule;
}
function emitSystemModuleBody(node, dependencyGroups, startIndex) {
// shape of the body in system modules:
@@ -36054,7 +36515,13 @@ var ts;
writeLine();
write("}"); // execute
}
- function emitSystemModule(node) {
+ function writeModuleName(node, emitRelativePathAsModuleName) {
+ var moduleName = node.moduleName;
+ if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) {
+ write("\"" + moduleName + "\", ");
+ }
+ }
+ function emitSystemModule(node, emitRelativePathAsModuleName) {
collectExternalModuleInfo(node);
// System modules has the following shape
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
@@ -36069,9 +36536,7 @@ var ts;
exportFunctionForFile = makeUniqueName("exports");
writeLine();
write("System.register(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
+ writeModuleName(node, emitRelativePathAsModuleName);
write("[");
var groupIndices = {};
var dependencyGroups = [];
@@ -36090,6 +36555,12 @@ var ts;
if (i !== 0) {
write(", ");
}
+ if (emitRelativePathAsModuleName) {
+ var name_29 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
+ if (name_29) {
+ text = "\"" + name_29 + "\"";
+ }
+ }
write(text);
}
write("], function(" + exportFunctionForFile + ") {");
@@ -36103,7 +36574,7 @@ var ts;
writeLine();
write("});");
}
- function getAMDDependencyNames(node, includeNonAmdDependencies) {
+ function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
// names of modules with corresponding parameter in the factory function
var aliasedModuleNames = [];
// names of modules with no corresponding parameters in factory function
@@ -36126,6 +36597,12 @@ var ts;
var importNode = externalImports_4[_c];
// Find the name of the external module
var externalModuleName = getExternalModuleNameText(importNode);
+ if (emitRelativePathAsModuleName) {
+ var name_30 = getExternalModuleNameFromDeclaration(host, resolver, importNode);
+ if (name_30) {
+ externalModuleName = "\"" + name_30 + "\"";
+ }
+ }
// Find the name of the module alias, if there is one
var importAliasName = getLocalNameForExternalImport(importNode);
if (includeNonAmdDependencies && importAliasName) {
@@ -36138,7 +36615,7 @@ var ts;
}
return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
}
- function emitAMDDependencies(node, includeNonAmdDependencies) {
+ function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
// An AMD define function has the following shape:
// define(id?, dependencies?, factory);
//
@@ -36150,7 +36627,7 @@ var ts;
// To ensure this is true in cases of modules with no aliases, e.g.:
// `import "module"` or ``
// we need to add modules without alias names to the end of the dependencies list
- var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);
+ var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName);
emitAMDDependencyList(dependencyNames);
write(", ");
emitAMDFactoryHeader(dependencyNames);
@@ -36177,15 +36654,13 @@ var ts;
}
write(") {");
}
- function emitAMDModule(node) {
+ function emitAMDModule(node, emitRelativePathAsModuleName) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
write("define(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
- emitAMDDependencies(node, /*includeNonAmdDependencies*/ true);
+ writeModuleName(node, emitRelativePathAsModuleName);
+ emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName);
increaseIndent();
var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
emitExportStarHelper();
@@ -36404,8 +36879,13 @@ var ts;
emitShebang();
emitDetachedCommentsAndUpdateCommentsInfo(node);
if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
- var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */];
- emitModule(node);
+ if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) {
+ var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */];
+ emitModule(node);
+ }
+ else {
+ bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true);
+ }
}
else {
// emit prologue directives prior to __extends
@@ -36666,7 +37146,7 @@ var ts;
}
function getLeadingCommentsWithoutDetachedComments() {
// get the leading comments from detachedPos
- var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
+ var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@@ -36683,10 +37163,10 @@ var ts;
function isTripleSlashComment(comment) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ &&
+ if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ &&
comment.pos + 2 < comment.end &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) {
- var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);
+ currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) {
+ var textSubStr = currentText.substring(comment.pos, comment.end);
return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?
true : false;
@@ -36703,7 +37183,7 @@ var ts;
}
else {
// get the leading comments from the node
- return ts.getLeadingCommentRangesOfNode(node, currentSourceFile);
+ return ts.getLeadingCommentRangesOfNodeFromText(node, currentText);
}
}
}
@@ -36712,7 +37192,7 @@ var ts;
// Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments
if (node.parent) {
if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) {
- return ts.getTrailingCommentRanges(currentSourceFile.text, node.end);
+ return ts.getTrailingCommentRanges(currentText, node.end);
}
}
}
@@ -36746,9 +37226,9 @@ var ts;
leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment);
}
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
- ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
}
function emitTrailingComments(node) {
if (compilerOptions.removeComments) {
@@ -36757,7 +37237,7 @@ var ts;
// Emit the trailing comments only if the parent's end doesn't match
var trailingComments = getTrailingCommentsToEmit(node);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
- ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
}
/**
* Emit trailing comments at the position. The term trailing comment is used here to describe following comment:
@@ -36768,9 +37248,9 @@ var ts;
if (compilerOptions.removeComments) {
return;
}
- var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos);
+ var trailingComments = ts.getTrailingCommentRanges(currentText, pos);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
- ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitLeadingCommentsOfPositionWorker(pos) {
if (compilerOptions.removeComments) {
@@ -36783,14 +37263,14 @@ var ts;
}
else {
// get the leading comments from the node
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos);
+ leadingComments = ts.getLeadingCommentRanges(currentText, pos);
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
- ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitDetachedCommentsAndUpdateCommentsInfo(node) {
- var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments);
+ var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments);
if (currentDetachedCommentInfo) {
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
@@ -36801,12 +37281,12 @@ var ts;
}
}
function emitShebang() {
- var shebang = ts.getShebang(currentSourceFile.text);
+ var shebang = ts.getShebang(currentText);
if (shebang) {
write(shebang);
}
}
- var _a;
+ var _a, _b;
}
function emitFile(jsFilePath, sourceFile) {
emitJavaScript(jsFilePath, sourceFile);
@@ -36866,11 +37346,11 @@ var ts;
if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
var failedLookupLocations = [];
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations };
}
- resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
@@ -36880,8 +37360,8 @@ var ts;
}
}
ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function loadNodeModuleFromFile(candidate, failedLookupLocation, host) {
- return ts.forEach(ts.moduleFileExtensions, tryLoad);
+ function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) {
+ return ts.forEach(extensions, tryLoad);
function tryLoad(ext) {
var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (host.fileExists(fileName)) {
@@ -36893,7 +37373,7 @@ var ts;
}
}
}
- function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) {
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) {
var packageJsonPath = ts.combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
var jsonContent;
@@ -36906,7 +37386,7 @@ var ts;
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
- var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
+ var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
if (result) {
return result;
}
@@ -36916,7 +37396,7 @@ var ts;
// 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(ts.combinePaths(candidate, "index"), failedLookupLocation, host);
+ return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName, directory, host) {
var failedLookupLocations = [];
@@ -36926,11 +37406,11 @@ var ts;
if (baseName !== "node_modules") {
var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
- result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
@@ -36956,9 +37436,10 @@ var ts;
var searchName;
var failedLookupLocations = [];
var referencedSourceFile;
+ var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions;
while (true) {
searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName));
- referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) {
+ referencedSourceFile = ts.forEach(extensions, function (extension) {
if (extension === ".tsx" && !compilerOptions.jsx) {
// resolve .tsx files only if jsx support is enabled
// 'logical not' handles both undefined and None cases
@@ -36989,10 +37470,8 @@ var ts;
/* @internal */
ts.defaultInitCompilerOptions = {
module: 1 /* CommonJS */,
- target: 0 /* ES3 */,
+ target: 1 /* ES5 */,
noImplicitAny: false,
- outDir: "built",
- rootDir: ".",
sourceMap: false
};
function createCompilerHost(options, setParentNodes) {
@@ -37397,43 +37876,55 @@ var ts;
if (file.imports) {
return;
}
+ var isJavaScriptFile = ts.isSourceFileJavaScript(file);
var imports;
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var node = _a[_i];
- collect(node, /* allowRelativeModuleNames */ true);
+ collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false);
}
file.imports = imports || emptyArray;
- function collect(node, allowRelativeModuleNames) {
- switch (node.kind) {
- case 222 /* ImportDeclaration */:
- case 221 /* ImportEqualsDeclaration */:
- case 228 /* ExportDeclaration */:
- var moduleNameExpr = ts.getExternalModuleName(node);
- if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
+ return;
+ function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
+ if (!collectOnlyRequireCalls) {
+ switch (node.kind) {
+ case 222 /* ImportDeclaration */:
+ case 221 /* ImportEqualsDeclaration */:
+ case 228 /* ExportDeclaration */:
+ var moduleNameExpr = ts.getExternalModuleName(node);
+ if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
+ break;
+ }
+ if (!moduleNameExpr.text) {
+ break;
+ }
+ if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
+ (imports || (imports = [])).push(moduleNameExpr);
+ }
break;
- }
- if (!moduleNameExpr.text) {
- break;
- }
- if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
- (imports || (imports = [])).push(moduleNameExpr);
- }
- break;
- case 218 /* ModuleDeclaration */:
- if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
- // TypeScript 1.0 spec (April 2014): 12.1.6
- // 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
- ts.forEachChild(node.body, function (node) {
+ case 218 /* ModuleDeclaration */:
+ if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
- // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
- // only through top - level external module names. Relative external module names are not permitted.
- collect(node, /* allowRelativeModuleNames */ false);
- });
- }
- break;
+ // 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
+ ts.forEachChild(node.body, function (node) {
+ // TypeScript 1.0 spec (April 2014): 12.1.6
+ // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
+ // only through top - level external module names. Relative external module names are not permitted.
+ collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls);
+ });
+ }
+ break;
+ }
+ }
+ if (isJavaScriptFile) {
+ if (ts.isRequireCall(node)) {
+ (imports || (imports = [])).push(node.arguments[0]);
+ }
+ else {
+ ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); });
+ }
}
}
}
@@ -37526,7 +38017,6 @@ var ts;
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
- file.isDefaultLib = true;
files.unshift(file);
}
else {
@@ -37604,6 +38094,9 @@ var ts;
commonPathComponents.length = sourcePathComponents.length;
}
});
+ if (!commonPathComponents) {
+ return currentDirectory;
+ }
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
@@ -37689,12 +38182,15 @@ var ts;
if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
+ // Cannot specify module gen that isn't amd or system with --out
+ if (outFile && options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
+ }
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir ||
options.sourceRoot ||
- (options.mapRoot &&
- (!outFile || firstExternalModuleSourceFile !== undefined))) {
+ options.mapRoot) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -38212,20 +38708,20 @@ var ts;
var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (var i = 0; i < sysFiles.length; i++) {
- var name_29 = sysFiles[i];
- if (ts.fileExtensionIs(name_29, ".d.ts")) {
- var baseName = name_29.substr(0, name_29.length - ".d.ts".length);
+ var name_31 = sysFiles[i];
+ if (ts.fileExtensionIs(name_31, ".d.ts")) {
+ var baseName = name_31.substr(0, name_31.length - ".d.ts".length);
if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) {
- fileNames.push(name_29);
+ fileNames.push(name_31);
}
}
- else if (ts.fileExtensionIs(name_29, ".ts")) {
- if (!ts.contains(sysFiles, name_29 + "x")) {
- fileNames.push(name_29);
+ else if (ts.fileExtensionIs(name_31, ".ts")) {
+ if (!ts.contains(sysFiles, name_31 + "x")) {
+ fileNames.push(name_31);
}
}
else {
- fileNames.push(name_29);
+ fileNames.push(name_31);
}
}
}
@@ -38453,12 +38949,12 @@ var ts;
ts.forEach(program.getSourceFiles(), function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
var nameToDeclarations = sourceFile.getNamedDeclarations();
- for (var name_30 in nameToDeclarations) {
- var declarations = ts.getProperty(nameToDeclarations, name_30);
+ for (var name_32 in nameToDeclarations) {
+ var declarations = ts.getProperty(nameToDeclarations, name_32);
if (declarations) {
// First do a quick check to see if the name of the declaration matches the
// last portion of the (possibly) dotted name they're searching for.
- var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_30);
+ var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_32);
if (!matches) {
continue;
}
@@ -38471,14 +38967,14 @@ var ts;
if (!containers) {
return undefined;
}
- matches = patternMatcher.getMatches(containers, name_30);
+ matches = patternMatcher.getMatches(containers, name_32);
if (!matches) {
continue;
}
}
var fileName = sourceFile.fileName;
var matchKind = bestMatchKind(matches);
- rawItems.push({ name: name_30, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
+ rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
}
}
}
@@ -38859,9 +39355,9 @@ var ts;
case 211 /* VariableDeclaration */:
case 163 /* BindingElement */:
var variableDeclarationNode;
- var name_31;
+ var name_33;
if (node.kind === 163 /* BindingElement */) {
- name_31 = node.name;
+ name_33 = node.name;
variableDeclarationNode = node;
// binding elements are added only for variable declarations
// bubble up to the containing variable declaration
@@ -38873,16 +39369,16 @@ var ts;
else {
ts.Debug.assert(!ts.isBindingPattern(node.name));
variableDeclarationNode = node;
- name_31 = node.name;
+ name_33 = node.name;
}
if (ts.isConst(variableDeclarationNode)) {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.constElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement);
}
else if (ts.isLet(variableDeclarationNode)) {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.letElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement);
}
else {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.variableElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement);
}
case 144 /* Constructor */:
return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement);
@@ -39802,7 +40298,7 @@ var ts;
if (!candidates.length) {
// We didn't have any sig help items produced by the TS compiler. If this is a JS
// file, then see if we can figure out anything better.
- if (ts.isJavaScript(sourceFile.fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
return createJavaScriptSignatureHelpItems(argumentInfo);
}
return undefined;
@@ -41662,9 +42158,9 @@ var ts;
}
Rules.prototype.getRuleName = function (rule) {
var o = this;
- for (var name_32 in o) {
- if (o[name_32] === rule) {
- return name_32;
+ for (var name_34 in o) {
+ if (o[name_34] === rule) {
+ return name_34;
}
}
throw new Error("Unknown rule");
@@ -42096,7 +42592,7 @@ var ts;
function TokenRangeAccess(from, to, except) {
this.tokens = [];
for (var token = from; token <= to; token++) {
- if (except.indexOf(token) < 0) {
+ if (ts.indexOf(except, token) < 0) {
this.tokens.push(token);
}
}
@@ -43709,13 +44205,18 @@ var ts;
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
- var node = new (ts.getNodeConstructor(kind))(pos, end);
+ var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
- function NodeObject() {
+ function NodeObject(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0 /* None */;
+ this.parent = undefined;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -44198,8 +44699,8 @@ var ts;
})();
var SourceFileObject = (function (_super) {
__extends(SourceFileObject, _super);
- function SourceFileObject() {
- _super.apply(this, arguments);
+ function SourceFileObject(kind, pos, end) {
+ _super.call(this, kind, pos, end);
}
SourceFileObject.prototype.update = function (newText, textChangeRange) {
return ts.updateSourceFile(this, newText, textChangeRange);
@@ -44521,6 +45022,9 @@ var ts;
ClassificationTypeNames.typeAliasName = "type alias name";
ClassificationTypeNames.parameterName = "parameter name";
ClassificationTypeNames.docCommentTagName = "doc comment tag name";
+ ClassificationTypeNames.jsxOpenTagName = "jsx open tag name";
+ ClassificationTypeNames.jsxCloseTagName = "jsx close tag name";
+ ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name";
return ClassificationTypeNames;
})();
ts.ClassificationTypeNames = ClassificationTypeNames;
@@ -44543,6 +45047,9 @@ var ts;
ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName";
ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName";
ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName";
+ ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName";
+ ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName";
+ ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
})(ts.ClassificationType || (ts.ClassificationType = {}));
var ClassificationType = ts.ClassificationType;
function displayPartsToString(displayParts) {
@@ -44922,8 +45429,9 @@ var ts;
};
}
ts.createDocumentRegistry = createDocumentRegistry;
- function preProcessFile(sourceText, readImportFiles) {
+ function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
+ if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
var referencedFiles = [];
var importedFiles = [];
var ambientExternalModules;
@@ -44957,9 +45465,207 @@ var ts;
end: pos + importPath.length
});
}
- function processImport() {
+ /**
+ * Returns true if at least one token was consumed from the stream
+ */
+ function tryConsumeDeclare() {
+ var token = scanner.getToken();
+ if (token === 122 /* DeclareKeyword */) {
+ // declare module "mod"
+ token = scanner.scan();
+ if (token === 125 /* ModuleKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ recordAmbientExternalModule();
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Returns true if at least one token was consumed from the stream
+ */
+ function tryConsumeImport() {
+ var token = scanner.getToken();
+ if (token === 89 /* ImportKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import "mod";
+ recordModuleName();
+ return true;
+ }
+ else {
+ if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import d from "mod";
+ recordModuleName();
+ return true;
+ }
+ }
+ else if (token === 56 /* EqualsToken */) {
+ if (tryConsumeRequireCall(/* skipCurrentToken */ true)) {
+ return true;
+ }
+ }
+ else if (token === 24 /* CommaToken */) {
+ // consume comma and keep going
+ token = scanner.scan();
+ }
+ else {
+ // unknown syntax
+ return true;
+ }
+ }
+ if (token === 15 /* OpenBraceToken */) {
+ token = scanner.scan();
+ // consume "{ a as B, c, d as D}" clauses
+ // make sure that it stops on EOF
+ while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
+ token = scanner.scan();
+ }
+ if (token === 16 /* CloseBraceToken */) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import {a as A} from "mod";
+ // import d, {a, b as B} from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ }
+ else if (token === 37 /* AsteriskToken */) {
+ token = scanner.scan();
+ if (token === 116 /* AsKeyword */) {
+ token = scanner.scan();
+ if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import * as NS from "mod"
+ // import d, * as NS from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeExport() {
+ var token = scanner.getToken();
+ if (token === 82 /* ExportKeyword */) {
+ token = scanner.scan();
+ if (token === 15 /* OpenBraceToken */) {
+ token = scanner.scan();
+ // consume "{ a as B, c, d as D}" clauses
+ // make sure it stops on EOF
+ while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
+ token = scanner.scan();
+ }
+ if (token === 16 /* CloseBraceToken */) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // export {a as A} from "mod";
+ // export {a, b as B} from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ }
+ else if (token === 37 /* AsteriskToken */) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // export * from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ else if (token === 89 /* ImportKeyword */) {
+ token = scanner.scan();
+ if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 56 /* EqualsToken */) {
+ if (tryConsumeRequireCall(/* skipCurrentToken */ true)) {
+ return true;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeRequireCall(skipCurrentToken) {
+ var token = skipCurrentToken ? scanner.scan() : scanner.getToken();
+ if (token === 127 /* RequireKeyword */) {
+ token = scanner.scan();
+ if (token === 17 /* OpenParenToken */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // require("mod");
+ recordModuleName();
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeDefine() {
+ var token = scanner.getToken();
+ if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") {
+ token = scanner.scan();
+ if (token !== 17 /* OpenParenToken */) {
+ return true;
+ }
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // looks like define ("modname", ... - skip string literal and comma
+ token = scanner.scan();
+ if (token === 24 /* CommaToken */) {
+ token = scanner.scan();
+ }
+ else {
+ // unexpected token
+ return true;
+ }
+ }
+ // should be start of dependency list
+ if (token !== 19 /* OpenBracketToken */) {
+ return true;
+ }
+ // skip open bracket
+ token = scanner.scan();
+ var i = 0;
+ // scan until ']' or EOF
+ while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
+ // record string literals as module names
+ if (token === 9 /* StringLiteral */) {
+ recordModuleName();
+ i++;
+ }
+ token = scanner.scan();
+ }
+ return true;
+ }
+ return false;
+ }
+ function processImports() {
scanner.setText(sourceText);
- var token = scanner.scan();
+ scanner.scan();
// Look for:
// import "mod";
// import d from "mod"
@@ -44971,152 +45677,26 @@ var ts;
// export * from "mod"
// export {a as b} from "mod"
// export import i = require("mod")
- while (token !== 1 /* EndOfFileToken */) {
- if (token === 122 /* DeclareKeyword */) {
- // declare module "mod"
- token = scanner.scan();
- if (token === 125 /* ModuleKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- recordAmbientExternalModule();
- continue;
- }
- }
+ // (for JavaScript files) require("mod")
+ while (true) {
+ if (scanner.getToken() === 1 /* EndOfFileToken */) {
+ break;
}
- else if (token === 89 /* ImportKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import "mod";
- recordModuleName();
- continue;
- }
- else {
- if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import d from "mod";
- recordModuleName();
- continue;
- }
- }
- else if (token === 56 /* EqualsToken */) {
- token = scanner.scan();
- if (token === 127 /* RequireKeyword */) {
- token = scanner.scan();
- if (token === 17 /* OpenParenToken */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import i = require("mod");
- recordModuleName();
- continue;
- }
- }
- }
- }
- else if (token === 24 /* CommaToken */) {
- // consume comma and keep going
- token = scanner.scan();
- }
- else {
- // unknown syntax
- continue;
- }
- }
- if (token === 15 /* OpenBraceToken */) {
- token = scanner.scan();
- // consume "{ a as B, c, d as D}" clauses
- while (token !== 16 /* CloseBraceToken */) {
- token = scanner.scan();
- }
- if (token === 16 /* CloseBraceToken */) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import {a as A} from "mod";
- // import d, {a, b as B} from "mod"
- recordModuleName();
- }
- }
- }
- }
- else if (token === 37 /* AsteriskToken */) {
- token = scanner.scan();
- if (token === 116 /* AsKeyword */) {
- token = scanner.scan();
- if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import * as NS from "mod"
- // import d, * as NS from "mod"
- recordModuleName();
- }
- }
- }
- }
- }
- }
+ // check if at least one of alternative have moved scanner forward
+ if (tryConsumeDeclare() ||
+ tryConsumeImport() ||
+ tryConsumeExport() ||
+ (detectJavaScriptImports && (tryConsumeRequireCall(/* skipCurrentToken */ false) || tryConsumeDefine()))) {
+ continue;
}
- else if (token === 82 /* ExportKeyword */) {
- token = scanner.scan();
- if (token === 15 /* OpenBraceToken */) {
- token = scanner.scan();
- // consume "{ a as B, c, d as D}" clauses
- while (token !== 16 /* CloseBraceToken */) {
- token = scanner.scan();
- }
- if (token === 16 /* CloseBraceToken */) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // export {a as A} from "mod";
- // export {a, b as B} from "mod"
- recordModuleName();
- }
- }
- }
- }
- else if (token === 37 /* AsteriskToken */) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // export * from "mod"
- recordModuleName();
- }
- }
- }
- else if (token === 89 /* ImportKeyword */) {
- token = scanner.scan();
- if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 56 /* EqualsToken */) {
- token = scanner.scan();
- if (token === 127 /* RequireKeyword */) {
- token = scanner.scan();
- if (token === 17 /* OpenParenToken */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // export import i = require("mod");
- recordModuleName();
- }
- }
- }
- }
- }
- }
+ else {
+ scanner.scan();
}
- token = scanner.scan();
}
scanner.setText(undefined);
}
if (readImportFiles) {
- processImport();
+ processImports();
}
processTripleSlashDirectives();
return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules };
@@ -45547,7 +46127,7 @@ var ts;
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(targetSourceFile)) {
return getJavaScriptSemanticDiagnostics(targetSourceFile);
}
// Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
@@ -45759,7 +46339,7 @@ var ts;
var typeChecker = program.getTypeChecker();
var syntacticStart = new Date().getTime();
var sourceFile = getValidSourceFile(fileName);
- var isJavaScriptFile = ts.isJavaScript(fileName);
+ var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile);
var isJsDocTagName = false;
var start = new Date().getTime();
var currentToken = ts.getTokenAtPosition(sourceFile, position);
@@ -46393,8 +46973,8 @@ var ts;
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
- var name_33 = element.propertyName || element.name;
- exisingImportsOrExports[name_33.text] = true;
+ var name_35 = element.propertyName || element.name;
+ exisingImportsOrExports[name_35.text] = true;
}
if (ts.isEmpty(exisingImportsOrExports)) {
return exportsOfModule;
@@ -46426,7 +47006,10 @@ var ts;
}
var existingName = void 0;
if (m.kind === 163 /* BindingElement */ && m.propertyName) {
- existingName = m.propertyName.text;
+ // include only identifiers in completion list
+ if (m.propertyName.kind === 69 /* Identifier */) {
+ existingName = m.propertyName.text;
+ }
}
else {
// TODO(jfreeman): Account for computed property name
@@ -46466,46 +47049,43 @@ var ts;
return undefined;
}
var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName;
- var entries;
if (isJsDocTagName) {
// If the current position is a jsDoc tag name, only tag names should be provided for completion
return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() };
}
- if (isRightOfDot && ts.isJavaScript(fileName)) {
- entries = getCompletionEntriesFromSymbols(symbols);
- ts.addRange(entries, getJavaScriptCompletionEntries());
+ var sourceFile = getValidSourceFile(fileName);
+ var entries = [];
+ if (isRightOfDot && ts.isSourceFileJavaScript(sourceFile)) {
+ var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries);
+ ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, uniqueNames));
}
else {
if (!symbols || symbols.length === 0) {
return undefined;
}
- entries = getCompletionEntriesFromSymbols(symbols);
+ getCompletionEntriesFromSymbols(symbols, entries);
}
// Add keywords if this is not a member completion list
if (!isMemberCompletion && !isJsDocTagName) {
ts.addRange(entries, keywordCompletions);
}
return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
- function getJavaScriptCompletionEntries() {
+ function getJavaScriptCompletionEntries(sourceFile, uniqueNames) {
var entries = [];
- var allNames = {};
var target = program.getCompilerOptions().target;
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile = _a[_i];
- var nameTable = getNameTable(sourceFile);
- for (var name_34 in nameTable) {
- if (!allNames[name_34]) {
- allNames[name_34] = name_34;
- var displayName = getCompletionEntryDisplayName(name_34, target, /*performCharacterChecks:*/ true);
- if (displayName) {
- var entry = {
- name: displayName,
- kind: ScriptElementKind.warning,
- kindModifiers: "",
- sortText: "1"
- };
- entries.push(entry);
- }
+ var nameTable = getNameTable(sourceFile);
+ for (var name_36 in nameTable) {
+ if (!uniqueNames[name_36]) {
+ uniqueNames[name_36] = name_36;
+ var displayName = getCompletionEntryDisplayName(name_36, target, /*performCharacterChecks:*/ true);
+ if (displayName) {
+ var entry = {
+ name: displayName,
+ kind: ScriptElementKind.warning,
+ kindModifiers: "",
+ sortText: "1"
+ };
+ entries.push(entry);
}
}
}
@@ -46543,25 +47123,24 @@ var ts;
sortText: "0"
};
}
- function getCompletionEntriesFromSymbols(symbols) {
+ function getCompletionEntriesFromSymbols(symbols, entries) {
var start = new Date().getTime();
- var entries = [];
+ var uniqueNames = {};
if (symbols) {
- var nameToSymbol = {};
for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
var symbol = symbols_3[_i];
var entry = createCompletionEntry(symbol, location);
if (entry) {
var id = ts.escapeIdentifier(entry.name);
- if (!ts.lookUp(nameToSymbol, id)) {
+ if (!ts.lookUp(uniqueNames, id)) {
entries.push(entry);
- nameToSymbol[id] = symbol;
+ uniqueNames[id] = id;
}
}
}
}
log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start));
- return entries;
+ return uniqueNames;
}
}
function getCompletionEntryDetails(fileName, position, entryName) {
@@ -46762,16 +47341,16 @@ var ts;
case ScriptElementKind.parameterElement:
case ScriptElementKind.localVariableElement:
// If it is call or construct signature of lambda's write type name
- displayParts.push(ts.punctuationPart(54 /* ColonToken */));
+ displayParts.push(ts.punctuationPart(ts.SyntaxKind.ColonToken));
displayParts.push(ts.spacePart());
if (useConstructSignatures) {
- displayParts.push(ts.keywordPart(92 /* NewKeyword */));
+ displayParts.push(ts.keywordPart(ts.SyntaxKind.NewKeyword));
displayParts.push(ts.spacePart());
}
- if (!(type.flags & 65536 /* Anonymous */)) {
- ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */));
+ if (!(type.flags & ts.TypeFlags.Anonymous)) {
+ ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, ts.SymbolFormatFlags.WriteTypeParametersOrArguments));
}
- addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */);
+ addSignatureDisplayParts(signature, allSignatures, ts.TypeFormatFlags.WriteArrowStyleSignature);
break;
default:
// Just signature
@@ -48396,19 +48975,19 @@ var ts;
if (isNameOfPropertyAssignment(node)) {
var objectLiteral = node.parent.parent;
var contextualType = typeChecker.getContextualType(objectLiteral);
- var name_35 = node.text;
+ var name_37 = node.text;
if (contextualType) {
if (contextualType.flags & 16384 /* Union */) {
// This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types)
// if not, search the constituent types for the property
- var unionProperty = contextualType.getProperty(name_35);
+ var unionProperty = contextualType.getProperty(name_37);
if (unionProperty) {
return [unionProperty];
}
else {
var result_4 = [];
ts.forEach(contextualType.types, function (t) {
- var symbol = t.getProperty(name_35);
+ var symbol = t.getProperty(name_37);
if (symbol) {
result_4.push(symbol);
}
@@ -48417,7 +48996,7 @@ var ts;
}
}
else {
- var symbol_1 = contextualType.getProperty(name_35);
+ var symbol_1 = contextualType.getProperty(name_37);
if (symbol_1) {
return [symbol_1];
}
@@ -48828,6 +49407,9 @@ var ts;
case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName;
case 17 /* parameterName */: return ClassificationTypeNames.parameterName;
case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName;
+ case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName;
+ case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName;
+ case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName;
}
}
function convertClassifications(classifications) {
@@ -49097,6 +49679,21 @@ var ts;
return 17 /* parameterName */;
}
return;
+ case 235 /* JsxOpeningElement */:
+ if (token.parent.tagName === token) {
+ return 19 /* jsxOpenTagName */;
+ }
+ return;
+ case 237 /* JsxClosingElement */:
+ if (token.parent.tagName === token) {
+ return 20 /* jsxCloseTagName */;
+ }
+ return;
+ case 234 /* JsxSelfClosingElement */:
+ if (token.parent.tagName === token) {
+ return 21 /* jsxSelfClosingTagName */;
+ }
+ return;
}
}
return 2 /* identifier */;
@@ -50021,18 +50618,8 @@ var ts;
ts.getDefaultLibFilePath = getDefaultLibFilePath;
function initializeServices() {
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0 /* None */;
- this.parent = undefined;
- }
- var proto = kind === 248 /* SourceFile */ ? new SourceFileObject() : new NodeObject();
- proto.kind = kind;
- Node.prototype = proto;
- return Node;
- },
+ getNodeConstructor: function () { return NodeObject; },
+ getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
getSignatureConstructor: function () { return SignatureObject; }
@@ -51102,7 +51689,8 @@ var ts;
};
CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
- var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()));
+ // for now treat files as JavaScript
+ var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
var convertResult = {
referencedFiles: [],
importedFiles: [],
@@ -51166,7 +51754,7 @@ var ts;
TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
try {
if (this.documentRegistry === undefined) {
- this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
+ this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
}
var hostAdapter = new LanguageServiceShimHostAdapter(host);
var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry);
@@ -51199,7 +51787,7 @@ var ts;
TypeScriptServicesFactory.prototype.close = function () {
// Forget all the registered shims
this._shims = [];
- this.documentRegistry = ts.createDocumentRegistry();
+ this.documentRegistry = undefined;
};
TypeScriptServicesFactory.prototype.registerShim = function (shim) {
this._shims.push(shim);
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index d2758e6d5e9..af9a8bffe35 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -387,6 +387,7 @@ declare namespace ts {
right: Identifier;
}
type EntityName = Identifier | QualifiedName;
+ type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
@@ -425,7 +426,7 @@ declare namespace ts {
initializer?: Expression;
}
interface BindingElement extends Declaration {
- propertyName?: Identifier;
+ propertyName?: PropertyName;
dotDotDotToken?: Node;
name: Identifier | BindingPattern;
initializer?: Expression;
@@ -452,7 +453,7 @@ declare namespace ts {
objectAssignmentInitializer?: Expression;
}
interface VariableLikeDeclaration extends Declaration {
- propertyName?: Identifier;
+ propertyName?: PropertyName;
dotDotDotToken?: Node;
name: DeclarationName;
questionToken?: Node;
@@ -581,7 +582,7 @@ declare namespace ts {
asteriskToken?: Node;
expression?: Expression;
}
- interface BinaryExpression extends Expression {
+ interface BinaryExpression extends Expression, Declaration {
left: Expression;
operatorToken: Node;
right: Expression;
@@ -625,7 +626,7 @@ declare namespace ts {
interface ObjectLiteralExpression extends PrimaryExpression, Declaration {
properties: NodeArray;
}
- interface PropertyAccessExpression extends MemberExpression {
+ interface PropertyAccessExpression extends MemberExpression, Declaration {
expression: LeftHandSideExpression;
dotToken: Node;
name: Identifier;
@@ -1220,6 +1221,7 @@ declare namespace ts {
ObjectLiteral = 524288,
ESSymbol = 16777216,
ThisType = 33554432,
+ ObjectLiteralPatternWithComputedProperties = 67108864,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
@@ -1537,7 +1539,6 @@ declare namespace ts {
function getTypeParameterOwner(d: Declaration): Declaration;
}
declare namespace ts {
- function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node;
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
@@ -2126,6 +2127,9 @@ declare namespace ts {
static typeAliasName: string;
static parameterName: string;
static docCommentTagName: string;
+ static jsxOpenTagName: string;
+ static jsxCloseTagName: string;
+ static jsxSelfClosingTagName: string;
}
enum ClassificationType {
comment = 1,
@@ -2146,6 +2150,9 @@ declare namespace ts {
typeAliasName = 16,
parameterName = 17,
docCommentTagName = 18,
+ jsxOpenTagName = 19,
+ jsxCloseTagName = 20,
+ jsxSelfClosingTagName = 21,
}
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
@@ -2171,7 +2178,7 @@ declare namespace ts {
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry;
- function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
+ function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
function createClassifier(): Classifier;
/**
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index 8b0ef04f96e..498ddc37860 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -622,6 +622,7 @@ var ts;
TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType";
TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol";
TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType";
+ TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties";
/* @internal */
TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic";
/* @internal */
@@ -1530,12 +1531,7 @@ var ts;
* List of supported extensions in order of file resolution precedence.
*/
ts.supportedExtensions = [".ts", ".tsx", ".d.ts"];
- /**
- * List of extensions that will be used to look for external modules.
- * This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation,
- * but still would like to load only TypeScript files as modules
- */
- ts.moduleFileExtensions = ts.supportedExtensions;
+ ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx");
function isSupportedSourceFileName(fileName) {
if (!fileName) {
return false;
@@ -1586,17 +1582,16 @@ var ts;
}
function Signature(checker) {
}
+ function Node(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0 /* None */;
+ this.parent = undefined;
+ }
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0 /* None */;
- this.parent = undefined;
- }
- Node.prototype = { kind: kind };
- return Node;
- },
+ getNodeConstructor: function () { return Node; },
+ getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
getSignatureConstructor: function () { return Signature; }
@@ -1913,7 +1908,16 @@ var ts;
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
- _fs.writeFileSync(fileName, data, "utf8");
+ var fd;
+ try {
+ fd = _fs.openSync(fileName, "w");
+ _fs.writeSync(fd, data, undefined, "utf8");
+ }
+ finally {
+ if (fd !== undefined) {
+ _fs.closeSync(fd);
+ }
+ }
}
function getCanonicalPath(path) {
return useCaseSensitiveFileNames ? path.toLowerCase() : path;
@@ -2614,6 +2618,7 @@ var ts;
Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." },
+ Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -3173,7 +3178,7 @@ var ts;
function getCommentRanges(text, pos, trailing) {
var result;
var collecting = trailing || pos === 0;
- while (true) {
+ while (pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
case 13 /* carriageReturn */:
@@ -3242,6 +3247,7 @@ var ts;
}
return result;
}
+ return result;
}
function getLeadingCommentRanges(text, pos) {
return getCommentRanges(text, pos, /*trailing*/ false);
@@ -3343,7 +3349,7 @@ var ts;
error(ts.Diagnostics.Digit_expected);
}
}
- return +(text.substring(start, end));
+ return "" + +(text.substring(start, end));
}
function scanOctalDigits() {
var start = pos;
@@ -3770,7 +3776,7 @@ var ts;
return pos++, token = 36 /* MinusToken */;
case 46 /* dot */:
if (isDigit(text.charCodeAt(pos + 1))) {
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8 /* NumericLiteral */;
}
if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
@@ -3873,7 +3879,7 @@ var ts;
case 55 /* _7 */:
case 56 /* _8 */:
case 57 /* _9 */:
- tokenValue = "" + scanNumber();
+ tokenValue = scanNumber();
return token = 8 /* NumericLiteral */;
case 58 /* colon */:
return pos++, token = 54 /* ColonToken */;
@@ -4177,1321 +4183,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-///
-/* @internal */
-var ts;
-(function (ts) {
- ts.bindTime = 0;
- (function (ModuleInstanceState) {
- ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
- ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
- ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
- })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
- var ModuleInstanceState = ts.ModuleInstanceState;
- var Reachability;
- (function (Reachability) {
- Reachability[Reachability["Unintialized"] = 1] = "Unintialized";
- Reachability[Reachability["Reachable"] = 2] = "Reachable";
- Reachability[Reachability["Unreachable"] = 4] = "Unreachable";
- Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable";
- })(Reachability || (Reachability = {}));
- function or(state1, state2) {
- return (state1 | state2) & 2 /* Reachable */
- ? 2 /* Reachable */
- : (state1 & state2) & 8 /* ReportedUnreachable */
- ? 8 /* ReportedUnreachable */
- : 4 /* Unreachable */;
- }
- function getModuleInstanceState(node) {
- // A module is uninstantiated if it contains only
- // 1. interface declarations, type alias declarations
- if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) {
- return 0 /* NonInstantiated */;
- }
- else if (ts.isConstEnumDeclaration(node)) {
- return 2 /* ConstEnumOnly */;
- }
- else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) {
- return 0 /* NonInstantiated */;
- }
- else if (node.kind === 219 /* ModuleBlock */) {
- var state = 0 /* NonInstantiated */;
- ts.forEachChild(node, function (n) {
- switch (getModuleInstanceState(n)) {
- case 0 /* NonInstantiated */:
- // child is non-instantiated - continue searching
- return false;
- case 2 /* ConstEnumOnly */:
- // child is const enum only - record state and continue searching
- state = 2 /* ConstEnumOnly */;
- return false;
- case 1 /* Instantiated */:
- // child is instantiated - record state and stop
- state = 1 /* Instantiated */;
- return true;
- }
- });
- return state;
- }
- else if (node.kind === 218 /* ModuleDeclaration */) {
- return getModuleInstanceState(node.body);
- }
- else {
- return 1 /* Instantiated */;
- }
- }
- ts.getModuleInstanceState = getModuleInstanceState;
- var ContainerFlags;
- (function (ContainerFlags) {
- // The current node is not a container, and no container manipulation should happen before
- // recursing into it.
- ContainerFlags[ContainerFlags["None"] = 0] = "None";
- // The current node is a container. It should be set as the current container (and block-
- // container) before recursing into it. The current node does not have locals. Examples:
- //
- // Classes, ObjectLiterals, TypeLiterals, Interfaces...
- ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
- // The current node is a block-scoped-container. It should be set as the current block-
- // container before recursing into it. Examples:
- //
- // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
- ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
- ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals";
- // If the current node is a container that also container that also contains locals. Examples:
- //
- // Functions, Methods, Modules, Source-files.
- ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals";
- })(ContainerFlags || (ContainerFlags = {}));
- var binder = createBinder();
- function bindSourceFile(file, options) {
- var start = new Date().getTime();
- binder(file, options);
- ts.bindTime += new Date().getTime() - start;
- }
- ts.bindSourceFile = bindSourceFile;
- function createBinder() {
- var file;
- var options;
- var parent;
- var container;
- var blockScopeContainer;
- var lastContainer;
- var seenThisKeyword;
- // state used by reachability checks
- var hasExplicitReturn;
- var currentReachabilityState;
- var labelStack;
- var labelIndexMap;
- var implicitLabels;
- // If this file is an external module, then it is automatically in strict-mode according to
- // ES6. If it is not an external module, then we'll determine if it is in strict mode or
- // not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
- var inStrictMode;
- var symbolCount = 0;
- var Symbol;
- var classifiableNames;
- function bindSourceFile(f, opts) {
- file = f;
- options = opts;
- inStrictMode = !!file.externalModuleIndicator;
- classifiableNames = {};
- Symbol = ts.objectAllocator.getSymbolConstructor();
- if (!file.locals) {
- bind(file);
- file.symbolCount = symbolCount;
- file.classifiableNames = classifiableNames;
- }
- parent = undefined;
- container = undefined;
- blockScopeContainer = undefined;
- lastContainer = undefined;
- seenThisKeyword = false;
- hasExplicitReturn = false;
- labelStack = undefined;
- labelIndexMap = undefined;
- implicitLabels = undefined;
- }
- return bindSourceFile;
- function createSymbol(flags, name) {
- symbolCount++;
- return new Symbol(flags, name);
- }
- function addDeclarationToSymbol(symbol, node, symbolFlags) {
- symbol.flags |= symbolFlags;
- node.symbol = symbol;
- if (!symbol.declarations) {
- symbol.declarations = [];
- }
- symbol.declarations.push(node);
- if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) {
- symbol.exports = {};
- }
- if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) {
- symbol.members = {};
- }
- if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) {
- symbol.valueDeclaration = node;
- }
- }
- // Should not be called on a declaration with a computed property name,
- // unless it is a well known Symbol.
- function getDeclarationName(node) {
- if (node.name) {
- if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
- return "\"" + node.name.text + "\"";
- }
- if (node.name.kind === 136 /* ComputedPropertyName */) {
- var nameExpression = node.name.expression;
- ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
- return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
- }
- return node.name.text;
- }
- switch (node.kind) {
- case 144 /* Constructor */:
- return "__constructor";
- case 152 /* FunctionType */:
- case 147 /* CallSignature */:
- return "__call";
- case 153 /* ConstructorType */:
- case 148 /* ConstructSignature */:
- return "__new";
- case 149 /* IndexSignature */:
- return "__index";
- case 228 /* ExportDeclaration */:
- return "__export";
- case 227 /* ExportAssignment */:
- return node.isExportEquals ? "export=" : "default";
- case 213 /* FunctionDeclaration */:
- case 214 /* ClassDeclaration */:
- return node.flags & 512 /* Default */ ? "default" : undefined;
- }
- }
- function getDisplayName(node) {
- return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node);
- }
- /**
- * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
- * @param symbolTable - The symbol table which node will be added to.
- * @param parent - node's parent declaration.
- * @param node - The declaration to be added to the symbol table
- * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
- * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
- */
- function declareSymbol(symbolTable, parent, node, includes, excludes) {
- ts.Debug.assert(!ts.hasDynamicName(node));
- var isDefaultExport = node.flags & 512 /* Default */;
- // The exported symbol for an export default function/class node is always named "default"
- var name = isDefaultExport && parent ? "default" : getDeclarationName(node);
- var symbol;
- if (name !== undefined) {
- // Check and see if the symbol table already has a symbol with this name. If not,
- // create a new symbol with this name and add it to the table. Note that we don't
- // give the new symbol any flags *yet*. This ensures that it will not conflict
- // with the 'excludes' flags we pass in.
- //
- // If we do get an existing symbol, see if it conflicts with the new symbol we're
- // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
- // the same symbol table. If we have a conflict, report the issue on each
- // declaration we have for this symbol, and then create a new symbol for this
- // declaration.
- //
- // If we created a new symbol, either because we didn't have a symbol with this name
- // in the symbol table, or we conflicted with an existing symbol, then just add this
- // node as the sole declaration of the new symbol.
- //
- // Otherwise, we'll be merging into a compatible existing symbol (for example when
- // you have multiple 'vars' with the same name in the same container). In this case
- // just add this node into the declarations list of the symbol.
- symbol = ts.hasProperty(symbolTable, name)
- ? symbolTable[name]
- : (symbolTable[name] = createSymbol(0 /* None */, name));
- if (name && (includes & 788448 /* Classifiable */)) {
- classifiableNames[name] = name;
- }
- if (symbol.flags & excludes) {
- if (node.name) {
- node.name.parent = node;
- }
- // Report errors every position with duplicate declaration
- // Report errors on previous encountered declarations
- var message = symbol.flags & 2 /* BlockScopedVariable */
- ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
- : ts.Diagnostics.Duplicate_identifier_0;
- ts.forEach(symbol.declarations, function (declaration) {
- if (declaration.flags & 512 /* Default */) {
- message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
- }
- });
- ts.forEach(symbol.declarations, function (declaration) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
- });
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
- symbol = createSymbol(0 /* None */, name);
- }
- }
- else {
- symbol = createSymbol(0 /* None */, "__missing");
- }
- addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
- return symbol;
- }
- function declareModuleMember(node, symbolFlags, symbolExcludes) {
- var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */;
- if (symbolFlags & 8388608 /* Alias */) {
- if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) {
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- }
- else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- else {
- // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue,
- // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
- // on it. There are 2 main reasons:
- //
- // 1. We treat locals and exports of the same name as mutually exclusive within a container.
- // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
- // with the same name in the same container.
- // TODO: Make this a more specific error and decouple it from the exclusion logic.
- // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
- // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
- // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
- if (hasExportModifier || container.flags & 131072 /* ExportContext */) {
- var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) |
- (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) |
- (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0);
- var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
- local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- node.localSymbol = local;
- return local;
- }
- else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- }
- // All container nodes are kept on a linked list in declaration order. This list is used by
- // the getLocalNameOfContainer function in the type checker to validate that the local name
- // used for a container is unique.
- function bindChildren(node) {
- // Before we recurse into a node's chilren, we first save the existing parent, container
- // and block-container. Then after we pop out of processing the children, we restore
- // these saved values.
- var saveParent = parent;
- var saveContainer = container;
- var savedBlockScopeContainer = blockScopeContainer;
- // This node will now be set as the parent of all of its children as we recurse into them.
- parent = node;
- // Depending on what kind of node this is, we may have to adjust the current container
- // and block-container. If the current node is a container, then it is automatically
- // considered the current block-container as well. Also, for containers that we know
- // may contain locals, we proactively initialize the .locals field. We do this because
- // it's highly likely that the .locals will be needed to place some child in (for example,
- // a parameter, or variable declaration).
- //
- // However, we do not proactively create the .locals for block-containers because it's
- // totally normal and common for block-containers to never actually have a block-scoped
- // variable in them. We don't want to end up allocating an object for every 'block' we
- // run into when most of them won't be necessary.
- //
- // Finally, if this is a block-container, then we clear out any existing .locals object
- // it may contain within it. This happens in incremental scenarios. Because we can be
- // reusing a node from a previous compilation, that node may have had 'locals' created
- // for it. We must clear this so we don't accidently move any stale data forward from
- // a previous compilation.
- var containerFlags = getContainerFlags(node);
- if (containerFlags & 1 /* IsContainer */) {
- container = blockScopeContainer = node;
- if (containerFlags & 4 /* HasLocals */) {
- container.locals = {};
- }
- addToContainerChain(container);
- }
- else if (containerFlags & 2 /* IsBlockScopedContainer */) {
- blockScopeContainer = node;
- blockScopeContainer.locals = undefined;
- }
- var savedReachabilityState;
- var savedLabelStack;
- var savedLabels;
- var savedImplicitLabels;
- var savedHasExplicitReturn;
- var kind = node.kind;
- var flags = node.flags;
- // reset all reachability check related flags on node (for incremental scenarios)
- flags &= ~1572864 /* ReachabilityCheckFlags */;
- if (kind === 215 /* InterfaceDeclaration */) {
- seenThisKeyword = false;
- }
- var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind);
- if (saveState) {
- savedReachabilityState = currentReachabilityState;
- savedLabelStack = labelStack;
- savedLabels = labelIndexMap;
- savedImplicitLabels = implicitLabels;
- savedHasExplicitReturn = hasExplicitReturn;
- currentReachabilityState = 2 /* Reachable */;
- hasExplicitReturn = false;
- labelStack = labelIndexMap = implicitLabels = undefined;
- }
- bindReachableStatement(node);
- if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) {
- flags |= 524288 /* HasImplicitReturn */;
- if (hasExplicitReturn) {
- flags |= 1048576 /* HasExplicitReturn */;
- }
- }
- if (kind === 215 /* InterfaceDeclaration */) {
- flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */;
- }
- node.flags = flags;
- if (saveState) {
- hasExplicitReturn = savedHasExplicitReturn;
- currentReachabilityState = savedReachabilityState;
- labelStack = savedLabelStack;
- labelIndexMap = savedLabels;
- implicitLabels = savedImplicitLabels;
- }
- container = saveContainer;
- parent = saveParent;
- blockScopeContainer = savedBlockScopeContainer;
- }
- /**
- * Returns true if node and its subnodes were successfully traversed.
- * Returning false means that node was not examined and caller needs to dive into the node himself.
- */
- function bindReachableStatement(node) {
- if (checkUnreachable(node)) {
- ts.forEachChild(node, bind);
- return;
- }
- switch (node.kind) {
- case 198 /* WhileStatement */:
- bindWhileStatement(node);
- break;
- case 197 /* DoStatement */:
- bindDoStatement(node);
- break;
- case 199 /* ForStatement */:
- bindForStatement(node);
- break;
- case 200 /* ForInStatement */:
- case 201 /* ForOfStatement */:
- bindForInOrForOfStatement(node);
- break;
- case 196 /* IfStatement */:
- bindIfStatement(node);
- break;
- case 204 /* ReturnStatement */:
- case 208 /* ThrowStatement */:
- bindReturnOrThrow(node);
- break;
- case 203 /* BreakStatement */:
- case 202 /* ContinueStatement */:
- bindBreakOrContinueStatement(node);
- break;
- case 209 /* TryStatement */:
- bindTryStatement(node);
- break;
- case 206 /* SwitchStatement */:
- bindSwitchStatement(node);
- break;
- case 220 /* CaseBlock */:
- bindCaseBlock(node);
- break;
- case 207 /* LabeledStatement */:
- bindLabeledStatement(node);
- break;
- default:
- ts.forEachChild(node, bind);
- break;
- }
- }
- function bindWhileStatement(n) {
- var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- // bind expressions (don't affect reachability)
- bind(n.expression);
- currentReachabilityState = preWhileState;
- var postWhileLabel = pushImplicitLabel();
- bind(n.statement);
- popImplicitLabel(postWhileLabel, postWhileState);
- }
- function bindDoStatement(n) {
- var preDoState = currentReachabilityState;
- var postDoLabel = pushImplicitLabel();
- bind(n.statement);
- var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState;
- popImplicitLabel(postDoLabel, postDoState);
- // bind expressions (don't affect reachability)
- bind(n.expression);
- }
- function bindForStatement(n) {
- var preForState = currentReachabilityState;
- var postForLabel = pushImplicitLabel();
- // bind expressions (don't affect reachability)
- bind(n.initializer);
- bind(n.condition);
- bind(n.incrementor);
- bind(n.statement);
- // for statement is considered infinite when it condition is either omitted or is true keyword
- // - for(..;;..)
- // - for(..;true;..)
- var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */);
- var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState;
- popImplicitLabel(postForLabel, postForState);
- }
- function bindForInOrForOfStatement(n) {
- var preStatementState = currentReachabilityState;
- var postStatementLabel = pushImplicitLabel();
- // bind expressions (don't affect reachability)
- bind(n.initializer);
- bind(n.expression);
- bind(n.statement);
- popImplicitLabel(postStatementLabel, preStatementState);
- }
- function bindIfStatement(n) {
- // denotes reachability state when entering 'thenStatement' part of the if statement:
- // i.e. if condition is false then thenStatement is unreachable
- var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- // denotes reachability state when entering 'elseStatement':
- // i.e. if condition is true then elseStatement is unreachable
- var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
- currentReachabilityState = ifTrueState;
- // bind expression (don't affect reachability)
- bind(n.expression);
- bind(n.thenStatement);
- if (n.elseStatement) {
- var preElseState = currentReachabilityState;
- currentReachabilityState = ifFalseState;
- bind(n.elseStatement);
- currentReachabilityState = or(currentReachabilityState, preElseState);
- }
- else {
- currentReachabilityState = or(currentReachabilityState, ifFalseState);
- }
- }
- function bindReturnOrThrow(n) {
- // bind expression (don't affect reachability)
- bind(n.expression);
- if (n.kind === 204 /* ReturnStatement */) {
- hasExplicitReturn = true;
- }
- currentReachabilityState = 4 /* Unreachable */;
- }
- function bindBreakOrContinueStatement(n) {
- // call bind on label (don't affect reachability)
- bind(n.label);
- // for continue case touch label so it will be marked a used
- var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */);
- if (isValidJump) {
- currentReachabilityState = 4 /* Unreachable */;
- }
- }
- function bindTryStatement(n) {
- // catch\finally blocks has the same reachability as try block
- var preTryState = currentReachabilityState;
- bind(n.tryBlock);
- var postTryState = currentReachabilityState;
- currentReachabilityState = preTryState;
- bind(n.catchClause);
- var postCatchState = currentReachabilityState;
- currentReachabilityState = preTryState;
- bind(n.finallyBlock);
- // post catch/finally state is reachable if
- // - post try state is reachable - control flow can fall out of try block
- // - post catch state is reachable - control flow can fall out of catch block
- currentReachabilityState = or(postTryState, postCatchState);
- }
- function bindSwitchStatement(n) {
- var preSwitchState = currentReachabilityState;
- var postSwitchLabel = pushImplicitLabel();
- // bind expression (don't affect reachability)
- bind(n.expression);
- bind(n.caseBlock);
- var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; });
- // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case
- var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState;
- popImplicitLabel(postSwitchLabel, postSwitchState);
- }
- function bindCaseBlock(n) {
- var startState = currentReachabilityState;
- for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) {
- var clause = _a[_i];
- currentReachabilityState = startState;
- bind(clause);
- if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) {
- errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
- }
- }
- }
- function bindLabeledStatement(n) {
- // call bind on label (don't affect reachability)
- bind(n.label);
- var ok = pushNamedLabel(n.label);
- bind(n.statement);
- if (ok) {
- popNamedLabel(n.label, currentReachabilityState);
- }
- }
- function getContainerFlags(node) {
- switch (node.kind) {
- case 186 /* ClassExpression */:
- case 214 /* ClassDeclaration */:
- case 215 /* InterfaceDeclaration */:
- case 217 /* EnumDeclaration */:
- case 155 /* TypeLiteral */:
- case 165 /* ObjectLiteralExpression */:
- return 1 /* IsContainer */;
- case 147 /* CallSignature */:
- case 148 /* ConstructSignature */:
- case 149 /* IndexSignature */:
- case 143 /* MethodDeclaration */:
- case 142 /* MethodSignature */:
- case 213 /* FunctionDeclaration */:
- case 144 /* Constructor */:
- case 145 /* GetAccessor */:
- case 146 /* SetAccessor */:
- case 152 /* FunctionType */:
- case 153 /* ConstructorType */:
- case 173 /* FunctionExpression */:
- case 174 /* ArrowFunction */:
- case 218 /* ModuleDeclaration */:
- case 248 /* SourceFile */:
- case 216 /* TypeAliasDeclaration */:
- return 5 /* IsContainerWithLocals */;
- case 244 /* CatchClause */:
- case 199 /* ForStatement */:
- case 200 /* ForInStatement */:
- case 201 /* ForOfStatement */:
- case 220 /* CaseBlock */:
- return 2 /* IsBlockScopedContainer */;
- case 192 /* Block */:
- // do not treat blocks directly inside a function as a block-scoped-container.
- // Locals that reside in this block should go to the function locals. Othewise 'x'
- // would not appear to be a redeclaration of a block scoped local in the following
- // example:
- //
- // function foo() {
- // var x;
- // let x;
- // }
- //
- // If we placed 'var x' into the function locals and 'let x' into the locals of
- // the block, then there would be no collision.
- //
- // By not creating a new block-scoped-container here, we ensure that both 'var x'
- // and 'let x' go into the Function-container's locals, and we do get a collision
- // conflict.
- return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
- }
- return 0 /* None */;
- }
- function addToContainerChain(next) {
- if (lastContainer) {
- lastContainer.nextContainer = next;
- }
- lastContainer = next;
- }
- function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
- // Just call this directly so that the return type of this function stays "void".
- declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes);
- }
- function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) {
- switch (container.kind) {
- // Modules, source files, and classes need specialized handling for how their
- // members are declared (for example, a member of a class will go into a specific
- // symbol table depending on if it is static or not). We defer to specialized
- // handlers to take care of declaring these child members.
- case 218 /* ModuleDeclaration */:
- return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 248 /* SourceFile */:
- return declareSourceFileMember(node, symbolFlags, symbolExcludes);
- case 186 /* ClassExpression */:
- case 214 /* ClassDeclaration */:
- return declareClassMember(node, symbolFlags, symbolExcludes);
- case 217 /* EnumDeclaration */:
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- case 155 /* TypeLiteral */:
- case 165 /* ObjectLiteralExpression */:
- case 215 /* InterfaceDeclaration */:
- // Interface/Object-types always have their children added to the 'members' of
- // their container. They are only accessible through an instance of their
- // container, and are never in scope otherwise (even inside the body of the
- // object / type / interface declaring them). An exception is type parameters,
- // which are in scope without qualification (similar to 'locals').
- return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- case 152 /* FunctionType */:
- case 153 /* ConstructorType */:
- case 147 /* CallSignature */:
- case 148 /* ConstructSignature */:
- case 149 /* IndexSignature */:
- case 143 /* MethodDeclaration */:
- case 142 /* MethodSignature */:
- case 144 /* Constructor */:
- case 145 /* GetAccessor */:
- case 146 /* SetAccessor */:
- case 213 /* FunctionDeclaration */:
- case 173 /* FunctionExpression */:
- case 174 /* ArrowFunction */:
- case 216 /* TypeAliasDeclaration */:
- // All the children of these container types are never visible through another
- // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
- // they're only accessed 'lexically' (i.e. from code that exists underneath
- // their container in the tree. To accomplish this, we simply add their declared
- // symbol to the 'locals' of the container. These symbols can then be found as
- // the type checker walks up the containers, checking them for matching names.
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- function declareClassMember(node, symbolFlags, symbolExcludes) {
- return node.flags & 64 /* Static */
- ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
- : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- }
- function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
- return ts.isExternalModule(file)
- ? declareModuleMember(node, symbolFlags, symbolExcludes)
- : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- function hasExportDeclarations(node) {
- var body = node.kind === 248 /* SourceFile */ ? node : node.body;
- if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) {
- for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
- var stat = _a[_i];
- if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) {
- return true;
- }
- }
- }
- return false;
- }
- function setExportContextFlag(node) {
- // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
- // declarations with export modifiers) is an export context in which declarations are implicitly exported.
- if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) {
- node.flags |= 131072 /* ExportContext */;
- }
- else {
- node.flags &= ~131072 /* ExportContext */;
- }
- }
- function bindModuleDeclaration(node) {
- setExportContextFlag(node);
- if (node.name.kind === 9 /* StringLiteral */) {
- declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- }
- else {
- var state = getModuleInstanceState(node);
- if (state === 0 /* NonInstantiated */) {
- declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
- // if module was already merged with some function, class or non-const enum
- // treat is a non-const-enum-only
- node.symbol.constEnumOnlyModule = false;
- }
- else {
- var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */;
- if (node.symbol.constEnumOnlyModule === undefined) {
- // non-merged case - use the current state
- node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
- }
- else {
- // merged case: module is const enum only if all its pieces are non-instantiated or const enum
- node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
- }
- }
- }
- }
- }
- function bindFunctionOrConstructorType(node) {
- // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
- // to the one we would get for: { <...>(...): T }
- //
- // We do that by making an anonymous type literal symbol, and then setting the function
- // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
- // from an actual type literal symbol you would have gotten had you used the long form.
- var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node));
- addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
- var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type");
- addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
- typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a);
- var _a;
- }
- function bindObjectLiteralExpression(node) {
- var ElementKind;
- (function (ElementKind) {
- ElementKind[ElementKind["Property"] = 1] = "Property";
- ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
- })(ElementKind || (ElementKind = {}));
- if (inStrictMode) {
- var seen = {};
- for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
- var prop = _a[_i];
- if (prop.name.kind !== 69 /* Identifier */) {
- continue;
- }
- var identifier = prop.name;
- // ECMA-262 11.1.5 Object Initialiser
- // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
- // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
- // IsDataDescriptor(propId.descriptor) is true.
- // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
- // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
- // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
- // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
- var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */
- ? 1 /* Property */
- : 2 /* Accessor */;
- var existingKind = seen[identifier.text];
- if (!existingKind) {
- seen[identifier.text] = currentKind;
- continue;
- }
- if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
- var span = ts.getErrorSpanForNode(file, identifier);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
- }
- }
- }
- return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object");
- }
- function bindAnonymousDeclaration(node, symbolFlags, name) {
- var symbol = createSymbol(symbolFlags, name);
- addDeclarationToSymbol(symbol, node, symbolFlags);
- }
- function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
- switch (blockScopeContainer.kind) {
- case 218 /* ModuleDeclaration */:
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- case 248 /* SourceFile */:
- if (ts.isExternalModule(container)) {
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- }
- // fall through.
- default:
- if (!blockScopeContainer.locals) {
- blockScopeContainer.locals = {};
- addToContainerChain(blockScopeContainer);
- }
- declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
- }
- }
- function bindBlockScopedVariableDeclaration(node) {
- bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */);
- }
- // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
- // check for reserved words used as identifiers in strict mode code.
- function checkStrictModeIdentifier(node) {
- if (inStrictMode &&
- node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ &&
- node.originalKeywordKind <= 114 /* LastFutureReservedWord */ &&
- !ts.isIdentifierName(node)) {
- // Report error only if there are no parse errors in file
- if (!file.parseDiagnostics.length) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
- }
- }
- }
- function getStrictModeIdentifierMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
- }
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
- }
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
- }
- function checkStrictModeBinaryExpression(node) {
- if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
- // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
- // Assignment operator(11.13) or of a PostfixExpression(11.3)
- checkStrictModeEvalOrArguments(node, node.left);
- }
- }
- function checkStrictModeCatchClause(node) {
- // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
- // Catch production is eval or arguments
- if (inStrictMode && node.variableDeclaration) {
- checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
- }
- }
- function checkStrictModeDeleteExpression(node) {
- // Grammar checking
- if (inStrictMode && node.expression.kind === 69 /* Identifier */) {
- // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
- // UnaryExpression is a direct reference to a variable, function argument, or function name
- var span = ts.getErrorSpanForNode(file, node.expression);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
- }
- }
- function isEvalOrArgumentsIdentifier(node) {
- return node.kind === 69 /* Identifier */ &&
- (node.text === "eval" || node.text === "arguments");
- }
- function checkStrictModeEvalOrArguments(contextNode, name) {
- if (name && name.kind === 69 /* Identifier */) {
- var identifier = name;
- if (isEvalOrArgumentsIdentifier(identifier)) {
- // We check first if the name is inside class declaration or class expression; if so give explicit message
- // otherwise report generic error message.
- var span = ts.getErrorSpanForNode(file, name);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));
- }
- }
- }
- function getStrictModeEvalOrArgumentsMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
- }
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
- }
- return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
- }
- function checkStrictModeFunctionName(node) {
- if (inStrictMode) {
- // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
- checkStrictModeEvalOrArguments(node, node.name);
- }
- }
- function checkStrictModeNumericLiteral(node) {
- if (inStrictMode && node.flags & 32768 /* OctalLiteral */) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
- }
- }
- function checkStrictModePostfixUnaryExpression(node) {
- // Grammar checking
- // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
- // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
- // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.operand);
- }
- }
- function checkStrictModePrefixUnaryExpression(node) {
- // Grammar checking
- if (inStrictMode) {
- if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) {
- checkStrictModeEvalOrArguments(node, node.operand);
- }
- }
- }
- function checkStrictModeWithStatement(node) {
- // Grammar checking for withStatement
- if (inStrictMode) {
- errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
- }
- }
- function errorOnFirstToken(node, message, arg0, arg1, arg2) {
- var span = ts.getSpanOfTokenAtPosition(file, node.pos);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
- }
- function getDestructuringParameterName(node) {
- return "__" + ts.indexOf(node.parent.parameters, node);
- }
- function bind(node) {
- if (!node) {
- return;
- }
- node.parent = parent;
- var savedInStrictMode = inStrictMode;
- if (!savedInStrictMode) {
- updateStrictMode(node);
- }
- // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
- // and then potentially add the symbol to an appropriate symbol table. Possible
- // destination symbol tables are:
- //
- // 1) The 'exports' table of the current container's symbol.
- // 2) The 'members' table of the current container's symbol.
- // 3) The 'locals' table of the current container.
- //
- // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
- // (like TypeLiterals for example) will not be put in any table.
- bindWorker(node);
- // Then we recurse into the children of the node to bind them as well. For certain
- // symbols we do specialized work when we recurse. For example, we'll keep track of
- // the current 'container' node when it changes. This helps us know which symbol table
- // a local should go into for example.
- bindChildren(node);
- inStrictMode = savedInStrictMode;
- }
- function updateStrictMode(node) {
- switch (node.kind) {
- case 248 /* SourceFile */:
- case 219 /* ModuleBlock */:
- updateStrictModeStatementList(node.statements);
- return;
- case 192 /* Block */:
- if (ts.isFunctionLike(node.parent)) {
- updateStrictModeStatementList(node.statements);
- }
- return;
- case 214 /* ClassDeclaration */:
- case 186 /* ClassExpression */:
- // All classes are automatically in strict mode in ES6.
- inStrictMode = true;
- return;
- }
- }
- function updateStrictModeStatementList(statements) {
- for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
- var statement = statements_1[_i];
- if (!ts.isPrologueDirective(statement)) {
- return;
- }
- if (isUseStrictPrologueDirective(statement)) {
- inStrictMode = true;
- return;
- }
- }
- }
- /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
- function isUseStrictPrologueDirective(node) {
- var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression);
- // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
- // string to contain unicode escapes (as per ES5).
- return nodeText === "\"use strict\"" || nodeText === "'use strict'";
- }
- function bindWorker(node) {
- switch (node.kind) {
- case 69 /* Identifier */:
- return checkStrictModeIdentifier(node);
- case 181 /* BinaryExpression */:
- return checkStrictModeBinaryExpression(node);
- case 244 /* CatchClause */:
- return checkStrictModeCatchClause(node);
- case 175 /* DeleteExpression */:
- return checkStrictModeDeleteExpression(node);
- case 8 /* NumericLiteral */:
- return checkStrictModeNumericLiteral(node);
- case 180 /* PostfixUnaryExpression */:
- return checkStrictModePostfixUnaryExpression(node);
- case 179 /* PrefixUnaryExpression */:
- return checkStrictModePrefixUnaryExpression(node);
- case 205 /* WithStatement */:
- return checkStrictModeWithStatement(node);
- case 97 /* ThisKeyword */:
- seenThisKeyword = true;
- return;
- case 137 /* TypeParameter */:
- return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */);
- case 138 /* Parameter */:
- return bindParameter(node);
- case 211 /* VariableDeclaration */:
- case 163 /* BindingElement */:
- return bindVariableDeclarationOrBindingElement(node);
- case 141 /* PropertyDeclaration */:
- case 140 /* PropertySignature */:
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */);
- case 245 /* PropertyAssignment */:
- case 246 /* ShorthandPropertyAssignment */:
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */);
- case 247 /* EnumMember */:
- return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */);
- case 147 /* CallSignature */:
- case 148 /* ConstructSignature */:
- case 149 /* IndexSignature */:
- return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
- case 143 /* MethodDeclaration */:
- case 142 /* MethodSignature */:
- // If this is an ObjectLiteralExpression method, then it sits in the same space
- // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
- // so that it will conflict with any other object literal members with the same
- // name.
- return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */);
- case 213 /* FunctionDeclaration */:
- checkStrictModeFunctionName(node);
- return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */);
- case 144 /* Constructor */:
- return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
- case 145 /* GetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */);
- case 146 /* SetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */);
- case 152 /* FunctionType */:
- case 153 /* ConstructorType */:
- return bindFunctionOrConstructorType(node);
- case 155 /* TypeLiteral */:
- return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type");
- case 165 /* ObjectLiteralExpression */:
- return bindObjectLiteralExpression(node);
- case 173 /* FunctionExpression */:
- case 174 /* ArrowFunction */:
- checkStrictModeFunctionName(node);
- var bindingName = node.name ? node.name.text : "__function";
- return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
- case 186 /* ClassExpression */:
- case 214 /* ClassDeclaration */:
- return bindClassLikeDeclaration(node);
- case 215 /* InterfaceDeclaration */:
- return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */);
- case 216 /* TypeAliasDeclaration */:
- return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */);
- case 217 /* EnumDeclaration */:
- return bindEnumDeclaration(node);
- case 218 /* ModuleDeclaration */:
- return bindModuleDeclaration(node);
- case 221 /* ImportEqualsDeclaration */:
- case 224 /* NamespaceImport */:
- case 226 /* ImportSpecifier */:
- case 230 /* ExportSpecifier */:
- return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
- case 223 /* ImportClause */:
- return bindImportClause(node);
- case 228 /* ExportDeclaration */:
- return bindExportDeclaration(node);
- case 227 /* ExportAssignment */:
- return bindExportAssignment(node);
- case 248 /* SourceFile */:
- return bindSourceFileIfExternalModule();
- }
- }
- function bindSourceFileIfExternalModule() {
- setExportContextFlag(file);
- if (ts.isExternalModule(file)) {
- bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
- }
- }
- function bindExportAssignment(node) {
- if (!container.symbol || !container.symbol.exports) {
- // Export assignment in some sort of block construct
- bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node));
- }
- else if (node.expression.kind === 69 /* Identifier */) {
- // An export default clause with an identifier exports all meanings of that identifier
- declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
- }
- else {
- // An export default clause with an expression exports a value
- declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
- }
- }
- function bindExportDeclaration(node) {
- if (!container.symbol || !container.symbol.exports) {
- // Export * in some sort of block construct
- bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node));
- }
- else if (!node.exportClause) {
- // All export * declarations are collected in an __export symbol
- declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */);
- }
- }
- function bindImportClause(node) {
- if (node.name) {
- declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
- }
- }
- function bindClassLikeDeclaration(node) {
- if (node.kind === 214 /* ClassDeclaration */) {
- bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */);
- }
- else {
- var bindingName = node.name ? node.name.text : "__class";
- bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
- // Add name of class expression into the map for semantic classifier
- if (node.name) {
- classifiableNames[node.name.text] = node.name.text;
- }
- }
- var symbol = node.symbol;
- // TypeScript 1.0 spec (April 2014): 8.4
- // Every class automatically contains a static property member named 'prototype', the
- // type of which is an instantiation of the class type with type Any supplied as a type
- // argument for each type parameter. It is an error to explicitly declare a static
- // property member with the name 'prototype'.
- //
- // Note: we check for this here because this class may be merging into a module. The
- // module might have an exported variable called 'prototype'. We can't allow that as
- // that would clash with the built-in 'prototype' for the class.
- var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype");
- if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) {
- if (node.name) {
- node.name.parent = node;
- }
- file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
- }
- symbol.exports[prototypeSymbol.name] = prototypeSymbol;
- prototypeSymbol.parent = symbol;
- }
- function bindEnumDeclaration(node) {
- return ts.isConst(node)
- ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
- : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
- }
- function bindVariableDeclarationOrBindingElement(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.name);
- }
- if (!ts.isBindingPattern(node.name)) {
- if (ts.isBlockOrCatchScoped(node)) {
- bindBlockScopedVariableDeclaration(node);
- }
- else if (ts.isParameterDeclaration(node)) {
- // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration
- // because its parent chain has already been set up, since parents are set before descending into children.
- //
- // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
- // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
- // For example:
- // function foo([a,a]) {} // Duplicate Identifier error
- // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
- // // which correctly set excluded symbols
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */);
- }
- }
- }
- function bindParameter(node) {
- if (inStrictMode) {
- // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
- // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
- checkStrictModeEvalOrArguments(node, node.name);
- }
- if (ts.isBindingPattern(node.name)) {
- bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node));
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
- }
- // If this is a property-parameter, then also declare the property symbol into the
- // containing class.
- if (node.flags & 56 /* AccessibilityModifier */ &&
- node.parent.kind === 144 /* Constructor */ &&
- ts.isClassLike(node.parent.parent)) {
- var classDeclaration = node.parent.parent;
- declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */);
- }
- }
- function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
- return ts.hasDynamicName(node)
- ? bindAnonymousDeclaration(node, symbolFlags, "__computed")
- : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
- }
- // reachability checks
- function pushNamedLabel(name) {
- initializeReachabilityStateIfNecessary();
- if (ts.hasProperty(labelIndexMap, name.text)) {
- return false;
- }
- labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1;
- return true;
- }
- function pushImplicitLabel() {
- initializeReachabilityStateIfNecessary();
- var index = labelStack.push(1 /* Unintialized */) - 1;
- implicitLabels.push(index);
- return index;
- }
- function popNamedLabel(label, outerState) {
- var index = labelIndexMap[label.text];
- ts.Debug.assert(index !== undefined);
- ts.Debug.assert(labelStack.length == index + 1);
- labelIndexMap[label.text] = undefined;
- setCurrentStateAtLabel(labelStack.pop(), outerState, label);
- }
- function popImplicitLabel(implicitLabelIndex, outerState) {
- if (labelStack.length !== implicitLabelIndex + 1) {
- ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex);
- }
- var i = implicitLabels.pop();
- if (implicitLabelIndex !== i) {
- ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex);
- }
- setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined);
- }
- function setCurrentStateAtLabel(innerMergedState, outerState, label) {
- if (innerMergedState === 1 /* Unintialized */) {
- if (label && !options.allowUnusedLabels) {
- file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label));
- }
- currentReachabilityState = outerState;
- }
- else {
- currentReachabilityState = or(innerMergedState, outerState);
- }
- }
- function jumpToLabel(label, outerState) {
- initializeReachabilityStateIfNecessary();
- var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels);
- if (index === undefined) {
- // reference to unknown label or
- // break/continue used outside of loops
- return false;
- }
- var stateAtLabel = labelStack[index];
- labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState);
- return true;
- }
- function checkUnreachable(node) {
- switch (currentReachabilityState) {
- case 4 /* Unreachable */:
- var reportError =
- // report error on all statements
- ts.isStatement(node) ||
- // report error on class declarations
- node.kind === 214 /* ClassDeclaration */ ||
- // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
- (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
- // report error on regular enums and const enums if preserveConstEnums is set
- (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
- if (reportError) {
- currentReachabilityState = 8 /* ReportedUnreachable */;
- // unreachable code is reported if
- // - user has explicitly asked about it AND
- // - statement is in not ambient context (statements in ambient context is already an error
- // so we should not report extras) AND
- // - node is not variable statement OR
- // - node is block scoped variable statement OR
- // - node is not block scoped variable statement and at least one variable declaration has initializer
- // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
- // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
- var reportUnreachableCode = !options.allowUnreachableCode &&
- !ts.isInAmbientContext(node) &&
- (node.kind !== 193 /* VariableStatement */ ||
- ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ ||
- ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
- if (reportUnreachableCode) {
- errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected);
- }
- }
- case 8 /* ReportedUnreachable */:
- return true;
- default:
- return false;
- }
- function shouldReportErrorOnModuleDeclaration(node) {
- var instanceState = getModuleInstanceState(node);
- return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums);
- }
- }
- function initializeReachabilityStateIfNecessary() {
- if (labelIndexMap) {
- return;
- }
- currentReachabilityState = 2 /* Reachable */;
- labelIndexMap = {};
- labelStack = [];
- implicitLabels = [];
- }
- }
-})(ts || (ts = {}));
-///
///
/* @internal */
var ts;
@@ -5812,6 +4503,10 @@ var ts;
return file.externalModuleIndicator !== undefined;
}
ts.isExternalModule = isExternalModule;
+ function isExternalOrCommonJsModule(file) {
+ return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
+ }
+ ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
function isDeclarationFile(file) {
return (file.flags & 4096 /* DeclarationFile */) !== 0;
}
@@ -5865,19 +4560,27 @@ var ts;
return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
+ function getLeadingCommentRangesOfNodeFromText(node, text) {
+ return ts.getLeadingCommentRanges(text, node.pos);
+ }
+ ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText;
function getJsDocComments(node, sourceFileOfNode) {
+ return getJsDocCommentsFromText(node, sourceFileOfNode.text);
+ }
+ ts.getJsDocComments = getJsDocComments;
+ function getJsDocCommentsFromText(node, text) {
var commentRanges = (node.kind === 138 /* Parameter */ || node.kind === 137 /* TypeParameter */) ?
- ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
- getLeadingCommentRangesOfNode(node, sourceFileOfNode);
+ ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
+ getLeadingCommentRangesOfNodeFromText(node, text);
return ts.filter(commentRanges, isJsDocComment);
function isJsDocComment(comment) {
// True if the comment starts with '/**' but not if it is '/**/'
- return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
- sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
+ return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
}
}
- ts.getJsDocComments = getJsDocComments;
+ ts.getJsDocCommentsFromText = getJsDocCommentsFromText;
ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/;
ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
function isTypeNode(node) {
@@ -6464,6 +5167,57 @@ var ts;
return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */;
}
ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
+ function isSourceFileJavaScript(file) {
+ return isInJavaScriptFile(file);
+ }
+ ts.isSourceFileJavaScript = isSourceFileJavaScript;
+ function isInJavaScriptFile(node) {
+ return node && !!(node.parserContextFlags & 32 /* JavaScriptFile */);
+ }
+ ts.isInJavaScriptFile = isInJavaScriptFile;
+ /**
+ * Returns true if the node is a CallExpression to the identifier 'require' with
+ * exactly one string literal argument.
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isRequireCall(expression) {
+ // of the form 'require("name")'
+ return expression.kind === 168 /* CallExpression */ &&
+ expression.expression.kind === 69 /* Identifier */ &&
+ expression.expression.text === "require" &&
+ expression.arguments.length === 1 &&
+ expression.arguments[0].kind === 9 /* StringLiteral */;
+ }
+ ts.isRequireCall = isRequireCall;
+ /**
+ * Returns true if the node is an assignment to a property on the identifier 'exports'.
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isExportsPropertyAssignment(expression) {
+ // of the form 'exports.name = expr' where 'name' and 'expr' are arbitrary
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181 /* BinaryExpression */) &&
+ (expression.operatorToken.kind === 56 /* EqualsToken */) &&
+ (expression.left.kind === 166 /* PropertyAccessExpression */) &&
+ (expression.left.expression.kind === 69 /* Identifier */) &&
+ ((expression.left.expression).text === "exports");
+ }
+ ts.isExportsPropertyAssignment = isExportsPropertyAssignment;
+ /**
+ * Returns true if the node is an assignment to the property access expression 'module.exports'.
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isModuleExportsAssignment(expression) {
+ // of the form 'module.exports = expr' where 'expr' is arbitrary
+ return isInJavaScriptFile(expression) &&
+ (expression.kind === 181 /* BinaryExpression */) &&
+ (expression.operatorToken.kind === 56 /* EqualsToken */) &&
+ (expression.left.kind === 166 /* PropertyAccessExpression */) &&
+ (expression.left.expression.kind === 69 /* Identifier */) &&
+ ((expression.left.expression).text === "module") &&
+ (expression.left.name.text === "exports");
+ }
+ ts.isModuleExportsAssignment = isModuleExportsAssignment;
function getExternalModuleName(node) {
if (node.kind === 222 /* ImportDeclaration */) {
return node.moduleSpecifier;
@@ -6791,8 +5545,8 @@ var ts;
function getFileReferenceFromReferencePath(comment, commentRange) {
var simpleReferenceRegEx = /^\/\/\/\s*/gim;
- if (simpleReferenceRegEx.exec(comment)) {
- if (isNoDefaultLibRegEx.exec(comment)) {
+ if (simpleReferenceRegEx.test(comment)) {
+ if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
@@ -6834,6 +5588,10 @@ var ts;
return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node);
}
ts.isAsyncFunctionLike = isAsyncFunctionLike;
+ function isStringOrNumericLiteral(kind) {
+ return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */;
+ }
+ ts.isStringOrNumericLiteral = isStringOrNumericLiteral;
/**
* A declaration has a dynamic name if both of the following are true:
* 1. The declaration has a computed property name
@@ -6842,11 +5600,15 @@ var ts;
* Symbol.
*/
function hasDynamicName(declaration) {
- return declaration.name &&
- declaration.name.kind === 136 /* ComputedPropertyName */ &&
- !isWellKnownSymbolSyntactically(declaration.name.expression);
+ return declaration.name && isDynamicName(declaration.name);
}
ts.hasDynamicName = hasDynamicName;
+ function isDynamicName(name) {
+ return name.kind === 136 /* ComputedPropertyName */ &&
+ !isStringOrNumericLiteral(name.expression.kind) &&
+ !isWellKnownSymbolSyntactically(name.expression);
+ }
+ ts.isDynamicName = isDynamicName;
/**
* Checks if the expression is of the form:
* Symbol.name
@@ -7087,11 +5849,11 @@ var ts;
}
ts.getIndentSize = getIndentSize;
function createTextWriter(newLine) {
- var output = "";
- var indent = 0;
- var lineStart = true;
- var lineCount = 0;
- var linePos = 0;
+ var output;
+ var indent;
+ var lineStart;
+ var lineCount;
+ var linePos;
function write(s) {
if (s && s.length) {
if (lineStart) {
@@ -7101,6 +5863,13 @@ var ts;
output += s;
}
}
+ function reset() {
+ output = "";
+ indent = 0;
+ lineStart = true;
+ lineCount = 0;
+ linePos = 0;
+ }
function rawWrite(s) {
if (s !== undefined) {
if (lineStart) {
@@ -7127,9 +5896,10 @@ var ts;
lineStart = true;
}
}
- function writeTextOfNode(sourceFile, node) {
- write(getSourceTextOfNodeFromSourceFile(sourceFile, node));
+ function writeTextOfNode(text, node) {
+ write(getTextOfNodeFromSourceText(text, node));
}
+ reset();
return {
write: write,
rawWrite: rawWrite,
@@ -7142,10 +5912,20 @@ var ts;
getTextPos: function () { return output.length; },
getLine: function () { return lineCount + 1; },
getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; },
- getText: function () { return output; }
+ getText: function () { return output; },
+ reset: reset
};
}
ts.createTextWriter = createTextWriter;
+ /**
+ * Resolves a local path to a path which is absolute to the base of the emit
+ */
+ function getExternalModuleNameFromPath(host, fileName) {
+ var dir = host.getCurrentDirectory();
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, /*isAbsolutePathAnUrl*/ false);
+ return ts.removeFileExtension(relativePath);
+ }
+ ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
var compilerOptions = host.getCompilerOptions();
var emitOutputFilePathWithoutExtension;
@@ -7174,6 +5954,10 @@ var ts;
return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
ts.getLineOfLocalPosition = getLineOfLocalPosition;
+ function getLineOfLocalPositionFromLineMap(lineMap, pos) {
+ return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
+ }
+ ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
function getFirstConstructorWithBody(node) {
return ts.forEach(node.members, function (member) {
if (member.kind === 144 /* Constructor */ && nodeIsPresent(member.body)) {
@@ -7246,22 +6030,22 @@ var ts;
};
}
ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
- function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) {
+ function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
// If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
- getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) {
+ getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
}
}
ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
- function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) {
+ function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) {
var emitLeadingSpace = !trailingSeparator;
ts.forEach(comments, function (comment) {
if (emitLeadingSpace) {
writer.write(" ");
emitLeadingSpace = false;
}
- writeComment(currentSourceFile, writer, comment, newLine);
+ writeComment(text, lineMap, writer, comment, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
@@ -7279,7 +6063,7 @@ var ts;
* Detached comment is a comment at the top of file or function body that is separated from
* the next statement by space.
*/
- function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) {
+ function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
var leadingComments;
var currentDetachedCommentInfo;
if (removeComments) {
@@ -7289,12 +6073,12 @@ var ts;
//
// var x = 10;
if (node.pos === 0) {
- leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment);
+ leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment);
}
}
else {
// removeComments is false, just get detached as normal and bypass the process to filter comment
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ leadingComments = ts.getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
var detachedComments = [];
@@ -7302,8 +6086,8 @@ var ts;
for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
var comment = leadingComments_1[_i];
if (lastComment) {
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end);
- var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos);
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
+ var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
if (commentLine >= lastCommentLine + 2) {
// There was a blank line between the last comment and this comment. This
// comment is not part of the copyright comments. Return what we have so
@@ -7318,36 +6102,36 @@ var ts;
// All comments look like they could have been part of the copyright header. Make
// sure there is at least one blank line between it and the node. If not, it's not
// a copyright header.
- var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end);
- var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));
+ var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end);
+ var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
// Valid detachedComments
- emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
- emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
+ emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
+ emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end };
}
}
}
return currentDetachedCommentInfo;
function isPinnedComment(comment) {
- return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;
+ return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;
}
}
ts.emitDetachedComments = emitDetachedComments;
- function writeCommentRange(currentSourceFile, writer, comment, newLine) {
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) {
- var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
- var lineCount = ts.getLineStarts(currentSourceFile).length;
+ function writeCommentRange(text, lineMap, writer, comment, newLine) {
+ if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) {
+ var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos);
+ var lineCount = lineMap.length;
var firstCommentLineIndent;
for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
var nextLineStart = (currentLine + 1) === lineCount
- ? currentSourceFile.text.length + 1
- : getStartPositionOfLine(currentLine + 1, currentSourceFile);
+ ? text.length + 1
+ : lineMap[currentLine + 1];
if (pos !== comment.pos) {
// If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
- firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
+ firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos);
}
// These are number of spaces writer is going to write at current indent
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
@@ -7365,7 +6149,7 @@ var ts;
// More right indented comment */ --4 = 8 - 4 + 11
// class c { }
// }
- var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
+ var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
@@ -7383,45 +6167,45 @@ var ts;
}
}
// Write the comment line text
- writeTrimmedCurrentLine(pos, nextLineStart);
+ writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
// Single line comment of style //....
- writer.write(currentSourceFile.text.substring(comment.pos, comment.end));
- }
- function writeTrimmedCurrentLine(pos, nextLineStart) {
- var end = Math.min(comment.end, nextLineStart - 1);
- var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
- if (currentLineText) {
- // trimmed forward and ending spaces text
- writer.write(currentLineText);
- if (end !== comment.end) {
- writer.writeLine();
- }
- }
- else {
- // Empty string - make sure we write empty line
- writer.writeLiteral(newLine);
- }
- }
- function calculateIndent(pos, end) {
- var currentLineIndent = 0;
- for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
- if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) {
- // Tabs = TabSize = indent size and go to next tabStop
- currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
- }
- else {
- // Single space
- currentLineIndent++;
- }
- }
- return currentLineIndent;
+ writer.write(text.substring(comment.pos, comment.end));
}
}
ts.writeCommentRange = writeCommentRange;
+ function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) {
+ var end = Math.min(comment.end, nextLineStart - 1);
+ var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
+ if (currentLineText) {
+ // trimmed forward and ending spaces text
+ writer.write(currentLineText);
+ if (end !== comment.end) {
+ writer.writeLine();
+ }
+ }
+ else {
+ // Empty string - make sure we write empty line
+ writer.writeLiteral(newLine);
+ }
+ }
+ function calculateIndent(text, pos, end) {
+ var currentLineIndent = 0;
+ for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) {
+ if (text.charCodeAt(pos) === 9 /* tab */) {
+ // Tabs = TabSize = indent size and go to next tabStop
+ currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
+ }
+ else {
+ // Single space
+ currentLineIndent++;
+ }
+ }
+ return currentLineIndent;
+ }
function modifierToFlag(token) {
switch (token) {
case 113 /* StaticKeyword */: return 64 /* Static */;
@@ -7517,14 +6301,14 @@ var ts;
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
- function isJavaScript(fileName) {
- return ts.fileExtensionIs(fileName, ".js");
+ function hasJavaScriptFileExtension(fileName) {
+ return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isJavaScript = isJavaScript;
- function isTsx(fileName) {
- return ts.fileExtensionIs(fileName, ".tsx");
+ ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function allowsJsxExpressions(fileName) {
+ return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx");
}
- ts.isTsx = isTsx;
+ ts.allowsJsxExpressions = allowsJsxExpressions;
/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* representing the UTF-8 encoding of the character, and return the expanded char code list.
@@ -7835,18 +6619,20 @@ var ts;
}
ts.getTypeParameterOwner = getTypeParameterOwner;
})(ts || (ts = {}));
-///
///
+///
var ts;
(function (ts) {
- var nodeConstructors = new Array(272 /* Count */);
/* @internal */ ts.parseTime = 0;
- function getNodeConstructor(kind) {
- return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind));
- }
- ts.getNodeConstructor = getNodeConstructor;
+ var NodeConstructor;
+ var SourceFileConstructor;
function createNode(kind, pos, end) {
- return new (getNodeConstructor(kind))(pos, end);
+ if (kind === 248 /* SourceFile */) {
+ return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
+ }
+ else {
+ return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
+ }
}
ts.createNode = createNode;
function visitNode(cbNode, node) {
@@ -8269,6 +7055,9 @@ var ts;
// up by avoiding the cost of creating/compiling scanners over and over again.
var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 1 /* DisallowIn */ | 4 /* Decorator */;
+ // capture constructors in 'initializeState' to avoid null checks
+ var NodeConstructor;
+ var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
var syntaxCursor;
@@ -8354,13 +7143,16 @@ var ts;
// attached to the EOF token.
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) {
- initializeState(fileName, _sourceText, languageVersion, _syntaxCursor);
+ var isJavaScriptFile = ts.hasJavaScriptFileExtension(fileName) || _sourceText.lastIndexOf("// @language=javascript", 0) === 0;
+ initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes);
clearState();
return result;
}
Parser.parseSourceFile = parseSourceFile;
- function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) {
+ function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) {
+ NodeConstructor = ts.objectAllocator.getNodeConstructor();
+ SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
parseDiagnostics = [];
@@ -8368,13 +7160,13 @@ var ts;
identifiers = {};
identifierCount = 0;
nodeCount = 0;
- contextFlags = ts.isJavaScript(fileName) ? 32 /* JavaScriptFile */ : 0 /* None */;
+ contextFlags = isJavaScriptFile ? 32 /* JavaScriptFile */ : 0 /* None */;
parseErrorBeforeNextFinishedNode = false;
// Initialize and prime the scanner before parsing the source elements.
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
- scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 /* JSX */ : 0 /* Standard */);
+ scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 /* JSX */ : 0 /* Standard */);
}
function clearState() {
// Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
@@ -8389,6 +7181,9 @@ var ts;
}
function parseSourceFileWorker(fileName, languageVersion, setParentNodes) {
sourceFile = createSourceFile(fileName, languageVersion);
+ if (contextFlags & 32 /* JavaScriptFile */) {
+ sourceFile.parserContextFlags = 32 /* JavaScriptFile */;
+ }
// Prime the scanner.
token = nextToken();
processReferenceComments(sourceFile);
@@ -8406,7 +7201,7 @@ var ts;
// If this is a javascript file, proactively see if we can get JSDoc comments for
// relevant nodes in the file. We'll use these to provide typing informaion if they're
// available.
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
addJSDocComments();
}
return sourceFile;
@@ -8461,15 +7256,16 @@ var ts;
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion) {
- var sourceFile = createNode(248 /* SourceFile */, /*pos*/ 0);
- sourceFile.pos = 0;
- sourceFile.end = sourceText.length;
+ // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
+ // this is quite rare comparing to other nodes and createNode should be as fast as possible
+ var sourceFile = new SourceFileConstructor(248 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = ts.normalizePath(fileName);
sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0;
- sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */;
+ sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */;
return sourceFile;
}
function setContextFlag(val, flag) {
@@ -8734,12 +7530,13 @@ var ts;
return parseExpected(23 /* SemicolonToken */);
}
}
+ // note: this function creates only node
function createNode(kind, pos) {
nodeCount++;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
- return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos);
+ return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -8904,7 +7701,7 @@ var ts;
case 12 /* ObjectLiteralMembers */:
return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName();
case 9 /* ObjectBindingElements */:
- return isLiteralPropertyName();
+ return token === 19 /* OpenBracketToken */ || isLiteralPropertyName();
case 7 /* HeritageClauseElement */:
// If we see { } then only consume it as an expression if it is followed by , or {
// That way we won't consume the body of a class in its heritage clause.
@@ -9584,9 +8381,7 @@ var ts;
}
function parseParameterType() {
if (parseOptional(54 /* ColonToken */)) {
- return token === 9 /* StringLiteral */
- ? parseLiteralNode(/*internName*/ true)
- : parseType();
+ return parseType();
}
return undefined;
}
@@ -9917,6 +8712,8 @@ var ts;
// If these are followed by a dot, then parse these out as a dotted type reference instead.
var node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
+ case 9 /* StringLiteral */:
+ return parseLiteralNode(/*internName*/ true);
case 103 /* VoidKeyword */:
case 97 /* ThisKeyword */:
return parseTokenNode();
@@ -9946,6 +8743,7 @@ var ts;
case 19 /* OpenBracketToken */:
case 25 /* LessThanToken */:
case 92 /* NewKeyword */:
+ case 9 /* StringLiteral */:
return true;
case 17 /* OpenParenToken */:
// Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
@@ -10362,7 +9160,7 @@ var ts;
return 1 /* True */;
}
// This *could* be a parenthesized arrow function.
- // Return Unknown to let the caller know.
+ // Return Unknown to const the caller know.
return 2 /* Unknown */;
}
else {
@@ -10448,7 +9246,7 @@ var ts;
// user meant to supply a block. For example, if the user wrote:
//
// a =>
- // let v = 0;
+ // const v = 0;
// }
//
// they may be missing an open brace. Check to see if that's the case so we can
@@ -10664,7 +9462,6 @@ var ts;
var unaryOperator = token;
var simpleUnaryExpression = parseSimpleUnaryExpression();
if (token === 38 /* AsteriskAsteriskToken */) {
- var diagnostic;
var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) {
parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
@@ -11868,7 +10665,6 @@ var ts;
}
function parseObjectBindingElement() {
var node = createNode(163 /* BindingElement */);
- // TODO(andersh): Handle computed properties
var tokenIsIdentifier = isIdentifier();
var propertyName = parsePropertyName();
if (tokenIsIdentifier && token !== 54 /* ColonToken */) {
@@ -12691,7 +11487,7 @@ var ts;
}
JSDocParser.isJSDocType = isJSDocType;
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined);
+ initializeState("file.js", content, 2 /* Latest */, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined);
var jsDocTypeExpression = parseJSDocTypeExpression(start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -12786,6 +11582,7 @@ var ts;
case 103 /* VoidKeyword */:
return parseTokenNode();
}
+ // TODO (drosen): Parse string literal types in JSDoc as well.
return parseJSDocTypeReference();
}
function parseJSDocThisType() {
@@ -12957,7 +11754,7 @@ var ts;
}
}
function parseIsolatedJSDocComment(content, start, length) {
- initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined);
+ initializeState("file.js", content, 2 /* Latest */, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined);
var jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -13682,6 +12479,1372 @@ var ts;
})(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
})(ts || (ts = {}));
+///
+///
+/* @internal */
+var ts;
+(function (ts) {
+ ts.bindTime = 0;
+ (function (ModuleInstanceState) {
+ ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
+ ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
+ ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
+ })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
+ var ModuleInstanceState = ts.ModuleInstanceState;
+ var Reachability;
+ (function (Reachability) {
+ Reachability[Reachability["Unintialized"] = 1] = "Unintialized";
+ Reachability[Reachability["Reachable"] = 2] = "Reachable";
+ Reachability[Reachability["Unreachable"] = 4] = "Unreachable";
+ Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable";
+ })(Reachability || (Reachability = {}));
+ function or(state1, state2) {
+ return (state1 | state2) & 2 /* Reachable */
+ ? 2 /* Reachable */
+ : (state1 & state2) & 8 /* ReportedUnreachable */
+ ? 8 /* ReportedUnreachable */
+ : 4 /* Unreachable */;
+ }
+ function getModuleInstanceState(node) {
+ // A module is uninstantiated if it contains only
+ // 1. interface declarations, type alias declarations
+ if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) {
+ return 0 /* NonInstantiated */;
+ }
+ else if (ts.isConstEnumDeclaration(node)) {
+ return 2 /* ConstEnumOnly */;
+ }
+ else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) {
+ return 0 /* NonInstantiated */;
+ }
+ else if (node.kind === 219 /* ModuleBlock */) {
+ var state = 0 /* NonInstantiated */;
+ ts.forEachChild(node, function (n) {
+ switch (getModuleInstanceState(n)) {
+ case 0 /* NonInstantiated */:
+ // child is non-instantiated - continue searching
+ return false;
+ case 2 /* ConstEnumOnly */:
+ // child is const enum only - record state and continue searching
+ state = 2 /* ConstEnumOnly */;
+ return false;
+ case 1 /* Instantiated */:
+ // child is instantiated - record state and stop
+ state = 1 /* Instantiated */;
+ return true;
+ }
+ });
+ return state;
+ }
+ else if (node.kind === 218 /* ModuleDeclaration */) {
+ return getModuleInstanceState(node.body);
+ }
+ else {
+ return 1 /* Instantiated */;
+ }
+ }
+ ts.getModuleInstanceState = getModuleInstanceState;
+ var ContainerFlags;
+ (function (ContainerFlags) {
+ // The current node is not a container, and no container manipulation should happen before
+ // recursing into it.
+ ContainerFlags[ContainerFlags["None"] = 0] = "None";
+ // The current node is a container. It should be set as the current container (and block-
+ // container) before recursing into it. The current node does not have locals. Examples:
+ //
+ // Classes, ObjectLiterals, TypeLiterals, Interfaces...
+ ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
+ // The current node is a block-scoped-container. It should be set as the current block-
+ // container before recursing into it. Examples:
+ //
+ // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
+ ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
+ ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals";
+ // If the current node is a container that also container that also contains locals. Examples:
+ //
+ // Functions, Methods, Modules, Source-files.
+ ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals";
+ })(ContainerFlags || (ContainerFlags = {}));
+ var binder = createBinder();
+ function bindSourceFile(file, options) {
+ var start = new Date().getTime();
+ binder(file, options);
+ ts.bindTime += new Date().getTime() - start;
+ }
+ ts.bindSourceFile = bindSourceFile;
+ function createBinder() {
+ var file;
+ var options;
+ var parent;
+ var container;
+ var blockScopeContainer;
+ var lastContainer;
+ var seenThisKeyword;
+ // state used by reachability checks
+ var hasExplicitReturn;
+ var currentReachabilityState;
+ var labelStack;
+ var labelIndexMap;
+ var implicitLabels;
+ // If this file is an external module, then it is automatically in strict-mode according to
+ // ES6. If it is not an external module, then we'll determine if it is in strict mode or
+ // not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
+ var inStrictMode;
+ var symbolCount = 0;
+ var Symbol;
+ var classifiableNames;
+ function bindSourceFile(f, opts) {
+ file = f;
+ options = opts;
+ inStrictMode = !!file.externalModuleIndicator;
+ classifiableNames = {};
+ Symbol = ts.objectAllocator.getSymbolConstructor();
+ if (!file.locals) {
+ bind(file);
+ file.symbolCount = symbolCount;
+ file.classifiableNames = classifiableNames;
+ }
+ parent = undefined;
+ container = undefined;
+ blockScopeContainer = undefined;
+ lastContainer = undefined;
+ seenThisKeyword = false;
+ hasExplicitReturn = false;
+ labelStack = undefined;
+ labelIndexMap = undefined;
+ implicitLabels = undefined;
+ }
+ return bindSourceFile;
+ function createSymbol(flags, name) {
+ symbolCount++;
+ return new Symbol(flags, name);
+ }
+ function addDeclarationToSymbol(symbol, node, symbolFlags) {
+ symbol.flags |= symbolFlags;
+ node.symbol = symbol;
+ if (!symbol.declarations) {
+ symbol.declarations = [];
+ }
+ symbol.declarations.push(node);
+ if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) {
+ symbol.exports = {};
+ }
+ if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) {
+ symbol.members = {};
+ }
+ if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) {
+ symbol.valueDeclaration = node;
+ }
+ }
+ // Should not be called on a declaration with a computed property name,
+ // unless it is a well known Symbol.
+ function getDeclarationName(node) {
+ if (node.name) {
+ if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
+ return "\"" + node.name.text + "\"";
+ }
+ if (node.name.kind === 136 /* ComputedPropertyName */) {
+ var nameExpression = node.name.expression;
+ // treat computed property names where expression is string/numeric literal as just string/numeric literal
+ if (ts.isStringOrNumericLiteral(nameExpression.kind)) {
+ return nameExpression.text;
+ }
+ ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
+ return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
+ }
+ return node.name.text;
+ }
+ switch (node.kind) {
+ case 144 /* Constructor */:
+ return "__constructor";
+ case 152 /* FunctionType */:
+ case 147 /* CallSignature */:
+ return "__call";
+ case 153 /* ConstructorType */:
+ case 148 /* ConstructSignature */:
+ return "__new";
+ case 149 /* IndexSignature */:
+ return "__index";
+ case 228 /* ExportDeclaration */:
+ return "__export";
+ case 227 /* ExportAssignment */:
+ return node.isExportEquals ? "export=" : "default";
+ case 181 /* BinaryExpression */:
+ // Binary expression case is for JS module 'module.exports = expr'
+ return "export=";
+ case 213 /* FunctionDeclaration */:
+ case 214 /* ClassDeclaration */:
+ return node.flags & 512 /* Default */ ? "default" : undefined;
+ }
+ }
+ function getDisplayName(node) {
+ return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node);
+ }
+ /**
+ * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
+ * @param symbolTable - The symbol table which node will be added to.
+ * @param parent - node's parent declaration.
+ * @param node - The declaration to be added to the symbol table
+ * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
+ * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
+ */
+ function declareSymbol(symbolTable, parent, node, includes, excludes) {
+ ts.Debug.assert(!ts.hasDynamicName(node));
+ var isDefaultExport = node.flags & 512 /* Default */;
+ // The exported symbol for an export default function/class node is always named "default"
+ var name = isDefaultExport && parent ? "default" : getDeclarationName(node);
+ var symbol;
+ if (name !== undefined) {
+ // Check and see if the symbol table already has a symbol with this name. If not,
+ // create a new symbol with this name and add it to the table. Note that we don't
+ // give the new symbol any flags *yet*. This ensures that it will not conflict
+ // with the 'excludes' flags we pass in.
+ //
+ // If we do get an existing symbol, see if it conflicts with the new symbol we're
+ // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
+ // the same symbol table. If we have a conflict, report the issue on each
+ // declaration we have for this symbol, and then create a new symbol for this
+ // declaration.
+ //
+ // If we created a new symbol, either because we didn't have a symbol with this name
+ // in the symbol table, or we conflicted with an existing symbol, then just add this
+ // node as the sole declaration of the new symbol.
+ //
+ // Otherwise, we'll be merging into a compatible existing symbol (for example when
+ // you have multiple 'vars' with the same name in the same container). In this case
+ // just add this node into the declarations list of the symbol.
+ symbol = ts.hasProperty(symbolTable, name)
+ ? symbolTable[name]
+ : (symbolTable[name] = createSymbol(0 /* None */, name));
+ if (name && (includes & 788448 /* Classifiable */)) {
+ classifiableNames[name] = name;
+ }
+ if (symbol.flags & excludes) {
+ if (node.name) {
+ node.name.parent = node;
+ }
+ // Report errors every position with duplicate declaration
+ // Report errors on previous encountered declarations
+ var message = symbol.flags & 2 /* BlockScopedVariable */
+ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
+ : ts.Diagnostics.Duplicate_identifier_0;
+ ts.forEach(symbol.declarations, function (declaration) {
+ if (declaration.flags & 512 /* Default */) {
+ message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
+ }
+ });
+ ts.forEach(symbol.declarations, function (declaration) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
+ });
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
+ symbol = createSymbol(0 /* None */, name);
+ }
+ }
+ else {
+ symbol = createSymbol(0 /* None */, "__missing");
+ }
+ addDeclarationToSymbol(symbol, node, includes);
+ symbol.parent = parent;
+ return symbol;
+ }
+ function declareModuleMember(node, symbolFlags, symbolExcludes) {
+ var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */;
+ if (symbolFlags & 8388608 /* Alias */) {
+ if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) {
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ else {
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ else {
+ // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue,
+ // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
+ // on it. There are 2 main reasons:
+ //
+ // 1. We treat locals and exports of the same name as mutually exclusive within a container.
+ // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
+ // with the same name in the same container.
+ // TODO: Make this a more specific error and decouple it from the exclusion logic.
+ // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
+ // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
+ // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
+ if (hasExportModifier || container.flags & 131072 /* ExportContext */) {
+ var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) |
+ (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) |
+ (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0);
+ var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
+ local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ node.localSymbol = local;
+ return local;
+ }
+ else {
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ }
+ // All container nodes are kept on a linked list in declaration order. This list is used by
+ // the getLocalNameOfContainer function in the type checker to validate that the local name
+ // used for a container is unique.
+ function bindChildren(node) {
+ // Before we recurse into a node's chilren, we first save the existing parent, container
+ // and block-container. Then after we pop out of processing the children, we restore
+ // these saved values.
+ var saveParent = parent;
+ var saveContainer = container;
+ var savedBlockScopeContainer = blockScopeContainer;
+ // This node will now be set as the parent of all of its children as we recurse into them.
+ parent = node;
+ // Depending on what kind of node this is, we may have to adjust the current container
+ // and block-container. If the current node is a container, then it is automatically
+ // considered the current block-container as well. Also, for containers that we know
+ // may contain locals, we proactively initialize the .locals field. We do this because
+ // it's highly likely that the .locals will be needed to place some child in (for example,
+ // a parameter, or variable declaration).
+ //
+ // However, we do not proactively create the .locals for block-containers because it's
+ // totally normal and common for block-containers to never actually have a block-scoped
+ // variable in them. We don't want to end up allocating an object for every 'block' we
+ // run into when most of them won't be necessary.
+ //
+ // Finally, if this is a block-container, then we clear out any existing .locals object
+ // it may contain within it. This happens in incremental scenarios. Because we can be
+ // reusing a node from a previous compilation, that node may have had 'locals' created
+ // for it. We must clear this so we don't accidently move any stale data forward from
+ // a previous compilation.
+ var containerFlags = getContainerFlags(node);
+ if (containerFlags & 1 /* IsContainer */) {
+ container = blockScopeContainer = node;
+ if (containerFlags & 4 /* HasLocals */) {
+ container.locals = {};
+ }
+ addToContainerChain(container);
+ }
+ else if (containerFlags & 2 /* IsBlockScopedContainer */) {
+ blockScopeContainer = node;
+ blockScopeContainer.locals = undefined;
+ }
+ var savedReachabilityState;
+ var savedLabelStack;
+ var savedLabels;
+ var savedImplicitLabels;
+ var savedHasExplicitReturn;
+ var kind = node.kind;
+ var flags = node.flags;
+ // reset all reachability check related flags on node (for incremental scenarios)
+ flags &= ~1572864 /* ReachabilityCheckFlags */;
+ if (kind === 215 /* InterfaceDeclaration */) {
+ seenThisKeyword = false;
+ }
+ var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind);
+ if (saveState) {
+ savedReachabilityState = currentReachabilityState;
+ savedLabelStack = labelStack;
+ savedLabels = labelIndexMap;
+ savedImplicitLabels = implicitLabels;
+ savedHasExplicitReturn = hasExplicitReturn;
+ currentReachabilityState = 2 /* Reachable */;
+ hasExplicitReturn = false;
+ labelStack = labelIndexMap = implicitLabels = undefined;
+ }
+ bindReachableStatement(node);
+ if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) {
+ flags |= 524288 /* HasImplicitReturn */;
+ if (hasExplicitReturn) {
+ flags |= 1048576 /* HasExplicitReturn */;
+ }
+ }
+ if (kind === 215 /* InterfaceDeclaration */) {
+ flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */;
+ }
+ node.flags = flags;
+ if (saveState) {
+ hasExplicitReturn = savedHasExplicitReturn;
+ currentReachabilityState = savedReachabilityState;
+ labelStack = savedLabelStack;
+ labelIndexMap = savedLabels;
+ implicitLabels = savedImplicitLabels;
+ }
+ container = saveContainer;
+ parent = saveParent;
+ blockScopeContainer = savedBlockScopeContainer;
+ }
+ /**
+ * Returns true if node and its subnodes were successfully traversed.
+ * Returning false means that node was not examined and caller needs to dive into the node himself.
+ */
+ function bindReachableStatement(node) {
+ if (checkUnreachable(node)) {
+ ts.forEachChild(node, bind);
+ return;
+ }
+ switch (node.kind) {
+ case 198 /* WhileStatement */:
+ bindWhileStatement(node);
+ break;
+ case 197 /* DoStatement */:
+ bindDoStatement(node);
+ break;
+ case 199 /* ForStatement */:
+ bindForStatement(node);
+ break;
+ case 200 /* ForInStatement */:
+ case 201 /* ForOfStatement */:
+ bindForInOrForOfStatement(node);
+ break;
+ case 196 /* IfStatement */:
+ bindIfStatement(node);
+ break;
+ case 204 /* ReturnStatement */:
+ case 208 /* ThrowStatement */:
+ bindReturnOrThrow(node);
+ break;
+ case 203 /* BreakStatement */:
+ case 202 /* ContinueStatement */:
+ bindBreakOrContinueStatement(node);
+ break;
+ case 209 /* TryStatement */:
+ bindTryStatement(node);
+ break;
+ case 206 /* SwitchStatement */:
+ bindSwitchStatement(node);
+ break;
+ case 220 /* CaseBlock */:
+ bindCaseBlock(node);
+ break;
+ case 207 /* LabeledStatement */:
+ bindLabeledStatement(node);
+ break;
+ default:
+ ts.forEachChild(node, bind);
+ break;
+ }
+ }
+ function bindWhileStatement(n) {
+ var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ // bind expressions (don't affect reachability)
+ bind(n.expression);
+ currentReachabilityState = preWhileState;
+ var postWhileLabel = pushImplicitLabel();
+ bind(n.statement);
+ popImplicitLabel(postWhileLabel, postWhileState);
+ }
+ function bindDoStatement(n) {
+ var preDoState = currentReachabilityState;
+ var postDoLabel = pushImplicitLabel();
+ bind(n.statement);
+ var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState;
+ popImplicitLabel(postDoLabel, postDoState);
+ // bind expressions (don't affect reachability)
+ bind(n.expression);
+ }
+ function bindForStatement(n) {
+ var preForState = currentReachabilityState;
+ var postForLabel = pushImplicitLabel();
+ // bind expressions (don't affect reachability)
+ bind(n.initializer);
+ bind(n.condition);
+ bind(n.incrementor);
+ bind(n.statement);
+ // for statement is considered infinite when it condition is either omitted or is true keyword
+ // - for(..;;..)
+ // - for(..;true;..)
+ var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */);
+ var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState;
+ popImplicitLabel(postForLabel, postForState);
+ }
+ function bindForInOrForOfStatement(n) {
+ var preStatementState = currentReachabilityState;
+ var postStatementLabel = pushImplicitLabel();
+ // bind expressions (don't affect reachability)
+ bind(n.initializer);
+ bind(n.expression);
+ bind(n.statement);
+ popImplicitLabel(postStatementLabel, preStatementState);
+ }
+ function bindIfStatement(n) {
+ // denotes reachability state when entering 'thenStatement' part of the if statement:
+ // i.e. if condition is false then thenStatement is unreachable
+ var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ // denotes reachability state when entering 'elseStatement':
+ // i.e. if condition is true then elseStatement is unreachable
+ var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState;
+ currentReachabilityState = ifTrueState;
+ // bind expression (don't affect reachability)
+ bind(n.expression);
+ bind(n.thenStatement);
+ if (n.elseStatement) {
+ var preElseState = currentReachabilityState;
+ currentReachabilityState = ifFalseState;
+ bind(n.elseStatement);
+ currentReachabilityState = or(currentReachabilityState, preElseState);
+ }
+ else {
+ currentReachabilityState = or(currentReachabilityState, ifFalseState);
+ }
+ }
+ function bindReturnOrThrow(n) {
+ // bind expression (don't affect reachability)
+ bind(n.expression);
+ if (n.kind === 204 /* ReturnStatement */) {
+ hasExplicitReturn = true;
+ }
+ currentReachabilityState = 4 /* Unreachable */;
+ }
+ function bindBreakOrContinueStatement(n) {
+ // call bind on label (don't affect reachability)
+ bind(n.label);
+ // for continue case touch label so it will be marked a used
+ var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */);
+ if (isValidJump) {
+ currentReachabilityState = 4 /* Unreachable */;
+ }
+ }
+ function bindTryStatement(n) {
+ // catch\finally blocks has the same reachability as try block
+ var preTryState = currentReachabilityState;
+ bind(n.tryBlock);
+ var postTryState = currentReachabilityState;
+ currentReachabilityState = preTryState;
+ bind(n.catchClause);
+ var postCatchState = currentReachabilityState;
+ currentReachabilityState = preTryState;
+ bind(n.finallyBlock);
+ // post catch/finally state is reachable if
+ // - post try state is reachable - control flow can fall out of try block
+ // - post catch state is reachable - control flow can fall out of catch block
+ currentReachabilityState = or(postTryState, postCatchState);
+ }
+ function bindSwitchStatement(n) {
+ var preSwitchState = currentReachabilityState;
+ var postSwitchLabel = pushImplicitLabel();
+ // bind expression (don't affect reachability)
+ bind(n.expression);
+ bind(n.caseBlock);
+ var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; });
+ // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case
+ var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState;
+ popImplicitLabel(postSwitchLabel, postSwitchState);
+ }
+ function bindCaseBlock(n) {
+ var startState = currentReachabilityState;
+ for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) {
+ var clause = _a[_i];
+ currentReachabilityState = startState;
+ bind(clause);
+ if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) {
+ errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
+ }
+ }
+ }
+ function bindLabeledStatement(n) {
+ // call bind on label (don't affect reachability)
+ bind(n.label);
+ var ok = pushNamedLabel(n.label);
+ bind(n.statement);
+ if (ok) {
+ popNamedLabel(n.label, currentReachabilityState);
+ }
+ }
+ function getContainerFlags(node) {
+ switch (node.kind) {
+ case 186 /* ClassExpression */:
+ case 214 /* ClassDeclaration */:
+ case 215 /* InterfaceDeclaration */:
+ case 217 /* EnumDeclaration */:
+ case 155 /* TypeLiteral */:
+ case 165 /* ObjectLiteralExpression */:
+ return 1 /* IsContainer */;
+ case 147 /* CallSignature */:
+ case 148 /* ConstructSignature */:
+ case 149 /* IndexSignature */:
+ case 143 /* MethodDeclaration */:
+ case 142 /* MethodSignature */:
+ case 213 /* FunctionDeclaration */:
+ case 144 /* Constructor */:
+ case 145 /* GetAccessor */:
+ case 146 /* SetAccessor */:
+ case 152 /* FunctionType */:
+ case 153 /* ConstructorType */:
+ case 173 /* FunctionExpression */:
+ case 174 /* ArrowFunction */:
+ case 218 /* ModuleDeclaration */:
+ case 248 /* SourceFile */:
+ case 216 /* TypeAliasDeclaration */:
+ return 5 /* IsContainerWithLocals */;
+ case 244 /* CatchClause */:
+ case 199 /* ForStatement */:
+ case 200 /* ForInStatement */:
+ case 201 /* ForOfStatement */:
+ case 220 /* CaseBlock */:
+ return 2 /* IsBlockScopedContainer */;
+ case 192 /* Block */:
+ // do not treat blocks directly inside a function as a block-scoped-container.
+ // Locals that reside in this block should go to the function locals. Othewise 'x'
+ // would not appear to be a redeclaration of a block scoped local in the following
+ // example:
+ //
+ // function foo() {
+ // var x;
+ // let x;
+ // }
+ //
+ // If we placed 'var x' into the function locals and 'let x' into the locals of
+ // the block, then there would be no collision.
+ //
+ // By not creating a new block-scoped-container here, we ensure that both 'var x'
+ // and 'let x' go into the Function-container's locals, and we do get a collision
+ // conflict.
+ return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
+ }
+ return 0 /* None */;
+ }
+ function addToContainerChain(next) {
+ if (lastContainer) {
+ lastContainer.nextContainer = next;
+ }
+ lastContainer = next;
+ }
+ function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
+ // Just call this directly so that the return type of this function stays "void".
+ declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes);
+ }
+ function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) {
+ switch (container.kind) {
+ // Modules, source files, and classes need specialized handling for how their
+ // members are declared (for example, a member of a class will go into a specific
+ // symbol table depending on if it is static or not). We defer to specialized
+ // handlers to take care of declaring these child members.
+ case 218 /* ModuleDeclaration */:
+ return declareModuleMember(node, symbolFlags, symbolExcludes);
+ case 248 /* SourceFile */:
+ return declareSourceFileMember(node, symbolFlags, symbolExcludes);
+ case 186 /* ClassExpression */:
+ case 214 /* ClassDeclaration */:
+ return declareClassMember(node, symbolFlags, symbolExcludes);
+ case 217 /* EnumDeclaration */:
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ case 155 /* TypeLiteral */:
+ case 165 /* ObjectLiteralExpression */:
+ case 215 /* InterfaceDeclaration */:
+ // Interface/Object-types always have their children added to the 'members' of
+ // their container. They are only accessible through an instance of their
+ // container, and are never in scope otherwise (even inside the body of the
+ // object / type / interface declaring them). An exception is type parameters,
+ // which are in scope without qualification (similar to 'locals').
+ return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ case 152 /* FunctionType */:
+ case 153 /* ConstructorType */:
+ case 147 /* CallSignature */:
+ case 148 /* ConstructSignature */:
+ case 149 /* IndexSignature */:
+ case 143 /* MethodDeclaration */:
+ case 142 /* MethodSignature */:
+ case 144 /* Constructor */:
+ case 145 /* GetAccessor */:
+ case 146 /* SetAccessor */:
+ case 213 /* FunctionDeclaration */:
+ case 173 /* FunctionExpression */:
+ case 174 /* ArrowFunction */:
+ case 216 /* TypeAliasDeclaration */:
+ // All the children of these container types are never visible through another
+ // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
+ // they're only accessed 'lexically' (i.e. from code that exists underneath
+ // their container in the tree. To accomplish this, we simply add their declared
+ // symbol to the 'locals' of the container. These symbols can then be found as
+ // the type checker walks up the containers, checking them for matching names.
+ return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function declareClassMember(node, symbolFlags, symbolExcludes) {
+ return node.flags & 64 /* Static */
+ ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
+ : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
+ return ts.isExternalModule(file)
+ ? declareModuleMember(node, symbolFlags, symbolExcludes)
+ : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ function hasExportDeclarations(node) {
+ var body = node.kind === 248 /* SourceFile */ ? node : node.body;
+ if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) {
+ for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
+ var stat = _a[_i];
+ if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ function setExportContextFlag(node) {
+ // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
+ // declarations with export modifiers) is an export context in which declarations are implicitly exported.
+ if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) {
+ node.flags |= 131072 /* ExportContext */;
+ }
+ else {
+ node.flags &= ~131072 /* ExportContext */;
+ }
+ }
+ function bindModuleDeclaration(node) {
+ setExportContextFlag(node);
+ if (node.name.kind === 9 /* StringLiteral */) {
+ declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
+ }
+ else {
+ var state = getModuleInstanceState(node);
+ if (state === 0 /* NonInstantiated */) {
+ declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
+ if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
+ // if module was already merged with some function, class or non-const enum
+ // treat is a non-const-enum-only
+ node.symbol.constEnumOnlyModule = false;
+ }
+ else {
+ var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */;
+ if (node.symbol.constEnumOnlyModule === undefined) {
+ // non-merged case - use the current state
+ node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
+ }
+ else {
+ // merged case: module is const enum only if all its pieces are non-instantiated or const enum
+ node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
+ }
+ }
+ }
+ }
+ }
+ function bindFunctionOrConstructorType(node) {
+ // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
+ // to the one we would get for: { <...>(...): T }
+ //
+ // We do that by making an anonymous type literal symbol, and then setting the function
+ // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
+ // from an actual type literal symbol you would have gotten had you used the long form.
+ var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node));
+ addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
+ var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type");
+ addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
+ typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a);
+ var _a;
+ }
+ function bindObjectLiteralExpression(node) {
+ var ElementKind;
+ (function (ElementKind) {
+ ElementKind[ElementKind["Property"] = 1] = "Property";
+ ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
+ })(ElementKind || (ElementKind = {}));
+ if (inStrictMode) {
+ var seen = {};
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (prop.name.kind !== 69 /* Identifier */) {
+ continue;
+ }
+ var identifier = prop.name;
+ // ECMA-262 11.1.5 Object Initialiser
+ // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
+ // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
+ // IsDataDescriptor(propId.descriptor) is true.
+ // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
+ // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
+ // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
+ // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
+ var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */
+ ? 1 /* Property */
+ : 2 /* Accessor */;
+ var existingKind = seen[identifier.text];
+ if (!existingKind) {
+ seen[identifier.text] = currentKind;
+ continue;
+ }
+ if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
+ var span = ts.getErrorSpanForNode(file, identifier);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
+ }
+ }
+ }
+ return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object");
+ }
+ function bindAnonymousDeclaration(node, symbolFlags, name) {
+ var symbol = createSymbol(symbolFlags, name);
+ addDeclarationToSymbol(symbol, node, symbolFlags);
+ }
+ function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
+ switch (blockScopeContainer.kind) {
+ case 218 /* ModuleDeclaration */:
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ case 248 /* SourceFile */:
+ if (ts.isExternalModule(container)) {
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ }
+ // fall through.
+ default:
+ if (!blockScopeContainer.locals) {
+ blockScopeContainer.locals = {};
+ addToContainerChain(blockScopeContainer);
+ }
+ declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function bindBlockScopedVariableDeclaration(node) {
+ bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */);
+ }
+ // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
+ // check for reserved words used as identifiers in strict mode code.
+ function checkStrictModeIdentifier(node) {
+ if (inStrictMode &&
+ node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ &&
+ node.originalKeywordKind <= 114 /* LastFutureReservedWord */ &&
+ !ts.isIdentifierName(node)) {
+ // Report error only if there are no parse errors in file
+ if (!file.parseDiagnostics.length) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
+ }
+ }
+ }
+ function getStrictModeIdentifierMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
+ }
+ function checkStrictModeBinaryExpression(node) {
+ if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
+ // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
+ // Assignment operator(11.13) or of a PostfixExpression(11.3)
+ checkStrictModeEvalOrArguments(node, node.left);
+ }
+ }
+ function checkStrictModeCatchClause(node) {
+ // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
+ // Catch production is eval or arguments
+ if (inStrictMode && node.variableDeclaration) {
+ checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
+ }
+ }
+ function checkStrictModeDeleteExpression(node) {
+ // Grammar checking
+ if (inStrictMode && node.expression.kind === 69 /* Identifier */) {
+ // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
+ // UnaryExpression is a direct reference to a variable, function argument, or function name
+ var span = ts.getErrorSpanForNode(file, node.expression);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
+ }
+ }
+ function isEvalOrArgumentsIdentifier(node) {
+ return node.kind === 69 /* Identifier */ &&
+ (node.text === "eval" || node.text === "arguments");
+ }
+ function checkStrictModeEvalOrArguments(contextNode, name) {
+ if (name && name.kind === 69 /* Identifier */) {
+ var identifier = name;
+ if (isEvalOrArgumentsIdentifier(identifier)) {
+ // We check first if the name is inside class declaration or class expression; if so give explicit message
+ // otherwise report generic error message.
+ var span = ts.getErrorSpanForNode(file, name);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));
+ }
+ }
+ }
+ function getStrictModeEvalOrArgumentsMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
+ }
+ function checkStrictModeFunctionName(node) {
+ if (inStrictMode) {
+ // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ }
+ function checkStrictModeNumericLiteral(node) {
+ if (inStrictMode && node.flags & 32768 /* OctalLiteral */) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
+ }
+ }
+ function checkStrictModePostfixUnaryExpression(node) {
+ // Grammar checking
+ // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
+ // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
+ // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
+ }
+ function checkStrictModePrefixUnaryExpression(node) {
+ // Grammar checking
+ if (inStrictMode) {
+ if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
+ }
+ }
+ function checkStrictModeWithStatement(node) {
+ // Grammar checking for withStatement
+ if (inStrictMode) {
+ errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
+ }
+ }
+ function errorOnFirstToken(node, message, arg0, arg1, arg2) {
+ var span = ts.getSpanOfTokenAtPosition(file, node.pos);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
+ }
+ function getDestructuringParameterName(node) {
+ return "__" + ts.indexOf(node.parent.parameters, node);
+ }
+ function bind(node) {
+ if (!node) {
+ return;
+ }
+ node.parent = parent;
+ var savedInStrictMode = inStrictMode;
+ if (!savedInStrictMode) {
+ updateStrictMode(node);
+ }
+ // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
+ // and then potentially add the symbol to an appropriate symbol table. Possible
+ // destination symbol tables are:
+ //
+ // 1) The 'exports' table of the current container's symbol.
+ // 2) The 'members' table of the current container's symbol.
+ // 3) The 'locals' table of the current container.
+ //
+ // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
+ // (like TypeLiterals for example) will not be put in any table.
+ bindWorker(node);
+ // Then we recurse into the children of the node to bind them as well. For certain
+ // symbols we do specialized work when we recurse. For example, we'll keep track of
+ // the current 'container' node when it changes. This helps us know which symbol table
+ // a local should go into for example.
+ bindChildren(node);
+ inStrictMode = savedInStrictMode;
+ }
+ function updateStrictMode(node) {
+ switch (node.kind) {
+ case 248 /* SourceFile */:
+ case 219 /* ModuleBlock */:
+ updateStrictModeStatementList(node.statements);
+ return;
+ case 192 /* Block */:
+ if (ts.isFunctionLike(node.parent)) {
+ updateStrictModeStatementList(node.statements);
+ }
+ return;
+ case 214 /* ClassDeclaration */:
+ case 186 /* ClassExpression */:
+ // All classes are automatically in strict mode in ES6.
+ inStrictMode = true;
+ return;
+ }
+ }
+ function updateStrictModeStatementList(statements) {
+ for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
+ var statement = statements_1[_i];
+ if (!ts.isPrologueDirective(statement)) {
+ return;
+ }
+ if (isUseStrictPrologueDirective(statement)) {
+ inStrictMode = true;
+ return;
+ }
+ }
+ }
+ /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
+ function isUseStrictPrologueDirective(node) {
+ var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression);
+ // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
+ // string to contain unicode escapes (as per ES5).
+ return nodeText === "\"use strict\"" || nodeText === "'use strict'";
+ }
+ function bindWorker(node) {
+ switch (node.kind) {
+ /* Strict mode checks */
+ case 69 /* Identifier */:
+ return checkStrictModeIdentifier(node);
+ case 181 /* BinaryExpression */:
+ if (ts.isInJavaScriptFile(node)) {
+ if (ts.isExportsPropertyAssignment(node)) {
+ bindExportsPropertyAssignment(node);
+ }
+ else if (ts.isModuleExportsAssignment(node)) {
+ bindModuleExportsAssignment(node);
+ }
+ }
+ return checkStrictModeBinaryExpression(node);
+ case 244 /* CatchClause */:
+ return checkStrictModeCatchClause(node);
+ case 175 /* DeleteExpression */:
+ return checkStrictModeDeleteExpression(node);
+ case 8 /* NumericLiteral */:
+ return checkStrictModeNumericLiteral(node);
+ case 180 /* PostfixUnaryExpression */:
+ return checkStrictModePostfixUnaryExpression(node);
+ case 179 /* PrefixUnaryExpression */:
+ return checkStrictModePrefixUnaryExpression(node);
+ case 205 /* WithStatement */:
+ return checkStrictModeWithStatement(node);
+ case 97 /* ThisKeyword */:
+ seenThisKeyword = true;
+ return;
+ case 137 /* TypeParameter */:
+ return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */);
+ case 138 /* Parameter */:
+ return bindParameter(node);
+ case 211 /* VariableDeclaration */:
+ case 163 /* BindingElement */:
+ return bindVariableDeclarationOrBindingElement(node);
+ case 141 /* PropertyDeclaration */:
+ case 140 /* PropertySignature */:
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */);
+ case 245 /* PropertyAssignment */:
+ case 246 /* ShorthandPropertyAssignment */:
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */);
+ case 247 /* EnumMember */:
+ return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */);
+ case 147 /* CallSignature */:
+ case 148 /* ConstructSignature */:
+ case 149 /* IndexSignature */:
+ return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
+ case 143 /* MethodDeclaration */:
+ case 142 /* MethodSignature */:
+ // If this is an ObjectLiteralExpression method, then it sits in the same space
+ // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
+ // so that it will conflict with any other object literal members with the same
+ // name.
+ return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */);
+ case 213 /* FunctionDeclaration */:
+ checkStrictModeFunctionName(node);
+ return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */);
+ case 144 /* Constructor */:
+ return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
+ case 145 /* GetAccessor */:
+ return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */);
+ case 146 /* SetAccessor */:
+ return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */);
+ case 152 /* FunctionType */:
+ case 153 /* ConstructorType */:
+ return bindFunctionOrConstructorType(node);
+ case 155 /* TypeLiteral */:
+ return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type");
+ case 165 /* ObjectLiteralExpression */:
+ return bindObjectLiteralExpression(node);
+ case 173 /* FunctionExpression */:
+ case 174 /* ArrowFunction */:
+ checkStrictModeFunctionName(node);
+ var bindingName = node.name ? node.name.text : "__function";
+ return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
+ case 168 /* CallExpression */:
+ if (ts.isInJavaScriptFile(node)) {
+ bindCallExpression(node);
+ }
+ break;
+ // Members of classes, interfaces, and modules
+ case 186 /* ClassExpression */:
+ case 214 /* ClassDeclaration */:
+ return bindClassLikeDeclaration(node);
+ case 215 /* InterfaceDeclaration */:
+ return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */);
+ case 216 /* TypeAliasDeclaration */:
+ return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */);
+ case 217 /* EnumDeclaration */:
+ return bindEnumDeclaration(node);
+ case 218 /* ModuleDeclaration */:
+ return bindModuleDeclaration(node);
+ // Imports and exports
+ case 221 /* ImportEqualsDeclaration */:
+ case 224 /* NamespaceImport */:
+ case 226 /* ImportSpecifier */:
+ case 230 /* ExportSpecifier */:
+ return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
+ case 223 /* ImportClause */:
+ return bindImportClause(node);
+ case 228 /* ExportDeclaration */:
+ return bindExportDeclaration(node);
+ case 227 /* ExportAssignment */:
+ return bindExportAssignment(node);
+ case 248 /* SourceFile */:
+ return bindSourceFileIfExternalModule();
+ }
+ }
+ function bindSourceFileIfExternalModule() {
+ setExportContextFlag(file);
+ if (ts.isExternalModule(file)) {
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindSourceFileAsExternalModule() {
+ bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
+ }
+ function bindExportAssignment(node) {
+ var boundExpression = node.kind === 227 /* ExportAssignment */ ? node.expression : node.right;
+ if (!container.symbol || !container.symbol.exports) {
+ // Export assignment in some sort of block construct
+ bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node));
+ }
+ else if (boundExpression.kind === 69 /* Identifier */) {
+ // An export default clause with an identifier exports all meanings of that identifier
+ declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
+ }
+ else {
+ // An export default clause with an expression exports a value
+ declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */);
+ }
+ }
+ function bindExportDeclaration(node) {
+ if (!container.symbol || !container.symbol.exports) {
+ // Export * in some sort of block construct
+ bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node));
+ }
+ else if (!node.exportClause) {
+ // All export * declarations are collected in an __export symbol
+ declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */);
+ }
+ }
+ function bindImportClause(node) {
+ if (node.name) {
+ declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
+ }
+ }
+ function setCommonJsModuleIndicator(node) {
+ if (!file.commonJsModuleIndicator) {
+ file.commonJsModuleIndicator = node;
+ bindSourceFileAsExternalModule();
+ }
+ }
+ function bindExportsPropertyAssignment(node) {
+ // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
+ // expression is the declaration
+ setCommonJsModuleIndicator(node);
+ declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */);
+ }
+ function bindModuleExportsAssignment(node) {
+ // 'module.exports = expr' assignment
+ setCommonJsModuleIndicator(node);
+ bindExportAssignment(node);
+ }
+ function bindCallExpression(node) {
+ // 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 && ts.isRequireCall(node)) {
+ setCommonJsModuleIndicator(node);
+ }
+ }
+ function bindClassLikeDeclaration(node) {
+ if (node.kind === 214 /* ClassDeclaration */) {
+ bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */);
+ }
+ else {
+ var bindingName = node.name ? node.name.text : "__class";
+ bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
+ // Add name of class expression into the map for semantic classifier
+ if (node.name) {
+ classifiableNames[node.name.text] = node.name.text;
+ }
+ }
+ var symbol = node.symbol;
+ // TypeScript 1.0 spec (April 2014): 8.4
+ // Every class automatically contains a static property member named 'prototype', the
+ // type of which is an instantiation of the class type with type Any supplied as a type
+ // argument for each type parameter. It is an error to explicitly declare a static
+ // property member with the name 'prototype'.
+ //
+ // Note: we check for this here because this class may be merging into a module. The
+ // module might have an exported variable called 'prototype'. We can't allow that as
+ // that would clash with the built-in 'prototype' for the class.
+ var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype");
+ if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) {
+ if (node.name) {
+ node.name.parent = node;
+ }
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
+ }
+ symbol.exports[prototypeSymbol.name] = prototypeSymbol;
+ prototypeSymbol.parent = symbol;
+ }
+ function bindEnumDeclaration(node) {
+ return ts.isConst(node)
+ ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
+ : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
+ }
+ function bindVariableDeclarationOrBindingElement(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (!ts.isBindingPattern(node.name)) {
+ if (ts.isBlockOrCatchScoped(node)) {
+ bindBlockScopedVariableDeclaration(node);
+ }
+ else if (ts.isParameterDeclaration(node)) {
+ // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration
+ // because its parent chain has already been set up, since parents are set before descending into children.
+ //
+ // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
+ // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
+ // For example:
+ // function foo([a,a]) {} // Duplicate Identifier error
+ // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
+ // // which correctly set excluded symbols
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */);
+ }
+ }
+ }
+ function bindParameter(node) {
+ if (inStrictMode) {
+ // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
+ // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (ts.isBindingPattern(node.name)) {
+ bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node));
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */);
+ }
+ // If this is a property-parameter, then also declare the property symbol into the
+ // containing class.
+ if (node.flags & 56 /* AccessibilityModifier */ &&
+ node.parent.kind === 144 /* Constructor */ &&
+ ts.isClassLike(node.parent.parent)) {
+ var classDeclaration = node.parent.parent;
+ declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */);
+ }
+ }
+ function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
+ return ts.hasDynamicName(node)
+ ? bindAnonymousDeclaration(node, symbolFlags, "__computed")
+ : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ }
+ // reachability checks
+ function pushNamedLabel(name) {
+ initializeReachabilityStateIfNecessary();
+ if (ts.hasProperty(labelIndexMap, name.text)) {
+ return false;
+ }
+ labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1;
+ return true;
+ }
+ function pushImplicitLabel() {
+ initializeReachabilityStateIfNecessary();
+ var index = labelStack.push(1 /* Unintialized */) - 1;
+ implicitLabels.push(index);
+ return index;
+ }
+ function popNamedLabel(label, outerState) {
+ var index = labelIndexMap[label.text];
+ ts.Debug.assert(index !== undefined);
+ ts.Debug.assert(labelStack.length == index + 1);
+ labelIndexMap[label.text] = undefined;
+ setCurrentStateAtLabel(labelStack.pop(), outerState, label);
+ }
+ function popImplicitLabel(implicitLabelIndex, outerState) {
+ if (labelStack.length !== implicitLabelIndex + 1) {
+ ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex);
+ }
+ var i = implicitLabels.pop();
+ if (implicitLabelIndex !== i) {
+ ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex);
+ }
+ setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined);
+ }
+ function setCurrentStateAtLabel(innerMergedState, outerState, label) {
+ if (innerMergedState === 1 /* Unintialized */) {
+ if (label && !options.allowUnusedLabels) {
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label));
+ }
+ currentReachabilityState = outerState;
+ }
+ else {
+ currentReachabilityState = or(innerMergedState, outerState);
+ }
+ }
+ function jumpToLabel(label, outerState) {
+ initializeReachabilityStateIfNecessary();
+ var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels);
+ if (index === undefined) {
+ // reference to unknown label or
+ // break/continue used outside of loops
+ return false;
+ }
+ var stateAtLabel = labelStack[index];
+ labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState);
+ return true;
+ }
+ function checkUnreachable(node) {
+ switch (currentReachabilityState) {
+ case 4 /* Unreachable */:
+ var reportError =
+ // report error on all statements except empty ones
+ (ts.isStatement(node) && node.kind !== 194 /* EmptyStatement */) ||
+ // report error on class declarations
+ node.kind === 214 /* ClassDeclaration */ ||
+ // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
+ (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
+ // report error on regular enums and const enums if preserveConstEnums is set
+ (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
+ if (reportError) {
+ currentReachabilityState = 8 /* ReportedUnreachable */;
+ // unreachable code is reported if
+ // - user has explicitly asked about it AND
+ // - statement is in not ambient context (statements in ambient context is already an error
+ // so we should not report extras) AND
+ // - node is not variable statement OR
+ // - node is block scoped variable statement OR
+ // - node is not block scoped variable statement and at least one variable declaration has initializer
+ // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
+ // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
+ var reportUnreachableCode = !options.allowUnreachableCode &&
+ !ts.isInAmbientContext(node) &&
+ (node.kind !== 193 /* VariableStatement */ ||
+ ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ ||
+ ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
+ if (reportUnreachableCode) {
+ errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected);
+ }
+ }
+ case 8 /* ReportedUnreachable */:
+ return true;
+ default:
+ return false;
+ }
+ function shouldReportErrorOnModuleDeclaration(node) {
+ var instanceState = getModuleInstanceState(node);
+ return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums);
+ }
+ }
+ function initializeReachabilityStateIfNecessary() {
+ if (labelIndexMap) {
+ return;
+ }
+ currentReachabilityState = 2 /* Reachable */;
+ labelIndexMap = {};
+ labelStack = [];
+ implicitLabels = [];
+ }
+ }
+})(ts || (ts = {}));
///
/* @internal */
var ts;
@@ -13755,7 +13918,7 @@ var ts;
symbolToString: symbolToString,
getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
getRootSymbols: getRootSymbols,
- getContextualType: getContextualType,
+ getContextualType: getApparentTypeOfContextualType,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: getResolvedSignature,
getConstantValue: getConstantValue,
@@ -14025,7 +14188,7 @@ var ts;
return ts.getAncestor(node, 248 /* SourceFile */);
}
function isGlobalSourceFile(node) {
- return node.kind === 248 /* SourceFile */ && !ts.isExternalModule(node);
+ return node.kind === 248 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning && ts.hasProperty(symbols, name)) {
@@ -14127,15 +14290,24 @@ var ts;
}
switch (location.kind) {
case 248 /* SourceFile */:
- if (!ts.isExternalModule(location))
+ if (!ts.isExternalOrCommonJsModule(location))
break;
case 218 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
if (location.kind === 248 /* SourceFile */ ||
(location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) {
- // It's an external module. Because of module/namespace merging, a module's exports are in scope,
- // yet we never want to treat an export specifier as putting a member in scope. Therefore,
- // if the name we find is purely an export specifier, it is not actually considered in scope.
+ // It's an external module. First see if the module has an export default and if the local
+ // name of that export default matches.
+ if (result = moduleExports["default"]) {
+ var localSymbol = ts.getLocalSymbolForExportDefault(result);
+ if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
+ break loop;
+ }
+ result = undefined;
+ }
+ // Because of module/namespace merging, a module's exports are in scope,
+ // yet we never want to treat an export specifier as putting a member in scope.
+ // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
// Two things to note about this:
// 1. We have to check this without calling getSymbol. The problem with calling getSymbol
// on an export specifier is that it might find the export specifier itself, and try to
@@ -14149,12 +14321,6 @@ var ts;
ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) {
break;
}
- result = moduleExports["default"];
- var localSymbol = ts.getLocalSymbolForExportDefault(result);
- if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) {
- break loop;
- }
- result = undefined;
}
if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) {
break loop;
@@ -14297,7 +14463,7 @@ var ts;
// declare module foo {
// interface bar {}
// }
- // let foo/*1*/: foo/*2*/.bar;
+ // const foo/*1*/: foo/*2*/.bar;
// The foo at /*1*/ and /*2*/ will share same symbol with two meaning
// block - scope variable and namespace module. However, only when we
// try to resolve name in /*1*/ which is used in variable position,
@@ -14601,6 +14767,9 @@ var ts;
if (moduleName === undefined) {
return;
}
+ if (moduleName.indexOf("!") >= 0) {
+ moduleName = moduleName.substr(0, moduleName.indexOf("!"));
+ }
var isRelative = ts.isExternalModuleNameRelative(moduleName);
if (!isRelative) {
var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */);
@@ -14788,7 +14957,7 @@ var ts;
}
switch (location_1.kind) {
case 248 /* SourceFile */:
- if (!ts.isExternalModule(location_1)) {
+ if (!ts.isExternalOrCommonJsModule(location_1)) {
break;
}
case 218 /* ModuleDeclaration */:
@@ -14910,7 +15079,7 @@ var ts;
// export class c {
// }
// }
- // let x: typeof m.c
+ // const x: typeof m.c
// In the above example when we start with checking if typeof m.c symbol is accessible,
// we are going to see if c can be accessed in scope directly.
// But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
@@ -14949,7 +15118,7 @@ var ts;
}
function hasExternalModuleSymbol(declaration) {
return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) ||
- (declaration.kind === 248 /* SourceFile */ && ts.isExternalModule(declaration));
+ (declaration.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol) {
var aliasesToMakeVisible;
@@ -15100,7 +15269,7 @@ var ts;
parentSymbol = symbol;
appendSymbolNameOnly(symbol, writer);
}
- // Let the writer know we just wrote out a symbol. The declaration emitter writer uses
+ // const the writer know we just wrote out a symbol. The declaration emitter writer uses
// this to determine if an import it has previously seen (and not written out) needs
// to be written to the file once the walk of the tree is complete.
//
@@ -15181,7 +15350,7 @@ var ts;
writeAnonymousType(type, flags);
}
else if (type.flags & 256 /* StringLiteral */) {
- writer.writeStringLiteral(type.text);
+ writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\"");
}
else {
// Should never get here
@@ -15568,7 +15737,7 @@ var ts;
}
}
else if (node.kind === 248 /* SourceFile */) {
- return ts.isExternalModule(node) ? node : undefined;
+ return ts.isExternalOrCommonJsModule(node) ? node : undefined;
}
}
ts.Debug.fail("getContainingModule cant reach here");
@@ -15650,7 +15819,7 @@ var ts;
// Private/protected properties/methods are not visible
return false;
}
- // Public properties/methods are visible if its parents are visible, so let it fall into next case statement
+ // Public properties/methods are visible if its parents are visible, so const it fall into next case statement
case 144 /* Constructor */:
case 148 /* ConstructSignature */:
case 147 /* CallSignature */:
@@ -15678,7 +15847,7 @@ var ts;
// Source file is always visible
case 248 /* SourceFile */:
return true;
- // Export assignements do not create name bindings outside the module
+ // Export assignments do not create name bindings outside the module
case 227 /* ExportAssignment */:
return false;
default:
@@ -15814,6 +15983,23 @@ var ts;
var symbol = getSymbolOfNode(node);
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);
}
+ function getTextOfPropertyName(name) {
+ switch (name.kind) {
+ case 69 /* Identifier */:
+ return name.text;
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ return name.text;
+ case 136 /* ComputedPropertyName */:
+ if (ts.isStringOrNumericLiteral(name.expression.kind)) {
+ return name.expression.text;
+ }
+ }
+ return undefined;
+ }
+ function isComputedNonLiteralName(name) {
+ return name.kind === 136 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind);
+ }
// Return the inferred type for a binding element
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
@@ -15835,10 +16021,15 @@ var ts;
if (pattern.kind === 161 /* ObjectBindingPattern */) {
// Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
var name_10 = declaration.propertyName || declaration.name;
+ if (isComputedNonLiteralName(name_10)) {
+ // computed properties with non-literal names are treated as 'any'
+ return anyType;
+ }
// Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
// or otherwise the type of the string index signature.
- type = getTypeOfPropertyOfType(parentType, name_10.text) ||
- isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
+ var text = getTextOfPropertyName(name_10);
+ type = getTypeOfPropertyOfType(parentType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
getIndexTypeOfType(parentType, 0 /* String */);
if (!type) {
error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10));
@@ -15938,10 +16129,17 @@ var ts;
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType) {
var members = {};
+ var hasComputedProperties = false;
ts.forEach(pattern.elements, function (e) {
- var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);
var name = e.propertyName || e.name;
- var symbol = createSymbol(flags, name.text);
+ if (isComputedNonLiteralName(name)) {
+ // do not include computed properties in the implied type
+ hasComputedProperties = true;
+ return;
+ }
+ var text = getTextOfPropertyName(name);
+ var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);
+ var symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType);
symbol.bindingElement = e;
members[symbol.name] = symbol;
@@ -15950,6 +16148,9 @@ var ts;
if (includePatternInType) {
result.pattern = pattern;
}
+ if (hasComputedProperties) {
+ result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */;
+ }
return result;
}
// Return the type implied by an array binding pattern
@@ -16026,6 +16227,14 @@ var ts;
if (declaration.kind === 227 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
+ // Handle module.exports = expr
+ if (declaration.kind === 181 /* BinaryExpression */) {
+ return links.type = checkExpression(declaration.right);
+ }
+ // Handle exports.p = expr
+ if (declaration.kind === 166 /* PropertyAccessExpression */) {
+ return checkExpressionCached(declaration.parent.right);
+ }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
return unknownType;
@@ -16304,23 +16513,25 @@ var ts;
}
function resolveBaseTypesOfClass(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
- var baseContructorType = getBaseConstructorTypeOfClass(type);
- if (!(baseContructorType.flags & 80896 /* ObjectType */)) {
+ var baseConstructorType = getBaseConstructorTypeOfClass(type);
+ if (!(baseConstructorType.flags & 80896 /* ObjectType */)) {
return;
}
var baseTypeNode = getBaseTypeNodeOfClass(type);
var baseType;
- if (baseContructorType.symbol && baseContructorType.symbol.flags & 32 /* Class */) {
- // When base constructor type is a class we know that the constructors all have the same type parameters as the
+ var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
+ if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
+ areAllOuterTypeParametersApplied(originalBaseType)) {
+ // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the
// class and all return the instance type of the class. There is no need for further checks and we can apply the
// type arguments in the same manner as a type reference to get the same error reporting experience.
- baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol);
+ baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
}
else {
// The class derives from a "class-like" constructor function, check that we have at least one construct signature
// with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
// we check that all instantiated signatures return the same type.
- var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments);
+ var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments);
if (!constructors.length) {
error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
return;
@@ -16345,6 +16556,17 @@ var ts;
type.resolvedBaseTypes.push(baseType);
}
}
+ function areAllOuterTypeParametersApplied(type) {
+ // An unapplied type parameter has its symbol still the same as the matching argument symbol.
+ // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
+ var outerTypeParameters = type.outerTypeParameters;
+ if (outerTypeParameters) {
+ var last = outerTypeParameters.length - 1;
+ var typeArguments = type.typeArguments;
+ return outerTypeParameters[last].symbol !== typeArguments[last].symbol;
+ }
+ return true;
+ }
function resolveBaseTypesOfInterface(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
@@ -16424,7 +16646,7 @@ var ts;
type.typeArguments = type.typeParameters;
type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */);
type.thisType.symbol = symbol;
- type.thisType.constraint = getTypeWithThisArgument(type);
+ type.thisType.constraint = type;
}
}
return links.declaredType;
@@ -16939,6 +17161,20 @@ var ts;
type = getApparentType(type);
return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
}
+ /**
+ * The apparent type of a type parameter is the base constraint instantiated with the type parameter
+ * as the type argument for the 'this' type.
+ */
+ function getApparentTypeOfTypeParameter(type) {
+ if (!type.resolvedApparentType) {
+ var constraintType = getConstraintOfTypeParameter(type);
+ while (constraintType && constraintType.flags & 512 /* TypeParameter */) {
+ constraintType = getConstraintOfTypeParameter(constraintType);
+ }
+ type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
+ }
+ return type.resolvedApparentType;
+ }
/**
* For a type parameter, return the base constraint of the type parameter. For the string, number,
* boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
@@ -16946,12 +17182,7 @@ var ts;
*/
function getApparentType(type) {
if (type.flags & 512 /* TypeParameter */) {
- do {
- type = getConstraintOfTypeParameter(type);
- } while (type && type.flags & 512 /* TypeParameter */);
- if (!type) {
- type = emptyObjectType;
- }
+ type = getApparentTypeOfTypeParameter(type);
}
if (type.flags & 258 /* StringLike */) {
type = globalStringType;
@@ -17116,7 +17347,7 @@ var ts;
if (node.initializer) {
var signatureDeclaration = node.parent;
var signature = getSignatureFromDeclaration(signatureDeclaration);
- var parameterIndex = signatureDeclaration.parameters.indexOf(node);
+ var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node);
ts.Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
@@ -17217,6 +17448,16 @@ var ts;
}
return result;
}
+ function resolveExternalModuleTypeByLiteral(name) {
+ var moduleSym = resolveExternalModuleName(name, name);
+ if (moduleSym) {
+ var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
+ if (resolvedModuleSymbol) {
+ return getTypeOfSymbol(resolvedModuleSymbol);
+ }
+ }
+ return anyType;
+ }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -17740,11 +17981,12 @@ var ts;
return links.resolvedType;
}
function getStringLiteralType(node) {
- if (ts.hasProperty(stringLiteralTypes, node.text)) {
- return stringLiteralTypes[node.text];
+ var text = node.text;
+ if (ts.hasProperty(stringLiteralTypes, text)) {
+ return stringLiteralTypes[text];
}
- var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */);
- type.text = ts.getTextOfNode(node);
+ var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */);
+ type.text = text;
return type;
}
function getTypeFromStringLiteral(node) {
@@ -18265,7 +18507,7 @@ var ts;
return false;
}
function hasExcessProperties(source, target, reportErrors) {
- if (someConstituentTypeHasKind(target, 80896 /* ObjectType */)) {
+ if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && someConstituentTypeHasKind(target, 80896 /* ObjectType */)) {
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
if (!isKnownProperty(target, prop.name)) {
@@ -18358,9 +18600,6 @@ var ts;
return result;
}
function typeParameterIdenticalTo(source, target) {
- if (source.symbol.name !== target.symbol.name) {
- return 0 /* False */;
- }
// covers case when both type parameters does not have constraint (both equal to noConstraintType)
if (source.constraint === target.constraint) {
return -1 /* True */;
@@ -18852,18 +19091,29 @@ var ts;
}
return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
}
+ function isMatchingSignature(source, target, partialMatch) {
+ // A source signature matches a target signature if the two signatures have the same number of required,
+ // optional, and rest parameters.
+ if (source.parameters.length === target.parameters.length &&
+ source.minArgumentCount === target.minArgumentCount &&
+ source.hasRestParameter === target.hasRestParameter) {
+ return true;
+ }
+ // A source signature partially matches a target signature if the target signature has no fewer required
+ // parameters and no more overall parameters than the source signature (where a signature with a rest
+ // parameter is always considered to have more overall parameters than one without).
+ if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter ||
+ source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) {
+ return true;
+ }
+ return false;
+ }
function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) {
if (source === target) {
return -1 /* True */;
}
- if (source.parameters.length !== target.parameters.length ||
- source.minArgumentCount !== target.minArgumentCount ||
- source.hasRestParameter !== target.hasRestParameter) {
- if (!partialMatch ||
- source.parameters.length < target.parameters.length && !source.hasRestParameter ||
- source.minArgumentCount > target.minArgumentCount) {
- return 0 /* False */;
- }
+ if (!(isMatchingSignature(source, target, partialMatch))) {
+ return 0 /* False */;
}
var result = -1 /* True */;
if (source.typeParameters && target.typeParameters) {
@@ -18957,6 +19207,9 @@ var ts;
function isTupleLikeType(type) {
return !!getPropertyOfType(type, "0");
}
+ function isStringLiteralType(type) {
+ return type.flags & 256 /* StringLiteral */;
+ }
/**
* Check if a Type was written as a tuple type literal.
* Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
@@ -19629,7 +19882,7 @@ var ts;
}
function narrowTypeByInstanceof(type, expr, assumeTrue) {
// Check that type is not any, assumed result is true, and we have variable symbol on the left
- if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) {
+ if (isTypeAny(type) || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) {
return type;
}
// Check that right operand is a function type with a prototype property
@@ -19660,6 +19913,12 @@ var ts;
}
}
if (targetType) {
+ if (!assumeTrue) {
+ if (type.flags & 16384 /* Union */) {
+ return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); }));
+ }
+ return type;
+ }
return getNarrowedType(type, targetType);
}
return type;
@@ -20129,6 +20388,9 @@ var ts;
function getIndexTypeOfContextualType(type, kind) {
return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); });
}
+ function contextualTypeIsStringLiteralType(type) {
+ return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type));
+ }
// Return true if the given contextual type is a tuple-like type
function contextualTypeIsTupleLikeType(type) {
return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type));
@@ -20150,7 +20412,7 @@ var ts;
}
function getContextualTypeForObjectLiteralElement(element) {
var objectLiteral = element.parent;
- var type = getContextualType(objectLiteral);
+ var type = getApparentTypeOfContextualType(objectLiteral);
if (type) {
if (!ts.hasDynamicName(element)) {
// For a (non-symbol) computed property, there is no reason to look up the name
@@ -20173,7 +20435,7 @@ var ts;
// type of T.
function getContextualTypeForElementExpression(node) {
var arrayLiteral = node.parent;
- var type = getContextualType(arrayLiteral);
+ var type = getApparentTypeOfContextualType(arrayLiteral);
if (type) {
var index = ts.indexOf(arrayLiteral.elements, node);
return getTypeOfPropertyOfContextualType(type, "" + index)
@@ -20206,11 +20468,28 @@ var ts;
}
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
- function getContextualType(node) {
- var type = getContextualTypeWorker(node);
+ function getApparentTypeOfContextualType(node) {
+ var type = getContextualType(node);
return type && getApparentType(type);
}
- function getContextualTypeWorker(node) {
+ /**
+ * Woah! Do you really want to use this function?
+ *
+ * Unless you're trying to get the *non-apparent* type for a
+ * value-literal type or you're authoring relevant portions of this algorithm,
+ * you probably meant to use 'getApparentTypeOfContextualType'.
+ * Otherwise this may not be very useful.
+ *
+ * In cases where you *are* working on this function, you should understand
+ * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContetxualType'.
+ *
+ * - Use 'getContextualType' when you are simply going to propagate the result to the expression.
+ * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
+ *
+ * @param node the expression whose contextual type will be returned.
+ * @returns the contextual type of an expression.
+ */
+ function getContextualType(node) {
if (isInsideWithStatementBody(node)) {
// We cannot answer semantic questions within a with block, do not proceed any further
return undefined;
@@ -20285,7 +20564,7 @@ var ts;
ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
var type = ts.isObjectLiteralMethod(node)
? getContextualTypeForObjectLiteralMethod(node)
- : getContextualType(node);
+ : getApparentTypeOfContextualType(node);
if (!type) {
return undefined;
}
@@ -20411,7 +20690,7 @@ var ts;
type.pattern = node;
return type;
}
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
var pattern = contextualType.pattern;
// If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
@@ -20494,10 +20773,11 @@ var ts;
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
var propertiesTable = {};
var propertiesArray = [];
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */);
var typeFlags = 0;
+ var patternWithComputedProperties = false;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var memberDecl = _a[_i];
var member = memberDecl.symbol;
@@ -20525,8 +20805,11 @@ var ts;
if (isOptional) {
prop.flags |= 536870912 /* Optional */;
}
+ if (ts.hasDynamicName(memberDecl)) {
+ patternWithComputedProperties = true;
+ }
}
- else if (contextualTypeHasPattern) {
+ else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) {
// If object literal is contextually typed by the implied type of a binding pattern, and if the
// binding pattern specifies a default value for the property, make the property optional.
var impliedProp = getPropertyOfType(contextualType, member.name);
@@ -20578,7 +20861,7 @@ var ts;
var numberIndexType = getIndexType(1 /* Number */);
var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType);
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */;
- result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */);
+ result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0);
if (inDestructuringPattern) {
result.pattern = node;
}
@@ -21289,7 +21572,7 @@ var ts;
// so order how inherited signatures are processed is still preserved.
// interface A { (x: string): void }
// interface B extends A { (x: 'foo'): string }
- // let b: B;
+ // const b: B;
// b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
function reorderCandidates(signatures, result) {
var lastParent;
@@ -22247,6 +22530,10 @@ var ts;
return anyType;
}
}
+ // In JavaScript files, calls to any identifier 'require' are treated as external module imports
+ if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node)) {
+ return resolveExternalModuleTypeByLiteral(node.arguments[0]);
+ }
return getReturnTypeOfSignature(signature);
}
function checkTaggedTemplateExpression(node) {
@@ -22257,7 +22544,10 @@ var ts;
var targetType = getTypeFromTypeNode(node.type);
if (produceDiagnostics && targetType !== unknownType) {
var widenedType = getWidenedType(exprType);
- if (!(isTypeAssignableTo(targetType, widenedType))) {
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ var bothAreStringLike = someConstituentTypeHasKind(targetType, 258 /* StringLike */) &&
+ someConstituentTypeHasKind(widenedType, 258 /* StringLike */);
+ if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) {
checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other);
}
}
@@ -22801,19 +23091,26 @@ var ts;
for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
var p = properties_3[_i];
if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) {
- // TODO(andersh): Computed property support
var name_13 = p.name;
+ if (name_13.kind === 136 /* ComputedPropertyName */) {
+ checkComputedPropertyName(name_13);
+ }
+ if (isComputedNonLiteralName(name_13)) {
+ continue;
+ }
+ var text = getTextOfPropertyName(name_13);
var type = isTypeAny(sourceType)
? sourceType
- : getTypeOfPropertyOfType(sourceType, name_13.text) ||
- isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1 /* Number */) ||
+ : getTypeOfPropertyOfType(sourceType, text) ||
+ isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) ||
getIndexTypeOfType(sourceType, 0 /* String */);
if (type) {
if (p.kind === 246 /* ShorthandPropertyAssignment */) {
checkDestructuringAssignment(p, type);
}
else {
- checkDestructuringAssignment(p.initializer || name_13, type);
+ // non-shorthand property assignments should always have initializers
+ checkDestructuringAssignment(p.initializer, type);
}
}
else {
@@ -23014,6 +23311,10 @@ var ts;
case 31 /* ExclamationEqualsToken */:
case 32 /* EqualsEqualsEqualsToken */:
case 33 /* ExclamationEqualsEqualsToken */:
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ if (someConstituentTypeHasKind(leftType, 258 /* StringLike */) && someConstituentTypeHasKind(rightType, 258 /* StringLike */)) {
+ return booleanType;
+ }
if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) {
reportOperatorError();
}
@@ -23137,6 +23438,13 @@ var ts;
var type2 = checkExpression(node.whenFalse, contextualMapper);
return getUnionType([type1, type2]);
}
+ function checkStringLiteralExpression(node) {
+ var contextualType = getContextualType(node);
+ if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
+ return getStringLiteralType(node);
+ }
+ return stringType;
+ }
function checkTemplateExpression(node) {
// We just want to check each expressions, but we are unconcerned with
// the type of each expression, as any value may be coerced into a string.
@@ -23187,7 +23495,7 @@ var ts;
if (isInferentialContext(contextualMapper)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
- var contextualType = getContextualType(node);
+ var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(contextualType);
if (contextualSignature && !contextualSignature.typeParameters) {
@@ -23251,6 +23559,7 @@ var ts;
case 183 /* TemplateExpression */:
return checkTemplateExpression(node);
case 9 /* StringLiteral */:
+ return checkStringLiteralExpression(node);
case 11 /* NoSubstitutionTemplateLiteral */:
return stringType;
case 10 /* RegularExpressionLiteral */:
@@ -24580,7 +24889,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 248 /* SourceFile */ && ts.isExternalModule(parent)) {
+ if (parent.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -24598,15 +24907,15 @@ var ts;
// A non-initialized declaration is a no-op as the block declaration will resolve before the var
// declaration. the problem is if the declaration has an initializer. this will act as a write to the
// block declared value. this is fine for let, but not const.
- // Only consider declarations with initializers, uninitialized let declarations will not
+ // Only consider declarations with initializers, uninitialized const declarations will not
// step on a let/const variable.
- // Do not consider let and const declarations, as duplicate block-scoped declarations
+ // Do not consider const and const declarations, as duplicate block-scoped declarations
// are handled by the binder.
- // We are only looking for let declarations that step on let\const declarations from a
+ // We are only looking for const declarations that step on let\const declarations from a
// different scope. e.g.:
// {
// const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
- // let x = 0; // symbol for this declaration will be 'symbol'
+ // const x = 0; // symbol for this declaration will be 'symbol'
// }
// skip block-scoped variables and parameters
if ((ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
@@ -24693,6 +25002,12 @@ var ts;
checkExpressionCached(node.initializer);
}
}
+ if (node.kind === 163 /* BindingElement */) {
+ // check computed properties inside property names of binding elements
+ if (node.propertyName && node.propertyName.kind === 136 /* ComputedPropertyName */) {
+ checkComputedPropertyName(node.propertyName);
+ }
+ }
// For a binding pattern, check contained binding elements
if (ts.isBindingPattern(node.name)) {
ts.forEach(node.name.elements, checkSourceElement);
@@ -25176,6 +25491,7 @@ var ts;
var firstDefaultClause;
var hasDuplicateDefaultClause = false;
var expressionType = checkExpression(node.expression);
+ var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258 /* StringLike */);
ts.forEach(node.caseBlock.clauses, function (clause) {
// Grammar check for duplicate default clauses, skip if we already report duplicate default clause
if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) {
@@ -25195,6 +25511,10 @@ var ts;
// TypeScript 1.0 spec (April 2014):5.9
// In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression.
var caseType = checkExpression(caseClause.expression);
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) {
+ return;
+ }
if (!isTypeAssignableTo(expressionType, caseType)) {
// check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined);
@@ -25659,11 +25979,14 @@ var ts;
var enumIsConst = ts.isConst(node);
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.name.kind === 136 /* ComputedPropertyName */) {
+ if (isComputedNonLiteralName(member.name)) {
error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
}
- else if (isNumericLiteralName(member.name.text)) {
- error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ else {
+ var text = getTextOfPropertyName(member.name);
+ if (isNumericLiteralName(text)) {
+ error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
+ }
}
var previousEnumMemberIsNonConstant = autoValue === undefined;
var initializer = member.initializer;
@@ -26305,8 +26628,8 @@ var ts;
}
// Function and class expression bodies are checked after all statements in the enclosing body. This is
// to ensure constructs like the following are permitted:
- // let foo = function () {
- // let s = foo();
+ // const foo = function () {
+ // const s = foo();
// return "hello";
// }
// Here, performing a full type check of the body of the function expression whilst in the process of
@@ -26421,8 +26744,12 @@ var ts;
if (!(links.flags & 1 /* TypeChecked */)) {
// Check whether the file has declared it is the default lib,
// and whether the user has specifically chosen to avoid checking it.
- if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) {
- return;
+ if (compilerOptions.skipDefaultLibCheck) {
+ // If the user specified '--noLib' and a file has a '/// ',
+ // then we should treat that file as a default lib.
+ if (node.hasNoDefaultLib) {
+ return;
+ }
}
// Grammar checking
checkGrammarSourceFile(node);
@@ -26432,7 +26759,7 @@ var ts;
potentialThisCollisions.length = 0;
ts.forEach(node.statements, checkSourceElement);
checkFunctionAndClassExpressionBodies(node);
- if (ts.isExternalModule(node)) {
+ if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
if (potentialThisCollisions.length) {
@@ -26515,7 +26842,7 @@ var ts;
}
switch (location.kind) {
case 248 /* SourceFile */:
- if (!ts.isExternalModule(location)) {
+ if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
case 218 /* ModuleDeclaration */:
@@ -27153,9 +27480,18 @@ var ts;
getReferencedValueDeclaration: getReferencedValueDeclaration,
getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
isOptionalParameter: isOptionalParameter,
- isArgumentsLocalBinding: isArgumentsLocalBinding
+ isArgumentsLocalBinding: isArgumentsLocalBinding,
+ getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration
};
}
+ function getExternalModuleFileFromDeclaration(declaration) {
+ var specifier = ts.getExternalModuleName(declaration);
+ var moduleSymbol = getSymbolAtLocation(specifier);
+ if (!moduleSymbol) {
+ return undefined;
+ }
+ return ts.getDeclarationOfKind(moduleSymbol, 248 /* SourceFile */);
+ }
function initializeTypeChecker() {
// Bind all source files and propagate errors
ts.forEach(host.getSourceFiles(), function (file) {
@@ -27163,11 +27499,10 @@ var ts;
});
// Initialize global symbol table
ts.forEach(host.getSourceFiles(), function (file) {
- if (!ts.isExternalModule(file)) {
+ if (!ts.isExternalOrCommonJsModule(file)) {
mergeSymbolTable(globals, file.locals);
}
});
- // Initialize special symbols
getSymbolLinks(undefinedSymbol).type = undefinedType;
getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments");
getSymbolLinks(unknownSymbol).type = unknownType;
@@ -27866,7 +28201,7 @@ var ts;
}
}
function checkGrammarForNonSymbolComputedProperty(node, message) {
- if (node.kind === 136 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) {
+ if (ts.isDynamicName(node)) {
return grammarErrorOnNode(node, message);
}
}
@@ -28225,11 +28560,15 @@ var ts;
var writeTextOfNode;
var writer = createAndSetNewTextWriterWithSymbolWriter();
var enclosingDeclaration;
- var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentIdentifiers;
+ var isCurrentFileExternalModule;
var reportedDeclarationError = false;
var errorNameNode;
var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments;
var emit = compilerOptions.stripInternal ? stripInternal : emitNode;
+ var noDeclare = !root;
var moduleElementDeclarationEmitInfo = [];
var asynchronousSubModuleDeclarationEmitInfo;
// Contains the reference paths that needs to go in the declaration file.
@@ -28272,23 +28611,56 @@ var ts;
else {
// Emit references corresponding to this file
var emittedReferencedFiles = [];
+ var prevModuleElementDeclarationEmitInfo = [];
ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ if (!ts.isDeclarationFile(sourceFile)) {
// Check what references need to be added
if (!compilerOptions.noResolve) {
ts.forEach(sourceFile.referencedFiles, function (fileReference) {
var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference);
- // If the reference file is a declaration file or an external module, emit that reference
- if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) &&
+ // If the reference file is a declaration file, emit that reference
+ if (referencedFile && (ts.isDeclarationFile(referencedFile) &&
!ts.contains(emittedReferencedFiles, referencedFile))) {
writeReferencePath(referencedFile);
emittedReferencedFiles.push(referencedFile);
}
});
}
+ }
+ if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) {
+ noDeclare = false;
emitSourceFile(sourceFile);
}
+ else if (ts.isExternalModule(sourceFile)) {
+ noDeclare = true;
+ write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {");
+ writeLine();
+ increaseIndent();
+ emitSourceFile(sourceFile);
+ decreaseIndent();
+ write("}");
+ writeLine();
+ // create asynchronous output for the importDeclarations
+ if (moduleElementDeclarationEmitInfo.length) {
+ var oldWriter = writer;
+ ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) {
+ if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
+ ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */);
+ createAndSetNewTextWriterWithSymbolWriter();
+ ts.Debug.assert(aliasEmitInfo.indent === 1);
+ increaseIndent();
+ writeImportDeclaration(aliasEmitInfo.node);
+ aliasEmitInfo.asynchronousOutput = writer.getText();
+ decreaseIndent();
+ }
+ });
+ setWriter(oldWriter);
+ }
+ prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
+ moduleElementDeclarationEmitInfo = [];
+ }
});
+ moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo);
}
return {
reportedDeclarationError: reportedDeclarationError,
@@ -28297,13 +28669,12 @@ var ts;
referencePathsOutput: referencePathsOutput
};
function hasInternalAnnotation(range) {
- var text = currentSourceFile.text;
- var comment = text.substring(range.pos, range.end);
+ var comment = currentText.substring(range.pos, range.end);
return comment.indexOf("@internal") >= 0;
}
function stripInternal(node) {
if (node) {
- var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);
+ var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos);
if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
return;
}
@@ -28395,7 +28766,7 @@ var ts;
var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
- diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
+ diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
}
else {
diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName));
@@ -28461,10 +28832,10 @@ var ts;
}
function writeJsDocComments(declaration) {
if (declaration) {
- var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile);
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments);
+ var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
- ts.emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange);
+ ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange);
}
}
function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) {
@@ -28481,7 +28852,7 @@ var ts;
case 103 /* VoidKeyword */:
case 97 /* ThisKeyword */:
case 9 /* StringLiteral */:
- return writeTextOfNode(currentSourceFile, type);
+ return writeTextOfNode(currentText, type);
case 188 /* ExpressionWithTypeArguments */:
return emitExpressionWithTypeArguments(type);
case 151 /* TypeReference */:
@@ -28512,14 +28883,14 @@ var ts;
}
function writeEntityName(entityName) {
if (entityName.kind === 69 /* Identifier */) {
- writeTextOfNode(currentSourceFile, entityName);
+ writeTextOfNode(currentText, entityName);
}
else {
var left = entityName.kind === 135 /* QualifiedName */ ? entityName.left : entityName.expression;
var right = entityName.kind === 135 /* QualifiedName */ ? entityName.right : entityName.name;
writeEntityName(left);
write(".");
- writeTextOfNode(currentSourceFile, right);
+ writeTextOfNode(currentText, right);
}
}
function emitEntityName(entityName) {
@@ -28549,7 +28920,7 @@ var ts;
}
}
function emitTypePredicate(type) {
- writeTextOfNode(currentSourceFile, type.parameterName);
+ writeTextOfNode(currentText, type.parameterName);
write(" is ");
emitType(type.type);
}
@@ -28590,9 +28961,12 @@ var ts;
}
}
function emitSourceFile(node) {
- currentSourceFile = node;
+ currentText = node.text;
+ currentLineMap = ts.getLineStarts(node);
+ currentIdentifiers = node.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(node);
enclosingDeclaration = node;
- ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true /* remove comments */);
+ ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true /* remove comments */);
emitLines(node.statements);
}
// Return a temp variable name to be used in `export default` statements.
@@ -28601,13 +28975,13 @@ var ts;
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName() {
var baseName = "_default";
- if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) {
+ if (!ts.hasProperty(currentIdentifiers, baseName)) {
return baseName;
}
var count = 0;
while (true) {
var name_18 = baseName + "_" + (++count);
- if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) {
+ if (!ts.hasProperty(currentIdentifiers, name_18)) {
return name_18;
}
}
@@ -28615,7 +28989,7 @@ var ts;
function emitExportAssignment(node) {
if (node.expression.kind === 69 /* Identifier */) {
write(node.isExportEquals ? "export = " : "export default ");
- writeTextOfNode(currentSourceFile, node.expression);
+ writeTextOfNode(currentText, node.expression);
}
else {
// Expression
@@ -28653,7 +29027,7 @@ var ts;
writeModuleElement(node);
}
else if (node.kind === 221 /* ImportEqualsDeclaration */ ||
- (node.parent.kind === 248 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) {
+ (node.parent.kind === 248 /* SourceFile */ && isCurrentFileExternalModule)) {
var isVisible;
if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) {
// Import declaration of another module that is visited async so lets put it in right spot
@@ -28707,7 +29081,7 @@ var ts;
}
function emitModuleElementDeclarationFlags(node) {
// If the node is parented in the current source file we need to emit export declare or just export
- if (node.parent === currentSourceFile) {
+ if (node.parent.kind === 248 /* SourceFile */) {
// If the node is exported
if (node.flags & 2 /* Export */) {
write("export ");
@@ -28715,7 +29089,7 @@ var ts;
if (node.flags & 512 /* Default */) {
write("default ");
}
- else if (node.kind !== 215 /* InterfaceDeclaration */) {
+ else if (node.kind !== 215 /* InterfaceDeclaration */ && !noDeclare) {
write("declare ");
}
}
@@ -28742,7 +29116,7 @@ var ts;
write("export ");
}
write("import ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" = ");
if (ts.isInternalModuleImportEqualsDeclaration(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError);
@@ -28750,7 +29124,7 @@ var ts;
}
else {
write("require(");
- writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node));
+ writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node));
write(");");
}
writer.writeLine();
@@ -28785,7 +29159,7 @@ var ts;
if (node.importClause) {
var currentWriterPos = writer.getTextPos();
if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) {
- writeTextOfNode(currentSourceFile, node.importClause.name);
+ writeTextOfNode(currentText, node.importClause.name);
}
if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) {
if (currentWriterPos !== writer.getTextPos()) {
@@ -28794,7 +29168,7 @@ var ts;
}
if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) {
write("* as ");
- writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name);
+ writeTextOfNode(currentText, node.importClause.namedBindings.name);
}
else {
write("{ ");
@@ -28804,16 +29178,28 @@ var ts;
}
write(" from ");
}
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
write(";");
writer.writeLine();
}
+ function emitExternalModuleSpecifier(moduleSpecifier) {
+ if (moduleSpecifier.kind === 9 /* StringLiteral */ && (!root) && (compilerOptions.out || compilerOptions.outFile)) {
+ var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent);
+ if (moduleName) {
+ write("\"");
+ write(moduleName);
+ write("\"");
+ return;
+ }
+ }
+ writeTextOfNode(currentText, moduleSpecifier);
+ }
function emitImportOrExportSpecifier(node) {
if (node.propertyName) {
- writeTextOfNode(currentSourceFile, node.propertyName);
+ writeTextOfNode(currentText, node.propertyName);
write(" as ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
function emitExportSpecifier(node) {
emitImportOrExportSpecifier(node);
@@ -28835,7 +29221,7 @@ var ts;
}
if (node.moduleSpecifier) {
write(" from ");
- writeTextOfNode(currentSourceFile, node.moduleSpecifier);
+ emitExternalModuleSpecifier(node.moduleSpecifier);
}
write(";");
writer.writeLine();
@@ -28849,11 +29235,11 @@ var ts;
else {
write("module ");
}
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
while (node.body.kind !== 219 /* ModuleBlock */) {
node = node.body;
write(".");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
@@ -28872,7 +29258,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
@@ -28894,7 +29280,7 @@ var ts;
write("const ");
}
write("enum ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
write(" {");
writeLine();
increaseIndent();
@@ -28905,7 +29291,7 @@ var ts;
}
function emitEnumMemberDeclaration(node) {
emitJsDocComments(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
@@ -28922,7 +29308,7 @@ var ts;
increaseIndent();
emitJsDocComments(node);
decreaseIndent();
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
// If there is constraint present and this is not a type parameter of the private method emit the constraint
if (node.constraint && !isPrivateMethodTypeParameter(node)) {
write(" extends ");
@@ -29037,7 +29423,7 @@ var ts;
write("abstract ");
}
write("class ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -29060,7 +29446,7 @@ var ts;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("interface ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -29095,7 +29481,7 @@ var ts;
// If this node is a computed name, it can only be a symbol, because we've already skipped
// it if it's not a well known symbol. In that case, the text of the name will be exactly
// what we want, namely the name expression enclosed in brackets.
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
// If optional property emit ?
if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && ts.hasQuestionToken(node)) {
write("?");
@@ -29177,7 +29563,7 @@ var ts;
emitBindingPattern(bindingElement.name);
}
else {
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError);
}
}
@@ -29221,7 +29607,7 @@ var ts;
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (!(node.flags & 16 /* Private */)) {
accessorWithTypeAnnotation = node;
var type = getTypeAnnotationFromAccessor(node);
@@ -29307,13 +29693,13 @@ var ts;
}
if (node.kind === 213 /* FunctionDeclaration */) {
write("function ");
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
else if (node.kind === 144 /* Constructor */) {
write("constructor");
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
if (ts.hasQuestionToken(node)) {
write("?");
}
@@ -29437,7 +29823,7 @@ var ts;
emitBindingPattern(node.name);
}
else {
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
}
if (resolver.isOptionalParameter(node)) {
write("?");
@@ -29552,7 +29938,7 @@ var ts;
// Example:
// original: function foo({y: [a,b,c]}) {}
// emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void;
- writeTextOfNode(currentSourceFile, bindingElement.propertyName);
+ writeTextOfNode(currentText, bindingElement.propertyName);
write(": ");
}
if (bindingElement.name) {
@@ -29575,7 +29961,7 @@ var ts;
if (bindingElement.dotDotDotToken) {
write("...");
}
- writeTextOfNode(currentSourceFile, bindingElement.name);
+ writeTextOfNode(currentText, bindingElement.name);
}
}
}
@@ -29667,6 +30053,18 @@ var ts;
return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile);
}
ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile;
+ function getResolvedExternalModuleName(host, file) {
+ return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName);
+ }
+ ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
+ function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
+ var file = resolver.getExternalModuleFileFromDeclaration(declaration);
+ if (!file || ts.isDeclarationFile(file)) {
+ return undefined;
+ }
+ return getResolvedExternalModuleName(host, file);
+ }
+ ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
var Jump;
(function (Jump) {
Jump[Jump["Break"] = 2] = "Break";
@@ -29954,15 +30352,19 @@ var ts;
var newLine = host.getNewLine();
var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */;
var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); };
+ var outFile = compilerOptions.outFile || compilerOptions.out;
+ var emitJavaScript = createFileEmitter();
if (targetSourceFile === undefined) {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
- var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
- emitFile(jsFilePath, sourceFile);
- }
- });
- if (compilerOptions.outFile || compilerOptions.out) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ if (outFile) {
+ emitFile(outFile);
+ }
+ else {
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {
+ var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
+ emitFile(jsFilePath, sourceFile);
+ }
+ });
}
}
else {
@@ -29971,8 +30373,8 @@ var ts;
var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
- else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {
- emitFile(compilerOptions.outFile || compilerOptions.out);
+ else if (!ts.isDeclarationFile(targetSourceFile) && outFile) {
+ emitFile(outFile);
}
}
// Sort and make the unique list of diagnostics
@@ -30024,10 +30426,16 @@ var ts;
}
}
}
- function emitJavaScript(jsFilePath, root) {
+ function createFileEmitter() {
var writer = ts.createTextWriter(newLine);
var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;
var currentSourceFile;
+ var currentText;
+ var currentLineMap;
+ var currentFileIdentifiers;
+ var renamedDependencies;
+ var isEs6Module;
+ var isCurrentFileExternalModule;
// name of an exporter function if file is a System external module
// System.register([...], function () {...})
// exporting in System modules looks like:
@@ -30035,15 +30443,15 @@ var ts;
// =>
// var x;... exporter("x", x = 1)
var exportFunctionForFile;
- var generatedNameSet = {};
- var nodeToGeneratedName = [];
+ var generatedNameSet;
+ var nodeToGeneratedName;
var computedPropertyNamesToGeneratedNames;
var convertedLoopState;
- var extendsEmitted = false;
- var decorateEmitted = false;
- var paramEmitted = false;
- var awaiterEmitted = false;
- var tempFlags = 0;
+ var extendsEmitted;
+ var decorateEmitted;
+ var paramEmitted;
+ var awaiterEmitted;
+ var tempFlags;
var tempVariables;
var tempParameters;
var externalImports;
@@ -30075,6 +30483,8 @@ var ts;
var scopeEmitEnd = function () { };
/** Sourcemap data that will get encoded */
var sourceMapData;
+ /** The root file passed to the emit function (if present) */
+ var root;
/** If removeComments is true, no leading-comments needed to be emitted **/
var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker;
var moduleEmitDelegates = (_a = {},
@@ -30085,31 +30495,77 @@ var ts;
_a[1 /* CommonJS */] = emitCommonJSModule,
_a
);
- if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
- initializeEmitterWithSourceMaps();
- }
- if (root) {
- // Do not call emit directly. It does not set the currentSourceFile.
- emitSourceFile(root);
- }
- else {
- ts.forEach(host.getSourceFiles(), function (sourceFile) {
- if (!isExternalModuleOrDeclarationFile(sourceFile)) {
- emitSourceFile(sourceFile);
+ var bundleEmitDelegates = (_b = {},
+ _b[5 /* ES6 */] = function () { },
+ _b[2 /* AMD */] = emitAMDModule,
+ _b[4 /* System */] = emitSystemModule,
+ _b[3 /* UMD */] = function () { },
+ _b[1 /* CommonJS */] = function () { },
+ _b
+ );
+ return doEmit;
+ function doEmit(jsFilePath, rootFile) {
+ // reset the state
+ writer.reset();
+ currentSourceFile = undefined;
+ currentText = undefined;
+ currentLineMap = undefined;
+ exportFunctionForFile = undefined;
+ generatedNameSet = {};
+ nodeToGeneratedName = [];
+ computedPropertyNamesToGeneratedNames = undefined;
+ convertedLoopState = undefined;
+ extendsEmitted = false;
+ decorateEmitted = false;
+ paramEmitted = false;
+ awaiterEmitted = false;
+ tempFlags = 0;
+ tempVariables = undefined;
+ tempParameters = undefined;
+ externalImports = undefined;
+ exportSpecifiers = undefined;
+ exportEquals = undefined;
+ hasExportStars = undefined;
+ detachedCommentsInfo = undefined;
+ sourceMapData = undefined;
+ isEs6Module = false;
+ renamedDependencies = undefined;
+ isCurrentFileExternalModule = false;
+ root = rootFile;
+ if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
+ initializeEmitterWithSourceMaps(jsFilePath, root);
+ }
+ if (root) {
+ // Do not call emit directly. It does not set the currentSourceFile.
+ emitSourceFile(root);
+ }
+ else {
+ if (modulekind) {
+ ts.forEach(host.getSourceFiles(), emitEmitHelpers);
}
- });
+ ts.forEach(host.getSourceFiles(), function (sourceFile) {
+ if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) {
+ emitSourceFile(sourceFile);
+ }
+ });
+ }
+ writeLine();
+ writeEmittedFiles(writer.getText(), jsFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM);
}
- writeLine();
- writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);
- return;
function emitSourceFile(sourceFile) {
currentSourceFile = sourceFile;
+ currentText = sourceFile.text;
+ currentLineMap = ts.getLineStarts(sourceFile);
exportFunctionForFile = undefined;
+ isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"];
+ renamedDependencies = sourceFile.renamedDependencies;
+ currentFileIdentifiers = sourceFile.identifiers;
+ isCurrentFileExternalModule = ts.isExternalModule(sourceFile);
emit(sourceFile);
}
function isUniqueName(name) {
return !resolver.hasGlobalName(name) &&
- !ts.hasProperty(currentSourceFile.identifiers, name) &&
+ !ts.hasProperty(currentFileIdentifiers, name) &&
!ts.hasProperty(generatedNameSet, name);
}
// Return the next available name in the pattern _a ... _z, _0, _1, ...
@@ -30192,7 +30648,7 @@ var ts;
var id = ts.getNodeId(node);
return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node)));
}
- function initializeEmitterWithSourceMaps() {
+ function initializeEmitterWithSourceMaps(jsFilePath, root) {
var sourceMapDir; // The directory in which sourcemap will be
// Current source map file and its index in the sources list
var sourceMapSourceIndex = -1;
@@ -30280,7 +30736,7 @@ var ts;
}
}
function recordSourceMapSpan(pos) {
- var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos);
+ var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos);
// Convert the location to be one-based.
sourceLinePos.line++;
sourceLinePos.character++;
@@ -30314,13 +30770,13 @@ var ts;
}
function recordEmitNodeStartSpan(node) {
// Get the token pos after skipping to the token (ignoring the leading trivia)
- recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos));
+ recordSourceMapSpan(ts.skipTrivia(currentText, node.pos));
}
function recordEmitNodeEndSpan(node) {
recordSourceMapSpan(node.end);
}
function writeTextWithSpanRecord(tokenKind, startPos, emitFn) {
- var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);
+ var tokenStartPos = ts.skipTrivia(currentText, startPos);
recordSourceMapSpan(tokenStartPos);
var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);
recordSourceMapSpan(tokenEndPos);
@@ -30402,9 +30858,9 @@ var ts;
sourceMapNameIndices.pop();
}
;
- function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) {
+ function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) {
recordSourceMapSpan(comment.pos);
- ts.writeCommentRange(currentSourceFile, writer, comment, newLine);
+ ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine);
recordSourceMapSpan(comment.end);
}
function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) {
@@ -30434,7 +30890,7 @@ var ts;
return output;
}
}
- function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) {
encodeLastRecordedSourceMapSpan();
var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent);
sourceMapDataList.push(sourceMapData);
@@ -30450,7 +30906,7 @@ var ts;
sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL;
}
// Write sourcemap url to the js file and write the js file
- writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);
+ writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark);
}
// Initialize source map data
var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath));
@@ -30522,7 +30978,7 @@ var ts;
scopeEmitEnd = recordScopeNameEnd;
writeComment = writeCommentRangeWithMap;
}
- function writeJavaScriptFile(emitOutput, writeByteOrderMark) {
+ function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) {
ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
// Create a temporary variable with a unique unused name.
@@ -30702,7 +31158,7 @@ var ts;
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (node.parent) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ return ts.getTextOfNodeFromSourceText(currentText, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
@@ -30729,7 +31185,7 @@ var ts;
// Find original source text, since we need to emit the raw strings of the tagged template.
// The raw strings contain the (escaped) strings of what the user wrote.
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node);
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
// thus we need to remove those characters.
// First template piece starts with "`", others with "}"
@@ -31146,7 +31602,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
write("\"");
}
@@ -31246,7 +31702,7 @@ var ts;
// Identifier references named import
write(getGeneratedNameForNode(declaration.parent.parent.parent));
var name_23 = declaration.propertyName || declaration.name;
- var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23);
+ var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23);
if (languageVersion === 0 /* ES3 */ && identifier === "default") {
write("[\"default\"]");
}
@@ -31270,7 +31726,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function isNameOfNestedRedeclaration(node) {
@@ -31308,7 +31764,7 @@ var ts;
write(node.text);
}
else {
- writeTextOfNode(currentSourceFile, node);
+ writeTextOfNode(currentText, node);
}
}
function emitThis(node) {
@@ -31712,7 +32168,7 @@ var ts;
function emitShorthandPropertyAssignment(node) {
// The name property of a short-hand property assignment is considered an expression position, so here
// we manually emit the identifier to avoid rewriting.
- writeTextOfNode(currentSourceFile, node.name);
+ writeTextOfNode(currentText, node.name);
// If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier,
// we emit a normal property assignment. For example:
// module m {
@@ -31722,7 +32178,7 @@ var ts;
// let obj = { y };
// }
// Here we need to emit obj = { y : m.y } regardless of the output target.
- if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) {
+ if (modulekind !== 5 /* ES6 */ || isNamespaceExportReference(node.name)) {
// Emit identifier as an identifier
write(": ");
emit(node.name);
@@ -31779,11 +32235,11 @@ var ts;
var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
// 1 .toString is a valid property access, emit a space after the literal
// Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal
- var shouldEmitSpace;
+ var shouldEmitSpace = false;
if (!indentedBeforeDot) {
if (node.expression.kind === 8 /* NumericLiteral */) {
// check if numeric literal was originally written with a dot
- var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
+ var text = ts.getTextOfNodeFromSourceText(currentText, node.expression);
shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0;
}
else {
@@ -32962,16 +33418,16 @@ var ts;
emitToken(16 /* CloseBraceToken */, node.clauses.end);
}
function nodeStartPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function nodeEndPositionsAreOnSameLine(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, node2.end);
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end);
}
function nodeEndIsOnSameLineAsNodeStart(node1, node2) {
- return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===
- ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));
+ return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
+ ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos));
}
function emitCaseOrDefaultClause(node) {
if (node.kind === 241 /* CaseClause */) {
@@ -33077,7 +33533,7 @@ var ts;
ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */);
// only allow export default at a source file level
if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) {
- if (!currentSourceFile.symbol.exports["___esModule"]) {
+ if (!isEs6Module) {
if (languageVersion === 1 /* ES5 */) {
// default value of configurable, enumerable, writable are `false`.
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
@@ -33272,14 +33728,20 @@ var ts;
return node;
}
function createPropertyAccessForDestructuringProperty(object, propName) {
- // We create a synthetic copy of the identifier in order to avoid the rewriting that might
- // otherwise occur when the identifier is emitted.
- var syntheticName = ts.createSynthesizedNode(propName.kind);
- syntheticName.text = propName.text;
- if (syntheticName.kind !== 69 /* Identifier */) {
- return createElementAccessExpression(object, syntheticName);
+ var index;
+ var nameIsComputed = propName.kind === 136 /* ComputedPropertyName */;
+ if (nameIsComputed) {
+ index = ensureIdentifier(propName.expression, /* reuseIdentifierExpression */ false);
}
- return createPropertyAccessExpression(object, syntheticName);
+ else {
+ // We create a synthetic copy of the identifier in order to avoid the rewriting that might
+ // otherwise occur when the identifier is emitted.
+ index = ts.createSynthesizedNode(propName.kind);
+ index.text = propName.text;
+ }
+ return !nameIsComputed && index.kind === 69 /* Identifier */
+ ? createPropertyAccessExpression(object, index)
+ : createElementAccessExpression(object, index);
}
function createSliceCall(value, sliceIndex) {
var call = ts.createSynthesizedNode(168 /* CallExpression */);
@@ -33742,7 +34204,6 @@ var ts;
var promiseConstructor = ts.getEntityNameFromTypeNode(node.type);
var isArrowFunction = node.kind === 174 /* ArrowFunction */;
var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0;
- var args;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
@@ -35197,8 +35658,8 @@ var ts;
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName) {
- if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
- return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\"";
+ if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) {
+ return "\"" + renamedDependencies[moduleName.text] + "\"";
}
return undefined;
}
@@ -35351,7 +35812,7 @@ var ts;
// - current file is not external module
// - import declaration is top level and target is value imported by entity name
if (resolver.isReferencedAliasDeclaration(node) ||
- (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
+ (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
emitLeadingComments(node);
emitStart(node);
// variable declaration for import-equals declaration can be hoisted in system modules
@@ -35579,7 +36040,7 @@ var ts;
function getLocalNameForExternalImport(node) {
var namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
- return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);
+ return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name);
}
if (node.kind === 222 /* ImportDeclaration */ && node.importClause) {
return getGeneratedNameForNode(node);
@@ -35884,7 +36345,7 @@ var ts;
ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */;
}
function isCurrentFileSystemExternalModule() {
- return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile);
+ return modulekind === 4 /* System */ && isCurrentFileExternalModule;
}
function emitSystemModuleBody(node, dependencyGroups, startIndex) {
// shape of the body in system modules:
@@ -36054,7 +36515,13 @@ var ts;
writeLine();
write("}"); // execute
}
- function emitSystemModule(node) {
+ function writeModuleName(node, emitRelativePathAsModuleName) {
+ var moduleName = node.moduleName;
+ if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) {
+ write("\"" + moduleName + "\", ");
+ }
+ }
+ function emitSystemModule(node, emitRelativePathAsModuleName) {
collectExternalModuleInfo(node);
// System modules has the following shape
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
@@ -36069,9 +36536,7 @@ var ts;
exportFunctionForFile = makeUniqueName("exports");
writeLine();
write("System.register(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
+ writeModuleName(node, emitRelativePathAsModuleName);
write("[");
var groupIndices = {};
var dependencyGroups = [];
@@ -36090,6 +36555,12 @@ var ts;
if (i !== 0) {
write(", ");
}
+ if (emitRelativePathAsModuleName) {
+ var name_29 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
+ if (name_29) {
+ text = "\"" + name_29 + "\"";
+ }
+ }
write(text);
}
write("], function(" + exportFunctionForFile + ") {");
@@ -36103,7 +36574,7 @@ var ts;
writeLine();
write("});");
}
- function getAMDDependencyNames(node, includeNonAmdDependencies) {
+ function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
// names of modules with corresponding parameter in the factory function
var aliasedModuleNames = [];
// names of modules with no corresponding parameters in factory function
@@ -36126,6 +36597,12 @@ var ts;
var importNode = externalImports_4[_c];
// Find the name of the external module
var externalModuleName = getExternalModuleNameText(importNode);
+ if (emitRelativePathAsModuleName) {
+ var name_30 = getExternalModuleNameFromDeclaration(host, resolver, importNode);
+ if (name_30) {
+ externalModuleName = "\"" + name_30 + "\"";
+ }
+ }
// Find the name of the module alias, if there is one
var importAliasName = getLocalNameForExternalImport(importNode);
if (includeNonAmdDependencies && importAliasName) {
@@ -36138,7 +36615,7 @@ var ts;
}
return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
}
- function emitAMDDependencies(node, includeNonAmdDependencies) {
+ function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) {
// An AMD define function has the following shape:
// define(id?, dependencies?, factory);
//
@@ -36150,7 +36627,7 @@ var ts;
// To ensure this is true in cases of modules with no aliases, e.g.:
// `import "module"` or ``
// we need to add modules without alias names to the end of the dependencies list
- var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);
+ var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName);
emitAMDDependencyList(dependencyNames);
write(", ");
emitAMDFactoryHeader(dependencyNames);
@@ -36177,15 +36654,13 @@ var ts;
}
write(") {");
}
- function emitAMDModule(node) {
+ function emitAMDModule(node, emitRelativePathAsModuleName) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
write("define(");
- if (node.moduleName) {
- write("\"" + node.moduleName + "\", ");
- }
- emitAMDDependencies(node, /*includeNonAmdDependencies*/ true);
+ writeModuleName(node, emitRelativePathAsModuleName);
+ emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName);
increaseIndent();
var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
emitExportStarHelper();
@@ -36404,8 +36879,13 @@ var ts;
emitShebang();
emitDetachedCommentsAndUpdateCommentsInfo(node);
if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
- var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */];
- emitModule(node);
+ if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) {
+ var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */];
+ emitModule(node);
+ }
+ else {
+ bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true);
+ }
}
else {
// emit prologue directives prior to __extends
@@ -36666,7 +37146,7 @@ var ts;
}
function getLeadingCommentsWithoutDetachedComments() {
// get the leading comments from detachedPos
- var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
+ var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@@ -36683,10 +37163,10 @@ var ts;
function isTripleSlashComment(comment) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
- if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ &&
+ if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ &&
comment.pos + 2 < comment.end &&
- currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) {
- var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);
+ currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) {
+ var textSubStr = currentText.substring(comment.pos, comment.end);
return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?
true : false;
@@ -36703,7 +37183,7 @@ var ts;
}
else {
// get the leading comments from the node
- return ts.getLeadingCommentRangesOfNode(node, currentSourceFile);
+ return ts.getLeadingCommentRangesOfNodeFromText(node, currentText);
}
}
}
@@ -36712,7 +37192,7 @@ var ts;
// Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments
if (node.parent) {
if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) {
- return ts.getTrailingCommentRanges(currentSourceFile.text, node.end);
+ return ts.getTrailingCommentRanges(currentText, node.end);
}
}
}
@@ -36746,9 +37226,9 @@ var ts;
leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment);
}
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
- ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
}
function emitTrailingComments(node) {
if (compilerOptions.removeComments) {
@@ -36757,7 +37237,7 @@ var ts;
// Emit the trailing comments only if the parent's end doesn't match
var trailingComments = getTrailingCommentsToEmit(node);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
- ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
}
/**
* Emit trailing comments at the position. The term trailing comment is used here to describe following comment:
@@ -36768,9 +37248,9 @@ var ts;
if (compilerOptions.removeComments) {
return;
}
- var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos);
+ var trailingComments = ts.getTrailingCommentRanges(currentText, pos);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
- ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitLeadingCommentsOfPositionWorker(pos) {
if (compilerOptions.removeComments) {
@@ -36783,14 +37263,14 @@ var ts;
}
else {
// get the leading comments from the node
- leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos);
+ leadingComments = ts.getLeadingCommentRanges(currentText, pos);
}
- ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);
+ ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
- ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
+ ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitDetachedCommentsAndUpdateCommentsInfo(node) {
- var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments);
+ var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments);
if (currentDetachedCommentInfo) {
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
@@ -36801,12 +37281,12 @@ var ts;
}
}
function emitShebang() {
- var shebang = ts.getShebang(currentSourceFile.text);
+ var shebang = ts.getShebang(currentText);
if (shebang) {
write(shebang);
}
}
- var _a;
+ var _a, _b;
}
function emitFile(jsFilePath, sourceFile) {
emitJavaScript(jsFilePath, sourceFile);
@@ -36866,11 +37346,11 @@ var ts;
if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
var failedLookupLocations = [];
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations };
}
- resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
@@ -36880,8 +37360,8 @@ var ts;
}
}
ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function loadNodeModuleFromFile(candidate, failedLookupLocation, host) {
- return ts.forEach(ts.moduleFileExtensions, tryLoad);
+ function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) {
+ return ts.forEach(extensions, tryLoad);
function tryLoad(ext) {
var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (host.fileExists(fileName)) {
@@ -36893,7 +37373,7 @@ var ts;
}
}
}
- function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) {
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) {
var packageJsonPath = ts.combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
var jsonContent;
@@ -36906,7 +37386,7 @@ var ts;
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
- var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
+ var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
if (result) {
return result;
}
@@ -36916,7 +37396,7 @@ var ts;
// 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(ts.combinePaths(candidate, "index"), failedLookupLocation, host);
+ return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName, directory, host) {
var failedLookupLocations = [];
@@ -36926,11 +37406,11 @@ var ts;
if (baseName !== "node_modules") {
var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host);
+ var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
- result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host);
+ result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
@@ -36956,9 +37436,10 @@ var ts;
var searchName;
var failedLookupLocations = [];
var referencedSourceFile;
+ var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions;
while (true) {
searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName));
- referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) {
+ referencedSourceFile = ts.forEach(extensions, function (extension) {
if (extension === ".tsx" && !compilerOptions.jsx) {
// resolve .tsx files only if jsx support is enabled
// 'logical not' handles both undefined and None cases
@@ -36989,10 +37470,8 @@ var ts;
/* @internal */
ts.defaultInitCompilerOptions = {
module: 1 /* CommonJS */,
- target: 0 /* ES3 */,
+ target: 1 /* ES5 */,
noImplicitAny: false,
- outDir: "built",
- rootDir: ".",
sourceMap: false
};
function createCompilerHost(options, setParentNodes) {
@@ -37397,43 +37876,55 @@ var ts;
if (file.imports) {
return;
}
+ var isJavaScriptFile = ts.isSourceFileJavaScript(file);
var imports;
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var node = _a[_i];
- collect(node, /* allowRelativeModuleNames */ true);
+ collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false);
}
file.imports = imports || emptyArray;
- function collect(node, allowRelativeModuleNames) {
- switch (node.kind) {
- case 222 /* ImportDeclaration */:
- case 221 /* ImportEqualsDeclaration */:
- case 228 /* ExportDeclaration */:
- var moduleNameExpr = ts.getExternalModuleName(node);
- if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
+ return;
+ function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
+ if (!collectOnlyRequireCalls) {
+ switch (node.kind) {
+ case 222 /* ImportDeclaration */:
+ case 221 /* ImportEqualsDeclaration */:
+ case 228 /* ExportDeclaration */:
+ var moduleNameExpr = ts.getExternalModuleName(node);
+ if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
+ break;
+ }
+ if (!moduleNameExpr.text) {
+ break;
+ }
+ if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
+ (imports || (imports = [])).push(moduleNameExpr);
+ }
break;
- }
- if (!moduleNameExpr.text) {
- break;
- }
- if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
- (imports || (imports = [])).push(moduleNameExpr);
- }
- break;
- case 218 /* ModuleDeclaration */:
- if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
- // TypeScript 1.0 spec (April 2014): 12.1.6
- // 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
- ts.forEachChild(node.body, function (node) {
+ case 218 /* ModuleDeclaration */:
+ if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
- // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
- // only through top - level external module names. Relative external module names are not permitted.
- collect(node, /* allowRelativeModuleNames */ false);
- });
- }
- break;
+ // 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
+ ts.forEachChild(node.body, function (node) {
+ // TypeScript 1.0 spec (April 2014): 12.1.6
+ // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
+ // only through top - level external module names. Relative external module names are not permitted.
+ collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls);
+ });
+ }
+ break;
+ }
+ }
+ if (isJavaScriptFile) {
+ if (ts.isRequireCall(node)) {
+ (imports || (imports = [])).push(node.arguments[0]);
+ }
+ else {
+ ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); });
+ }
}
}
}
@@ -37526,7 +38017,6 @@ var ts;
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
- file.isDefaultLib = true;
files.unshift(file);
}
else {
@@ -37604,6 +38094,9 @@ var ts;
commonPathComponents.length = sourcePathComponents.length;
}
});
+ if (!commonPathComponents) {
+ return currentDirectory;
+ }
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
@@ -37689,12 +38182,15 @@ var ts;
if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
+ // Cannot specify module gen that isn't amd or system with --out
+ if (outFile && options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
+ }
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir ||
options.sourceRoot ||
- (options.mapRoot &&
- (!outFile || firstExternalModuleSourceFile !== undefined))) {
+ options.mapRoot) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -38212,20 +38708,20 @@ var ts;
var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (var i = 0; i < sysFiles.length; i++) {
- var name_29 = sysFiles[i];
- if (ts.fileExtensionIs(name_29, ".d.ts")) {
- var baseName = name_29.substr(0, name_29.length - ".d.ts".length);
+ var name_31 = sysFiles[i];
+ if (ts.fileExtensionIs(name_31, ".d.ts")) {
+ var baseName = name_31.substr(0, name_31.length - ".d.ts".length);
if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) {
- fileNames.push(name_29);
+ fileNames.push(name_31);
}
}
- else if (ts.fileExtensionIs(name_29, ".ts")) {
- if (!ts.contains(sysFiles, name_29 + "x")) {
- fileNames.push(name_29);
+ else if (ts.fileExtensionIs(name_31, ".ts")) {
+ if (!ts.contains(sysFiles, name_31 + "x")) {
+ fileNames.push(name_31);
}
}
else {
- fileNames.push(name_29);
+ fileNames.push(name_31);
}
}
}
@@ -38453,12 +38949,12 @@ var ts;
ts.forEach(program.getSourceFiles(), function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
var nameToDeclarations = sourceFile.getNamedDeclarations();
- for (var name_30 in nameToDeclarations) {
- var declarations = ts.getProperty(nameToDeclarations, name_30);
+ for (var name_32 in nameToDeclarations) {
+ var declarations = ts.getProperty(nameToDeclarations, name_32);
if (declarations) {
// First do a quick check to see if the name of the declaration matches the
// last portion of the (possibly) dotted name they're searching for.
- var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_30);
+ var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_32);
if (!matches) {
continue;
}
@@ -38471,14 +38967,14 @@ var ts;
if (!containers) {
return undefined;
}
- matches = patternMatcher.getMatches(containers, name_30);
+ matches = patternMatcher.getMatches(containers, name_32);
if (!matches) {
continue;
}
}
var fileName = sourceFile.fileName;
var matchKind = bestMatchKind(matches);
- rawItems.push({ name: name_30, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
+ rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
}
}
}
@@ -38859,9 +39355,9 @@ var ts;
case 211 /* VariableDeclaration */:
case 163 /* BindingElement */:
var variableDeclarationNode;
- var name_31;
+ var name_33;
if (node.kind === 163 /* BindingElement */) {
- name_31 = node.name;
+ name_33 = node.name;
variableDeclarationNode = node;
// binding elements are added only for variable declarations
// bubble up to the containing variable declaration
@@ -38873,16 +39369,16 @@ var ts;
else {
ts.Debug.assert(!ts.isBindingPattern(node.name));
variableDeclarationNode = node;
- name_31 = node.name;
+ name_33 = node.name;
}
if (ts.isConst(variableDeclarationNode)) {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.constElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement);
}
else if (ts.isLet(variableDeclarationNode)) {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.letElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement);
}
else {
- return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.variableElement);
+ return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement);
}
case 144 /* Constructor */:
return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement);
@@ -39802,7 +40298,7 @@ var ts;
if (!candidates.length) {
// We didn't have any sig help items produced by the TS compiler. If this is a JS
// file, then see if we can figure out anything better.
- if (ts.isJavaScript(sourceFile.fileName)) {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
return createJavaScriptSignatureHelpItems(argumentInfo);
}
return undefined;
@@ -41662,9 +42158,9 @@ var ts;
}
Rules.prototype.getRuleName = function (rule) {
var o = this;
- for (var name_32 in o) {
- if (o[name_32] === rule) {
- return name_32;
+ for (var name_34 in o) {
+ if (o[name_34] === rule) {
+ return name_34;
}
}
throw new Error("Unknown rule");
@@ -42096,7 +42592,7 @@ var ts;
function TokenRangeAccess(from, to, except) {
this.tokens = [];
for (var token = from; token <= to; token++) {
- if (except.indexOf(token) < 0) {
+ if (ts.indexOf(except, token) < 0) {
this.tokens.push(token);
}
}
@@ -43709,13 +44205,18 @@ var ts;
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
- var node = new (ts.getNodeConstructor(kind))(pos, end);
+ var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
- function NodeObject() {
+ function NodeObject(kind, pos, end) {
+ this.kind = kind;
+ this.pos = pos;
+ this.end = end;
+ this.flags = 0 /* None */;
+ this.parent = undefined;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -44198,8 +44699,8 @@ var ts;
})();
var SourceFileObject = (function (_super) {
__extends(SourceFileObject, _super);
- function SourceFileObject() {
- _super.apply(this, arguments);
+ function SourceFileObject(kind, pos, end) {
+ _super.call(this, kind, pos, end);
}
SourceFileObject.prototype.update = function (newText, textChangeRange) {
return ts.updateSourceFile(this, newText, textChangeRange);
@@ -44521,6 +45022,9 @@ var ts;
ClassificationTypeNames.typeAliasName = "type alias name";
ClassificationTypeNames.parameterName = "parameter name";
ClassificationTypeNames.docCommentTagName = "doc comment tag name";
+ ClassificationTypeNames.jsxOpenTagName = "jsx open tag name";
+ ClassificationTypeNames.jsxCloseTagName = "jsx close tag name";
+ ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name";
return ClassificationTypeNames;
})();
ts.ClassificationTypeNames = ClassificationTypeNames;
@@ -44543,6 +45047,9 @@ var ts;
ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName";
ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName";
ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName";
+ ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName";
+ ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName";
+ ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
})(ts.ClassificationType || (ts.ClassificationType = {}));
var ClassificationType = ts.ClassificationType;
function displayPartsToString(displayParts) {
@@ -44922,8 +45429,9 @@ var ts;
};
}
ts.createDocumentRegistry = createDocumentRegistry;
- function preProcessFile(sourceText, readImportFiles) {
+ function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
+ if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
var referencedFiles = [];
var importedFiles = [];
var ambientExternalModules;
@@ -44957,9 +45465,207 @@ var ts;
end: pos + importPath.length
});
}
- function processImport() {
+ /**
+ * Returns true if at least one token was consumed from the stream
+ */
+ function tryConsumeDeclare() {
+ var token = scanner.getToken();
+ if (token === 122 /* DeclareKeyword */) {
+ // declare module "mod"
+ token = scanner.scan();
+ if (token === 125 /* ModuleKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ recordAmbientExternalModule();
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Returns true if at least one token was consumed from the stream
+ */
+ function tryConsumeImport() {
+ var token = scanner.getToken();
+ if (token === 89 /* ImportKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import "mod";
+ recordModuleName();
+ return true;
+ }
+ else {
+ if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import d from "mod";
+ recordModuleName();
+ return true;
+ }
+ }
+ else if (token === 56 /* EqualsToken */) {
+ if (tryConsumeRequireCall(/* skipCurrentToken */ true)) {
+ return true;
+ }
+ }
+ else if (token === 24 /* CommaToken */) {
+ // consume comma and keep going
+ token = scanner.scan();
+ }
+ else {
+ // unknown syntax
+ return true;
+ }
+ }
+ if (token === 15 /* OpenBraceToken */) {
+ token = scanner.scan();
+ // consume "{ a as B, c, d as D}" clauses
+ // make sure that it stops on EOF
+ while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
+ token = scanner.scan();
+ }
+ if (token === 16 /* CloseBraceToken */) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import {a as A} from "mod";
+ // import d, {a, b as B} from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ }
+ else if (token === 37 /* AsteriskToken */) {
+ token = scanner.scan();
+ if (token === 116 /* AsKeyword */) {
+ token = scanner.scan();
+ if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // import * as NS from "mod"
+ // import d, * as NS from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeExport() {
+ var token = scanner.getToken();
+ if (token === 82 /* ExportKeyword */) {
+ token = scanner.scan();
+ if (token === 15 /* OpenBraceToken */) {
+ token = scanner.scan();
+ // consume "{ a as B, c, d as D}" clauses
+ // make sure it stops on EOF
+ while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
+ token = scanner.scan();
+ }
+ if (token === 16 /* CloseBraceToken */) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // export {a as A} from "mod";
+ // export {a, b as B} from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ }
+ else if (token === 37 /* AsteriskToken */) {
+ token = scanner.scan();
+ if (token === 133 /* FromKeyword */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // export * from "mod"
+ recordModuleName();
+ }
+ }
+ }
+ else if (token === 89 /* ImportKeyword */) {
+ token = scanner.scan();
+ if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
+ token = scanner.scan();
+ if (token === 56 /* EqualsToken */) {
+ if (tryConsumeRequireCall(/* skipCurrentToken */ true)) {
+ return true;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeRequireCall(skipCurrentToken) {
+ var token = skipCurrentToken ? scanner.scan() : scanner.getToken();
+ if (token === 127 /* RequireKeyword */) {
+ token = scanner.scan();
+ if (token === 17 /* OpenParenToken */) {
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // require("mod");
+ recordModuleName();
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ function tryConsumeDefine() {
+ var token = scanner.getToken();
+ if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") {
+ token = scanner.scan();
+ if (token !== 17 /* OpenParenToken */) {
+ return true;
+ }
+ token = scanner.scan();
+ if (token === 9 /* StringLiteral */) {
+ // looks like define ("modname", ... - skip string literal and comma
+ token = scanner.scan();
+ if (token === 24 /* CommaToken */) {
+ token = scanner.scan();
+ }
+ else {
+ // unexpected token
+ return true;
+ }
+ }
+ // should be start of dependency list
+ if (token !== 19 /* OpenBracketToken */) {
+ return true;
+ }
+ // skip open bracket
+ token = scanner.scan();
+ var i = 0;
+ // scan until ']' or EOF
+ while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
+ // record string literals as module names
+ if (token === 9 /* StringLiteral */) {
+ recordModuleName();
+ i++;
+ }
+ token = scanner.scan();
+ }
+ return true;
+ }
+ return false;
+ }
+ function processImports() {
scanner.setText(sourceText);
- var token = scanner.scan();
+ scanner.scan();
// Look for:
// import "mod";
// import d from "mod"
@@ -44971,152 +45677,26 @@ var ts;
// export * from "mod"
// export {a as b} from "mod"
// export import i = require("mod")
- while (token !== 1 /* EndOfFileToken */) {
- if (token === 122 /* DeclareKeyword */) {
- // declare module "mod"
- token = scanner.scan();
- if (token === 125 /* ModuleKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- recordAmbientExternalModule();
- continue;
- }
- }
+ // (for JavaScript files) require("mod")
+ while (true) {
+ if (scanner.getToken() === 1 /* EndOfFileToken */) {
+ break;
}
- else if (token === 89 /* ImportKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import "mod";
- recordModuleName();
- continue;
- }
- else {
- if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import d from "mod";
- recordModuleName();
- continue;
- }
- }
- else if (token === 56 /* EqualsToken */) {
- token = scanner.scan();
- if (token === 127 /* RequireKeyword */) {
- token = scanner.scan();
- if (token === 17 /* OpenParenToken */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import i = require("mod");
- recordModuleName();
- continue;
- }
- }
- }
- }
- else if (token === 24 /* CommaToken */) {
- // consume comma and keep going
- token = scanner.scan();
- }
- else {
- // unknown syntax
- continue;
- }
- }
- if (token === 15 /* OpenBraceToken */) {
- token = scanner.scan();
- // consume "{ a as B, c, d as D}" clauses
- while (token !== 16 /* CloseBraceToken */) {
- token = scanner.scan();
- }
- if (token === 16 /* CloseBraceToken */) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import {a as A} from "mod";
- // import d, {a, b as B} from "mod"
- recordModuleName();
- }
- }
- }
- }
- else if (token === 37 /* AsteriskToken */) {
- token = scanner.scan();
- if (token === 116 /* AsKeyword */) {
- token = scanner.scan();
- if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // import * as NS from "mod"
- // import d, * as NS from "mod"
- recordModuleName();
- }
- }
- }
- }
- }
- }
+ // check if at least one of alternative have moved scanner forward
+ if (tryConsumeDeclare() ||
+ tryConsumeImport() ||
+ tryConsumeExport() ||
+ (detectJavaScriptImports && (tryConsumeRequireCall(/* skipCurrentToken */ false) || tryConsumeDefine()))) {
+ continue;
}
- else if (token === 82 /* ExportKeyword */) {
- token = scanner.scan();
- if (token === 15 /* OpenBraceToken */) {
- token = scanner.scan();
- // consume "{ a as B, c, d as D}" clauses
- while (token !== 16 /* CloseBraceToken */) {
- token = scanner.scan();
- }
- if (token === 16 /* CloseBraceToken */) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // export {a as A} from "mod";
- // export {a, b as B} from "mod"
- recordModuleName();
- }
- }
- }
- }
- else if (token === 37 /* AsteriskToken */) {
- token = scanner.scan();
- if (token === 133 /* FromKeyword */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // export * from "mod"
- recordModuleName();
- }
- }
- }
- else if (token === 89 /* ImportKeyword */) {
- token = scanner.scan();
- if (token === 69 /* Identifier */ || ts.isKeyword(token)) {
- token = scanner.scan();
- if (token === 56 /* EqualsToken */) {
- token = scanner.scan();
- if (token === 127 /* RequireKeyword */) {
- token = scanner.scan();
- if (token === 17 /* OpenParenToken */) {
- token = scanner.scan();
- if (token === 9 /* StringLiteral */) {
- // export import i = require("mod");
- recordModuleName();
- }
- }
- }
- }
- }
- }
+ else {
+ scanner.scan();
}
- token = scanner.scan();
}
scanner.setText(undefined);
}
if (readImportFiles) {
- processImport();
+ processImports();
}
processTripleSlashDirectives();
return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules };
@@ -45547,7 +46127,7 @@ var ts;
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
- if (ts.isJavaScript(fileName)) {
+ if (ts.isSourceFileJavaScript(targetSourceFile)) {
return getJavaScriptSemanticDiagnostics(targetSourceFile);
}
// Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
@@ -45759,7 +46339,7 @@ var ts;
var typeChecker = program.getTypeChecker();
var syntacticStart = new Date().getTime();
var sourceFile = getValidSourceFile(fileName);
- var isJavaScriptFile = ts.isJavaScript(fileName);
+ var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile);
var isJsDocTagName = false;
var start = new Date().getTime();
var currentToken = ts.getTokenAtPosition(sourceFile, position);
@@ -46393,8 +46973,8 @@ var ts;
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
- var name_33 = element.propertyName || element.name;
- exisingImportsOrExports[name_33.text] = true;
+ var name_35 = element.propertyName || element.name;
+ exisingImportsOrExports[name_35.text] = true;
}
if (ts.isEmpty(exisingImportsOrExports)) {
return exportsOfModule;
@@ -46426,7 +47006,10 @@ var ts;
}
var existingName = void 0;
if (m.kind === 163 /* BindingElement */ && m.propertyName) {
- existingName = m.propertyName.text;
+ // include only identifiers in completion list
+ if (m.propertyName.kind === 69 /* Identifier */) {
+ existingName = m.propertyName.text;
+ }
}
else {
// TODO(jfreeman): Account for computed property name
@@ -46466,46 +47049,43 @@ var ts;
return undefined;
}
var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName;
- var entries;
if (isJsDocTagName) {
// If the current position is a jsDoc tag name, only tag names should be provided for completion
return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() };
}
- if (isRightOfDot && ts.isJavaScript(fileName)) {
- entries = getCompletionEntriesFromSymbols(symbols);
- ts.addRange(entries, getJavaScriptCompletionEntries());
+ var sourceFile = getValidSourceFile(fileName);
+ var entries = [];
+ if (isRightOfDot && ts.isSourceFileJavaScript(sourceFile)) {
+ var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries);
+ ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, uniqueNames));
}
else {
if (!symbols || symbols.length === 0) {
return undefined;
}
- entries = getCompletionEntriesFromSymbols(symbols);
+ getCompletionEntriesFromSymbols(symbols, entries);
}
// Add keywords if this is not a member completion list
if (!isMemberCompletion && !isJsDocTagName) {
ts.addRange(entries, keywordCompletions);
}
return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
- function getJavaScriptCompletionEntries() {
+ function getJavaScriptCompletionEntries(sourceFile, uniqueNames) {
var entries = [];
- var allNames = {};
var target = program.getCompilerOptions().target;
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile = _a[_i];
- var nameTable = getNameTable(sourceFile);
- for (var name_34 in nameTable) {
- if (!allNames[name_34]) {
- allNames[name_34] = name_34;
- var displayName = getCompletionEntryDisplayName(name_34, target, /*performCharacterChecks:*/ true);
- if (displayName) {
- var entry = {
- name: displayName,
- kind: ScriptElementKind.warning,
- kindModifiers: "",
- sortText: "1"
- };
- entries.push(entry);
- }
+ var nameTable = getNameTable(sourceFile);
+ for (var name_36 in nameTable) {
+ if (!uniqueNames[name_36]) {
+ uniqueNames[name_36] = name_36;
+ var displayName = getCompletionEntryDisplayName(name_36, target, /*performCharacterChecks:*/ true);
+ if (displayName) {
+ var entry = {
+ name: displayName,
+ kind: ScriptElementKind.warning,
+ kindModifiers: "",
+ sortText: "1"
+ };
+ entries.push(entry);
}
}
}
@@ -46543,25 +47123,24 @@ var ts;
sortText: "0"
};
}
- function getCompletionEntriesFromSymbols(symbols) {
+ function getCompletionEntriesFromSymbols(symbols, entries) {
var start = new Date().getTime();
- var entries = [];
+ var uniqueNames = {};
if (symbols) {
- var nameToSymbol = {};
for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
var symbol = symbols_3[_i];
var entry = createCompletionEntry(symbol, location);
if (entry) {
var id = ts.escapeIdentifier(entry.name);
- if (!ts.lookUp(nameToSymbol, id)) {
+ if (!ts.lookUp(uniqueNames, id)) {
entries.push(entry);
- nameToSymbol[id] = symbol;
+ uniqueNames[id] = id;
}
}
}
}
log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start));
- return entries;
+ return uniqueNames;
}
}
function getCompletionEntryDetails(fileName, position, entryName) {
@@ -46762,16 +47341,16 @@ var ts;
case ScriptElementKind.parameterElement:
case ScriptElementKind.localVariableElement:
// If it is call or construct signature of lambda's write type name
- displayParts.push(ts.punctuationPart(54 /* ColonToken */));
+ displayParts.push(ts.punctuationPart(ts.SyntaxKind.ColonToken));
displayParts.push(ts.spacePart());
if (useConstructSignatures) {
- displayParts.push(ts.keywordPart(92 /* NewKeyword */));
+ displayParts.push(ts.keywordPart(ts.SyntaxKind.NewKeyword));
displayParts.push(ts.spacePart());
}
- if (!(type.flags & 65536 /* Anonymous */)) {
- ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */));
+ if (!(type.flags & ts.TypeFlags.Anonymous)) {
+ ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, ts.SymbolFormatFlags.WriteTypeParametersOrArguments));
}
- addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */);
+ addSignatureDisplayParts(signature, allSignatures, ts.TypeFormatFlags.WriteArrowStyleSignature);
break;
default:
// Just signature
@@ -48396,19 +48975,19 @@ var ts;
if (isNameOfPropertyAssignment(node)) {
var objectLiteral = node.parent.parent;
var contextualType = typeChecker.getContextualType(objectLiteral);
- var name_35 = node.text;
+ var name_37 = node.text;
if (contextualType) {
if (contextualType.flags & 16384 /* Union */) {
// This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types)
// if not, search the constituent types for the property
- var unionProperty = contextualType.getProperty(name_35);
+ var unionProperty = contextualType.getProperty(name_37);
if (unionProperty) {
return [unionProperty];
}
else {
var result_4 = [];
ts.forEach(contextualType.types, function (t) {
- var symbol = t.getProperty(name_35);
+ var symbol = t.getProperty(name_37);
if (symbol) {
result_4.push(symbol);
}
@@ -48417,7 +48996,7 @@ var ts;
}
}
else {
- var symbol_1 = contextualType.getProperty(name_35);
+ var symbol_1 = contextualType.getProperty(name_37);
if (symbol_1) {
return [symbol_1];
}
@@ -48828,6 +49407,9 @@ var ts;
case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName;
case 17 /* parameterName */: return ClassificationTypeNames.parameterName;
case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName;
+ case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName;
+ case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName;
+ case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName;
}
}
function convertClassifications(classifications) {
@@ -49097,6 +49679,21 @@ var ts;
return 17 /* parameterName */;
}
return;
+ case 235 /* JsxOpeningElement */:
+ if (token.parent.tagName === token) {
+ return 19 /* jsxOpenTagName */;
+ }
+ return;
+ case 237 /* JsxClosingElement */:
+ if (token.parent.tagName === token) {
+ return 20 /* jsxCloseTagName */;
+ }
+ return;
+ case 234 /* JsxSelfClosingElement */:
+ if (token.parent.tagName === token) {
+ return 21 /* jsxSelfClosingTagName */;
+ }
+ return;
}
}
return 2 /* identifier */;
@@ -50021,18 +50618,8 @@ var ts;
ts.getDefaultLibFilePath = getDefaultLibFilePath;
function initializeServices() {
ts.objectAllocator = {
- getNodeConstructor: function (kind) {
- function Node(pos, end) {
- this.pos = pos;
- this.end = end;
- this.flags = 0 /* None */;
- this.parent = undefined;
- }
- var proto = kind === 248 /* SourceFile */ ? new SourceFileObject() : new NodeObject();
- proto.kind = kind;
- Node.prototype = proto;
- return Node;
- },
+ getNodeConstructor: function () { return NodeObject; },
+ getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
getSignatureConstructor: function () { return SignatureObject; }
@@ -51102,7 +51689,8 @@ var ts;
};
CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
- var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()));
+ // for now treat files as JavaScript
+ var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
var convertResult = {
referencedFiles: [],
importedFiles: [],
@@ -51166,7 +51754,7 @@ var ts;
TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
try {
if (this.documentRegistry === undefined) {
- this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
+ this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
}
var hostAdapter = new LanguageServiceShimHostAdapter(host);
var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry);
@@ -51199,7 +51787,7 @@ var ts;
TypeScriptServicesFactory.prototype.close = function () {
// Forget all the registered shims
this._shims = [];
- this.documentRegistry = ts.createDocumentRegistry();
+ this.documentRegistry = undefined;
};
TypeScriptServicesFactory.prototype.registerShim = function (shim) {
this._shims.push(shim);
diff --git a/package.json b/package.json
index 7b8abfaae43..261cdfa64b7 100644
--- a/package.json
+++ b/package.json
@@ -35,7 +35,8 @@
"browserify": "latest",
"istanbul": "latest",
"mocha-fivemat-progress-reporter": "latest",
- "tslint": "latest",
+ "tslint": "next",
+ "typescript": "next",
"tsd": "latest"
},
"scripts": {
diff --git a/scripts/tslint/booleanTriviaRule.ts b/scripts/tslint/booleanTriviaRule.ts
index be32a870ff4..93c312ab870 100644
--- a/scripts/tslint/booleanTriviaRule.ts
+++ b/scripts/tslint/booleanTriviaRule.ts
@@ -1,6 +1,5 @@
-///
-///
-
+import * as Lint from "tslint/lib/lint";
+import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING_FACTORY = (name: string, currently: string) => `Tag boolean argument as '${name}' (currently '${currently}')`;
@@ -19,7 +18,7 @@ class BooleanTriviaWalker extends Lint.RuleWalker {
visitCallExpression(node: ts.CallExpression) {
super.visitCallExpression(node);
- if (node.arguments) {
+ if (node.arguments) {
const targetCallSignature = this.checker.getResolvedSignature(node);
if (!!targetCallSignature) {
const targetParameters = targetCallSignature.getParameters();
@@ -37,7 +36,7 @@ class BooleanTriviaWalker extends Lint.RuleWalker {
let triviaContent: string;
const ranges = ts.getLeadingCommentRanges(arg.getFullText(), 0);
if (ranges && ranges.length === 1 && ranges[0].kind === ts.SyntaxKind.MultiLineCommentTrivia) {
- triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); //+/-2 to remove /**/
+ triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); // +/-2 to remove /**/
}
if (triviaContent !== param.getName()) {
this.addFailure(this.createFailure(arg.getStart(source), arg.getWidth(source), Rule.FAILURE_STRING_FACTORY(param.getName(), triviaContent)));
@@ -45,6 +44,6 @@ class BooleanTriviaWalker extends Lint.RuleWalker {
}
}
}
- }
+ }
}
}
diff --git a/scripts/tslint/nextLineRule.ts b/scripts/tslint/nextLineRule.ts
index 6d803fc7f88..d25652f7bce 100644
--- a/scripts/tslint/nextLineRule.ts
+++ b/scripts/tslint/nextLineRule.ts
@@ -1,5 +1,5 @@
-///
-///
+import * as Lint from "tslint/lib/lint";
+import * as ts from "typescript";
const OPTION_CATCH = "check-catch";
const OPTION_ELSE = "check-else";
diff --git a/scripts/tslint/noInOperatorRule.ts b/scripts/tslint/noInOperatorRule.ts
new file mode 100644
index 00000000000..527e8c1b895
--- /dev/null
+++ b/scripts/tslint/noInOperatorRule.ts
@@ -0,0 +1,20 @@
+import * as Lint from "tslint/lib/lint";
+import * as ts from "typescript";
+
+
+export class Rule extends Lint.Rules.AbstractRule {
+ public static FAILURE_STRING = "Don't use the 'in' keyword - use 'hasProperty' to check for key presence instead";
+
+ public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
+ return this.applyWithWalker(new InWalker(sourceFile, this.getOptions()));
+ }
+}
+
+class InWalker extends Lint.RuleWalker {
+ visitNode(node: ts.Node) {
+ super.visitNode(node);
+ if (node.kind === ts.SyntaxKind.InKeyword && node.parent && node.parent.kind === ts.SyntaxKind.BinaryExpression) {
+ this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
+ }
+ }
+}
diff --git a/scripts/tslint/noNullRule.ts b/scripts/tslint/noNullRule.ts
index 2a2c5bc3717..8e9deca996b 100644
--- a/scripts/tslint/noNullRule.ts
+++ b/scripts/tslint/noNullRule.ts
@@ -1,5 +1,5 @@
-///
-///
+import * as Lint from "tslint/lib/lint";
+import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
diff --git a/scripts/tslint/preferConstRule.ts b/scripts/tslint/preferConstRule.ts
index 29160a9c634..aaa1b0e53d5 100644
--- a/scripts/tslint/preferConstRule.ts
+++ b/scripts/tslint/preferConstRule.ts
@@ -1,5 +1,5 @@
-///
-///
+import * as Lint from "tslint/lib/lint";
+import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
@@ -85,12 +85,12 @@ class PreferConstWalker extends Lint.RuleWalker {
visitBinaryExpression(node: ts.BinaryExpression) {
if (isAssignmentOperator(node.operatorToken.kind)) {
- this.visitLHSExpressions(node.left);
+ this.visitLeftHandSideExpression(node.left);
}
super.visitBinaryExpression(node);
}
- private visitLHSExpressions(node: ts.Expression) {
+ private visitLeftHandSideExpression(node: ts.Expression) {
while (node.kind === ts.SyntaxKind.ParenthesizedExpression) {
node = (node as ts.ParenthesizedExpression).expression;
}
@@ -101,23 +101,25 @@ class PreferConstWalker extends Lint.RuleWalker {
this.visitBindingLiteralExpression(node as (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression));
}
}
-
+
private visitBindingLiteralExpression(node: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) {
if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) {
const pattern = node as ts.ObjectLiteralExpression;
for (const element of pattern.properties) {
- if (element.name.kind === ts.SyntaxKind.Identifier) {
- this.markAssignment(element.name as ts.Identifier)
+ const kind = element.kind;
+
+ if (kind === ts.SyntaxKind.ShorthandPropertyAssignment) {
+ this.markAssignment((element as ts.ShorthandPropertyAssignment).name);
}
- else if (isBindingPattern(element.name)) {
- this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern);
+ else if (kind === ts.SyntaxKind.PropertyAssignment) {
+ this.visitLeftHandSideExpression((element as ts.PropertyAssignment).initializer);
}
}
}
else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) {
const pattern = node as ts.ArrayLiteralExpression;
for (const element of pattern.elements) {
- this.visitLHSExpressions(element);
+ this.visitLeftHandSideExpression(element);
}
}
}
@@ -145,7 +147,7 @@ class PreferConstWalker extends Lint.RuleWalker {
private visitAnyUnaryExpression(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression) {
if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) {
- this.visitLHSExpressions(node.operand);
+ this.visitLeftHandSideExpression(node.operand);
}
}
@@ -211,12 +213,12 @@ class PreferConstWalker extends Lint.RuleWalker {
}
}
- private collectNameIdentifiers(value: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map) {
+ private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map) {
if (node.kind === ts.SyntaxKind.Identifier) {
- table[(node as ts.Identifier).text] = {declaration: value, usages: 0};
+ table[(node as ts.Identifier).text] = { declaration, usages: 0 };
}
else {
- this.collectBindingPatternIdentifiers(value, node as ts.BindingPattern, table);
+ this.collectBindingPatternIdentifiers(declaration, node as ts.BindingPattern, table);
}
}
diff --git a/scripts/tslint/typeOperatorSpacingRule.ts b/scripts/tslint/typeOperatorSpacingRule.ts
index 23925493340..7ceef2372bf 100644
--- a/scripts/tslint/typeOperatorSpacingRule.ts
+++ b/scripts/tslint/typeOperatorSpacingRule.ts
@@ -1,5 +1,5 @@
-///
-///
+import * as Lint from "tslint/lib/lint";
+import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
@@ -13,10 +13,10 @@ export class Rule extends Lint.Rules.AbstractRule {
class TypeOperatorSpacingWalker extends Lint.RuleWalker {
public visitNode(node: ts.Node) {
if (node.kind === ts.SyntaxKind.UnionType || node.kind === ts.SyntaxKind.IntersectionType) {
- let types = (node).types;
+ const types = (node).types;
let expectedStart = types[0].end + 2; // space, | or &
for (let i = 1; i < types.length; i++) {
- let currentType = types[i];
+ const currentType = types[i];
if (expectedStart !== currentType.pos || currentType.getLeadingTriviaWidth() !== 1) {
const failure = this.createFailure(currentType.pos, currentType.getWidth(), Rule.FAILURE_STRING);
this.addFailure(failure);
diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts
index 2993ec3aa0c..7561783d139 100644
--- a/src/compiler/binder.ts
+++ b/src/compiler/binder.ts
@@ -139,6 +139,8 @@ namespace ts {
file.classifiableNames = classifiableNames;
}
+ file = undefined;
+ options = undefined;
parent = undefined;
container = undefined;
blockScopeContainer = undefined;
@@ -175,9 +177,14 @@ namespace ts {
symbol.members = {};
}
- if (symbolFlags & SymbolFlags.Value && !symbol.valueDeclaration) {
- symbol.valueDeclaration = node;
- }
+ if (symbolFlags & SymbolFlags.Value) {
+ const valueDeclaration = symbol.valueDeclaration;
+ if (!valueDeclaration ||
+ (valueDeclaration.kind !== node.kind && valueDeclaration.kind === SyntaxKind.ModuleDeclaration)) {
+ // other kinds of value declarations take precedence over modules
+ symbol.valueDeclaration = node;
+ }
+ }
}
// Should not be called on a declaration with a computed property name,
@@ -189,7 +196,7 @@ namespace ts {
}
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (node.name).expression;
- // treat computed property names where expression is string/numeric literal as just string/numeric literal
+ // treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteral(nameExpression.kind)) {
return (nameExpression).text;
}
@@ -450,7 +457,7 @@ namespace ts {
/**
* Returns true if node and its subnodes were successfully traversed.
- * Returning false means that node was not examined and caller needs to dive into the node himself.
+ * Returning false means that node was not examined and caller needs to dive into the node himself.
*/
function bindReachableStatement(node: Node): void {
if (checkUnreachable(node)) {
@@ -560,7 +567,7 @@ namespace ts {
}
function bindIfStatement(n: IfStatement): void {
- // denotes reachability state when entering 'thenStatement' part of the if statement:
+ // denotes reachability state when entering 'thenStatement' part of the if statement:
// i.e. if condition is false then thenStatement is unreachable
const ifTrueState = n.expression.kind === SyntaxKind.FalseKeyword ? Reachability.Unreachable : currentReachabilityState;
// denotes reachability state when entering 'elseStatement':
@@ -1179,7 +1186,7 @@ namespace ts {
return checkStrictModePrefixUnaryExpression(node);
case SyntaxKind.WithStatement:
return checkStrictModeWithStatement(node);
- case SyntaxKind.ThisKeyword:
+ case SyntaxKind.ThisType:
seenThisKeyword = true;
return;
@@ -1528,7 +1535,7 @@ namespace ts {
// unreachable code is reported if
// - user has explicitly asked about it AND
- // - statement is in not ambient context (statements in ambient context is already an error
+ // - statement is in not ambient context (statements in ambient context is already an error
// so we should not report extras) AND
// - node is not variable statement OR
// - node is block scoped variable statement OR
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts
index ae57a2c6ed4..18667e46733 100644
--- a/src/compiler/checker.ts
+++ b/src/compiler/checker.ts
@@ -46,6 +46,7 @@ namespace ts {
const compilerOptions = host.getCompilerOptions();
const languageVersion = compilerOptions.target || ScriptTarget.ES3;
const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None;
+ const allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ModuleKind.System;
const emitResolver = createResolver();
@@ -123,8 +124,8 @@ namespace ts {
const noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
- const anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false);
- const unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false);
+ const anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false);
+ const unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false);
const globals: SymbolTable = {};
@@ -141,9 +142,6 @@ namespace ts {
let globalRegExpType: ObjectType;
let globalTemplateStringsArrayType: ObjectType;
let globalESSymbolType: ObjectType;
- let jsxElementType: ObjectType;
- /** Lazily loaded, use getJsxIntrinsicElementType() */
- let jsxIntrinsicElementsType: ObjectType;
let globalIterableType: GenericType;
let globalIteratorType: GenericType;
let globalIterableIteratorType: GenericType;
@@ -201,15 +199,24 @@ namespace ts {
"symbol": {
type: esSymbolType,
flags: TypeFlags.ESSymbol
+ },
+ "undefined": {
+ type: undefinedType,
+ flags: TypeFlags.ContainsUndefinedOrNull
}
};
+ let jsxElementType: ObjectType;
+ /** Things we lazy load from the JSX namespace */
+ const jsxTypes: Map = {};
const JsxNames = {
JSX: "JSX",
IntrinsicElements: "IntrinsicElements",
ElementClass: "ElementClass",
ElementAttributesPropertyNameContainer: "ElementAttributesProperty",
- Element: "Element"
+ Element: "Element",
+ IntrinsicAttributes: "IntrinsicAttributes",
+ IntrinsicClassAttributes: "IntrinsicClassAttributes"
};
const subtypeRelation: Map = {};
@@ -300,7 +307,12 @@ namespace ts {
target.constEnumOnlyModule = false;
}
target.flags |= source.flags;
- if (!target.valueDeclaration && source.valueDeclaration) target.valueDeclaration = source.valueDeclaration;
+ if (source.valueDeclaration &&
+ (!target.valueDeclaration ||
+ (target.valueDeclaration.kind === SyntaxKind.ModuleDeclaration && source.valueDeclaration.kind !== SyntaxKind.ModuleDeclaration))) {
+ // other kinds of value declarations take precedence over modules
+ target.valueDeclaration = source.valueDeclaration;
+ }
forEach(source.declarations, node => {
target.declarations.push(node);
});
@@ -383,6 +395,14 @@ namespace ts {
return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node);
}
+ /** Is this type one of the apparent types created from the primitive types. */
+ function isPrimitiveApparentType(type: Type): boolean {
+ return type === globalStringType ||
+ type === globalNumberType ||
+ type === globalBooleanType ||
+ type === globalESSymbolType;
+ }
+
function getSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags): Symbol {
if (meaning && hasProperty(symbols, name)) {
const symbol = symbols[name];
@@ -483,15 +503,41 @@ namespace ts {
// Locals of a source file are not in scope (because they get merged into the global symbol table)
if (location.locals && !isGlobalSourceFile(location)) {
if (result = getSymbol(location.locals, name, meaning)) {
- // Type parameters of a function are in scope in the entire function declaration, including the parameter
- // list and return type. However, local types are only in scope in the function body.
- if (!(meaning & SymbolFlags.Type) ||
- !(result.flags & (SymbolFlags.Type & ~SymbolFlags.TypeParameter)) ||
- !isFunctionLike(location) ||
- lastLocation === (location).body) {
+ let useResult = true;
+ if (isFunctionLike(location) && lastLocation && lastLocation !== (location).body) {
+ // symbol lookup restrictions for function-like declarations
+ // - Type parameters of a function are in scope in the entire function declaration, including the parameter
+ // list and return type. However, local types are only in scope in the function body.
+ // - parameters are only in the scope of function body
+ if (meaning & result.flags & SymbolFlags.Type) {
+ useResult = result.flags & SymbolFlags.TypeParameter
+ // type parameters are visible in parameter list, return type and type parameter list
+ ? lastLocation === (location).type ||
+ lastLocation.kind === SyntaxKind.Parameter ||
+ lastLocation.kind === SyntaxKind.TypeParameter
+ // local types not visible outside the function body
+ : false;
+ }
+ if (meaning & SymbolFlags.Value && result.flags & SymbolFlags.FunctionScopedVariable) {
+ // parameters are visible only inside function body, parameter list and return type
+ // technically for parameter list case here we might mix parameters and variables declared in function,
+ // however it is detected separately when checking initializers of parameters
+ // to make sure that they reference no variables declared after them.
+ useResult =
+ lastLocation.kind === SyntaxKind.Parameter ||
+ (
+ lastLocation === (location).type &&
+ result.valueDeclaration.kind === SyntaxKind.Parameter
+ );
+ }
+ }
+
+ if (useResult) {
break loop;
}
- result = undefined;
+ else {
+ result = undefined;
+ }
}
}
switch (location.kind) {
@@ -513,7 +559,7 @@ namespace ts {
}
// Because of module/namespace merging, a module's exports are in scope,
- // yet we never want to treat an export specifier as putting a member in scope.
+ // yet we never want to treat an export specifier as putting a member in scope.
// Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
// Two things to note about this:
// 1. We have to check this without calling getSymbol. The problem with calling getSymbol
@@ -749,9 +795,12 @@ namespace ts {
const moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier);
if (moduleSymbol) {
const exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]);
- if (!exportDefaultSymbol) {
+ if (!exportDefaultSymbol && !allowSyntheticDefaultImports) {
error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
}
+ else if (!exportDefaultSymbol && allowSyntheticDefaultImports) {
+ return resolveSymbol(moduleSymbol.exports["export="]) || resolveSymbol(moduleSymbol);
+ }
return exportDefaultSymbol;
}
}
@@ -1009,16 +1058,12 @@ namespace ts {
// Module names are escaped in our symbol table. However, string literal values aren't.
// Escape the name in the "require(...)" clause to ensure we find the right symbol.
- let moduleName = escapeIdentifier(moduleReferenceLiteral.text);
+ const moduleName = escapeIdentifier(moduleReferenceLiteral.text);
if (moduleName === undefined) {
return;
}
- if (moduleName.indexOf("!") >= 0) {
- moduleName = moduleName.substr(0, moduleName.indexOf("!"));
- }
-
const isRelative = isExternalModuleNameRelative(moduleName);
if (!isRelative) {
const symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule);
@@ -1074,39 +1119,81 @@ namespace ts {
return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol));
}
- function extendExportSymbols(target: SymbolTable, source: SymbolTable) {
+ interface ExportCollisionTracker {
+ specifierText: string;
+ exportsWithDuplicate: ExportDeclaration[];
+ }
+
+ /**
+ * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
+ * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
+ */
+ function extendExportSymbols(target: SymbolTable, source: SymbolTable, lookupTable?: Map, exportNode?: ExportDeclaration) {
for (const id in source) {
if (id !== "default" && !hasProperty(target, id)) {
target[id] = source[id];
+ if (lookupTable && exportNode) {
+ lookupTable[id] = {
+ specifierText: getTextOfNode(exportNode.moduleSpecifier)
+ } as ExportCollisionTracker;
+ }
+ }
+ else if (lookupTable && exportNode && id !== "default" && hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) {
+ if (!lookupTable[id].exportsWithDuplicate) {
+ lookupTable[id].exportsWithDuplicate = [exportNode];
+ }
+ else {
+ lookupTable[id].exportsWithDuplicate.push(exportNode);
+ }
}
}
}
function getExportsForModule(moduleSymbol: Symbol): SymbolTable {
- let result: SymbolTable;
const visitedSymbols: Symbol[] = [];
- visit(moduleSymbol);
- return result || moduleSymbol.exports;
+ return visit(moduleSymbol) || moduleSymbol.exports;
// The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
// module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
- function visit(symbol: Symbol) {
- if (symbol && symbol.flags & SymbolFlags.HasExports && !contains(visitedSymbols, symbol)) {
- visitedSymbols.push(symbol);
- if (symbol !== moduleSymbol) {
- if (!result) {
- result = cloneSymbolTable(moduleSymbol.exports);
- }
- extendExportSymbols(result, symbol.exports);
- }
- // All export * declarations are collected in an __export symbol by the binder
- const exportStars = symbol.exports["__export"];
- if (exportStars) {
- for (const node of exportStars.declarations) {
- visit(resolveExternalModuleName(node, (node).moduleSpecifier));
- }
- }
+ function visit(symbol: Symbol): SymbolTable {
+ if (!(symbol && symbol.flags & SymbolFlags.HasExports && !contains(visitedSymbols, symbol))) {
+ return;
}
+ visitedSymbols.push(symbol);
+ const symbols = cloneSymbolTable(symbol.exports);
+ // All export * declarations are collected in an __export symbol by the binder
+ const exportStars = symbol.exports["__export"];
+ if (exportStars) {
+ const nestedSymbols: SymbolTable = {};
+ const lookupTable: Map = {};
+ for (const node of exportStars.declarations) {
+ const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier);
+ const exportedSymbols = visit(resolvedModule);
+ extendExportSymbols(
+ nestedSymbols,
+ exportedSymbols,
+ lookupTable,
+ node as ExportDeclaration
+ );
+ }
+ for (const id in lookupTable) {
+ const { exportsWithDuplicate } = lookupTable[id];
+ // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
+ if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || hasProperty(symbols, id)) {
+ continue;
+ }
+ for (const node of exportsWithDuplicate) {
+ diagnostics.add(createDiagnosticForNode(
+ node,
+ Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity,
+ lookupTable[id].specifierText,
+ id
+ ));
+ }
+ }
+ extendExportSymbols(symbols, nestedSymbols);
+ }
+ return symbols;
}
}
@@ -1500,9 +1587,9 @@ namespace ts {
return result;
}
- function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string {
+ function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string {
const writer = getSingleLineStringWriter();
- getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags);
+ getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind);
const result = writer.string();
releaseStringWriter(writer);
@@ -1854,7 +1941,7 @@ namespace ts {
if (flags & TypeFormatFlags.InElementType) {
writePunctuation(writer, SyntaxKind.OpenParenToken);
}
- buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, symbolStack);
+ buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, /*kind*/ undefined, symbolStack);
if (flags & TypeFormatFlags.InElementType) {
writePunctuation(writer, SyntaxKind.CloseParenToken);
}
@@ -1866,7 +1953,7 @@ namespace ts {
}
writeKeyword(writer, SyntaxKind.NewKeyword);
writeSpace(writer);
- buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, symbolStack);
+ buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, /*kind*/ undefined, symbolStack);
if (flags & TypeFormatFlags.InElementType) {
writePunctuation(writer, SyntaxKind.CloseParenToken);
}
@@ -1880,15 +1967,12 @@ namespace ts {
writer.writeLine();
writer.increaseIndent();
for (const signature of resolved.callSignatures) {
- buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack);
+ buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack);
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
for (const signature of resolved.constructSignatures) {
- writeKeyword(writer, SyntaxKind.NewKeyword);
- writeSpace(writer);
-
- buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack);
+ buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, SignatureKind.Construct, symbolStack);
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
@@ -1929,7 +2013,7 @@ namespace ts {
if (p.flags & SymbolFlags.Optional) {
writePunctuation(writer, SyntaxKind.QuestionToken);
}
- buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack);
+ buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack);
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
@@ -2049,7 +2133,12 @@ namespace ts {
buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack);
}
- function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) {
+ function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind, symbolStack?: Symbol[]) {
+ if (kind === SignatureKind.Construct) {
+ writeKeyword(writer, SyntaxKind.NewKeyword);
+ writeSpace(writer);
+ }
+
if (signature.target && (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature)) {
// Instantiated signature, write type arguments instead
// This is achieved by passing in the mapper separately
@@ -2283,7 +2372,7 @@ namespace ts {
return false;
}
resolutionTargets.push(target);
- resolutionResults.push(true);
+ resolutionResults.push(/*items*/ true);
resolutionPropertyNames.push(propertyName);
return true;
}
@@ -3182,7 +3271,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
- case SyntaxKind.StringLiteral:
+ case SyntaxKind.StringLiteralType:
return true;
case SyntaxKind.ArrayType:
return isIndependentType((node).elementType);
@@ -3355,7 +3444,7 @@ namespace ts {
function getDefaultConstructSignatures(classType: InterfaceType): Signature[] {
if (!hasClassBaseType(classType)) {
- return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)];
+ return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)];
}
const baseConstructorType = getBaseConstructorTypeOfClass(classType);
const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct);
@@ -3836,8 +3925,14 @@ namespace ts {
let minArgumentCount = -1;
for (let i = 0, n = declaration.parameters.length; i < n; i++) {
const param = declaration.parameters[i];
- parameters.push(param.symbol);
- if (param.type && param.type.kind === SyntaxKind.StringLiteral) {
+ let paramSymbol = param.symbol;
+ // Include parameter symbol instead of property symbol in the signature
+ if (paramSymbol && !!(paramSymbol.flags & SymbolFlags.Property) && !isBindingPattern(param.name)) {
+ const resolvedSymbol = resolveName(param, paramSymbol.name, SymbolFlags.Value, undefined, undefined);
+ paramSymbol = resolvedSymbol;
+ }
+ parameters.push(paramSymbol);
+ if (param.type && param.type.kind === SyntaxKind.StringLiteralType) {
hasStringLiterals = true;
}
@@ -3980,7 +4075,7 @@ namespace ts {
}
function getSignatureInstantiation(signature: Signature, typeArguments: Type[]): Signature {
- return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true);
+ return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true);
}
function getErasedSignature(signature: Signature): Signature {
@@ -3990,7 +4085,7 @@ namespace ts {
signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper);
}
else {
- signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true);
+ signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
}
}
return signature.erasedSignatureCache;
@@ -4506,8 +4601,7 @@ namespace ts {
return links.resolvedType;
}
- function getStringLiteralType(node: StringLiteral): StringLiteralType {
- const text = node.text;
+ function getStringLiteralTypeForText(text: string): StringLiteralType {
if (hasProperty(stringLiteralTypes, text)) {
return stringLiteralTypes[text];
}
@@ -4517,10 +4611,10 @@ namespace ts {
return type;
}
- function getTypeFromStringLiteral(node: StringLiteral): Type {
+ function getTypeFromStringLiteralTypeNode(node: StringLiteralTypeNode): Type {
const links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getStringLiteralType(node);
+ links.resolvedType = getStringLiteralTypeForText(node.text);
}
return links.resolvedType;
}
@@ -4560,10 +4654,10 @@ namespace ts {
return esSymbolType;
case SyntaxKind.VoidKeyword:
return voidType;
- case SyntaxKind.ThisKeyword:
+ case SyntaxKind.ThisType:
return getTypeFromThisTypeNode(node);
- case SyntaxKind.StringLiteral:
- return getTypeFromStringLiteral(node);
+ case SyntaxKind.StringLiteralType:
+ return getTypeFromStringLiteralTypeNode(node);
case SyntaxKind.TypeReference:
return getTypeFromTypeReference(node);
case SyntaxKind.TypePredicate:
@@ -5047,9 +5141,6 @@ namespace ts {
}
return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false);
}
- if (source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.TypeParameter) {
- return typeParameterIdenticalTo(source, target);
- }
if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union ||
source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) {
if (result = eachTypeRelatedToSomeType(source, target)) {
@@ -5106,7 +5197,7 @@ namespace ts {
let result = Ternary.True;
const sourceTypes = source.types;
for (const sourceType of sourceTypes) {
- const related = typeRelatedToSomeType(sourceType, target, false);
+ const related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
if (!related) {
return Ternary.False;
}
@@ -5180,17 +5271,6 @@ namespace ts {
return result;
}
- function typeParameterIdenticalTo(source: TypeParameter, target: TypeParameter): Ternary {
- // covers case when both type parameters does not have constraint (both equal to noConstraintType)
- if (source.constraint === target.constraint) {
- return Ternary.True;
- }
- if (source.constraint === noConstraintType || target.constraint === noConstraintType) {
- return Ternary.False;
- }
- return isIdenticalTo(source.constraint, target.constraint);
- }
-
// Determine if two object types are related by structure. First, check if the result is already available in the global cache.
// Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
// Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
@@ -5203,9 +5283,12 @@ namespace ts {
const id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id;
const related = relation[id];
if (related !== undefined) {
- // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate
- // errors, we can use the cached value. Otherwise, recompute the relation
- if (!elaborateErrors || (related === RelationComparisonResult.FailedAndReported)) {
+ if (elaborateErrors && related === RelationComparisonResult.Failed) {
+ // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported
+ // failure and continue computing the relation such that errors get reported.
+ relation[id] = RelationComparisonResult.FailedAndReported;
+ }
+ else {
return related === RelationComparisonResult.Succeeded ? Ternary.True : Ternary.False;
}
}
@@ -5413,20 +5496,26 @@ namespace ts {
outer: for (const t of targetSignatures) {
if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) {
- let localErrors = reportErrors;
- const checkedAbstractAssignability = false;
+ // Only elaborate errors from the first failure
+ let shouldElaborateErrors = reportErrors;
for (const s of sourceSignatures) {
if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) {
- const related = signatureRelatedTo(s, t, localErrors);
+ const related = signatureRelatedTo(s, t, shouldElaborateErrors);
if (related) {
result &= related;
errorInfo = saveErrorInfo;
continue outer;
}
- // Only report errors from the first failure
- localErrors = false;
+ shouldElaborateErrors = false;
}
}
+ // don't elaborate the primitive apparent types (like Number)
+ // because the actual primitives will have already been reported.
+ if (shouldElaborateErrors && !isPrimitiveApparentType(source)) {
+ reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1,
+ typeToString(source),
+ signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
+ }
return Ternary.False;
}
}
@@ -5504,7 +5593,7 @@ namespace ts {
const saveErrorInfo = errorInfo;
let related = isRelatedTo(s, t, reportErrors);
if (!related) {
- related = isRelatedTo(t, s, false);
+ related = isRelatedTo(t, s, /*reportErrors*/ false);
if (!related) {
if (reportErrors) {
reportError(Diagnostics.Types_of_parameters_0_and_1_are_incompatible,
@@ -5631,7 +5720,7 @@ namespace ts {
let related: Ternary;
if (sourceStringType && sourceNumberType) {
// If we know for sure we're testing both string and numeric index types then only report errors from the second one
- related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors);
+ related = isRelatedTo(sourceStringType, targetType, /*reportErrors*/ false) || isRelatedTo(sourceNumberType, targetType, reportErrors);
}
else {
related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors);
@@ -5736,26 +5825,19 @@ namespace ts {
if (!(isMatchingSignature(source, target, partialMatch))) {
return Ternary.False;
}
- let result = Ternary.True;
- if (source.typeParameters && target.typeParameters) {
- if (source.typeParameters.length !== target.typeParameters.length) {
- return Ternary.False;
- }
- for (let i = 0, len = source.typeParameters.length; i < len; ++i) {
- const related = compareTypes(source.typeParameters[i], target.typeParameters[i]);
- if (!related) {
- return Ternary.False;
- }
- result &= related;
- }
- }
- else if (source.typeParameters || target.typeParameters) {
+ // Check that the two signatures have the same number of type parameters. We might consider
+ // also checking that any type parameter constraints match, but that would require instantiating
+ // the constraints with a common set of type arguments to get relatable entities in places where
+ // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile,
+ // particularly as we're comparing erased versions of the signatures below.
+ if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) {
return Ternary.False;
}
// Spec 1.0 Section 3.8.3 & 3.8.4:
// M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N
source = getErasedSignature(source);
target = getErasedSignature(target);
+ let result = Ternary.True;
const targetLen = target.parameters.length;
for (let i = 0; i < targetLen; i++) {
const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]);
@@ -6061,6 +6143,17 @@ namespace ts {
}
function inferFromTypes(source: Type, target: Type) {
+ if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union ||
+ source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) {
+ // Source and target are both unions or both intersections. To improve the quality of
+ // inferences we first reduce the types by removing constituents that are identically
+ // matched by a constituent in the other type. For example, when inferring from
+ // 'string | string[]' to 'string | T', we reduce the types to 'string[]' and 'T'.
+ const reducedSource = reduceUnionOrIntersectionType(source, target);
+ const reducedTarget = reduceUnionOrIntersectionType(target, source);
+ source = reducedSource;
+ target = reducedTarget;
+ }
if (target.flags & TypeFlags.TypeParameter) {
// If target is a type parameter, make an inference, unless the source type contains
// the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
@@ -6071,7 +6164,6 @@ namespace ts {
if (source.flags & TypeFlags.ContainsAnyFunctionType) {
return;
}
-
const typeParameters = context.typeParameters;
for (let i = 0; i < typeParameters.length; i++) {
if (target === typeParameters[i]) {
@@ -6144,9 +6236,12 @@ namespace ts {
}
else {
source = getApparentType(source);
- if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) ||
- (target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) {
- // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members
+ if (source.flags & TypeFlags.ObjectType && (
+ target.flags & TypeFlags.Reference && (target).typeArguments ||
+ target.flags & TypeFlags.Tuple ||
+ target.flags & TypeFlags.Anonymous && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) {
+ // If source is an object type, and target is a type reference with type arguments, a tuple type,
+ // the type of a method, or a type literal, infer from members
if (isInProcess(source, target)) {
return;
}
@@ -6219,6 +6314,41 @@ namespace ts {
}
}
+ function typeIdenticalToSomeType(source: Type, target: UnionOrIntersectionType): boolean {
+ for (const t of target.types) {
+ if (isTypeIdenticalTo(source, t)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return the reduced form of the source type. This type is computed by by removing all source
+ * constituents that have an identical match in the target type.
+ */
+ function reduceUnionOrIntersectionType(source: UnionOrIntersectionType, target: UnionOrIntersectionType) {
+ let sourceTypes = source.types;
+ let sourceIndex = 0;
+ let modified = false;
+ while (sourceIndex < sourceTypes.length) {
+ if (typeIdenticalToSomeType(sourceTypes[sourceIndex], target)) {
+ if (!modified) {
+ sourceTypes = sourceTypes.slice(0);
+ modified = true;
+ }
+ sourceTypes.splice(sourceIndex, 1);
+ }
+ else {
+ sourceIndex++;
+ }
+ }
+ if (modified) {
+ return source.flags & TypeFlags.Union ? getUnionType(sourceTypes, /*noSubtypeReduction*/ true) : getIntersectionType(sourceTypes);
+ }
+ return source;
+ }
+
function getInferenceCandidates(context: InferenceContext, index: number): Type[] {
const inferences = context.inferences[index];
return inferences.primary || inferences.secondary || emptyArray;
@@ -6402,6 +6532,8 @@ namespace ts {
// Only narrow when symbol is variable of type any or an object, union, or type parameter type
if (node && symbol.flags & SymbolFlags.Variable) {
if (isTypeAny(type) || type.flags & (TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) {
+ const declaration = getDeclarationOfKind(symbol, SyntaxKind.VariableDeclaration);
+ const top = declaration && getDeclarationContainer(declaration);
const originalType = type;
const nodeStack: {node: Node, child: Node}[] = [];
loop: while (node.parent) {
@@ -6415,15 +6547,12 @@ namespace ts {
break;
case SyntaxKind.SourceFile:
case SyntaxKind.ModuleDeclaration:
- case SyntaxKind.FunctionDeclaration:
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.MethodSignature:
- case SyntaxKind.GetAccessor:
- case SyntaxKind.SetAccessor:
- case SyntaxKind.Constructor:
- // Stop at the first containing function or module declaration
+ // Stop at the first containing file or module declaration
break loop;
}
+ if (node === top) {
+ break;
+ }
}
let nodes: {node: Node, child: Node};
@@ -6486,6 +6615,10 @@ namespace ts {
assumeTrue = !assumeTrue;
}
const typeInfo = primitiveTypeInfo[right.text];
+ // Don't narrow `undefined`
+ if (typeInfo && typeInfo.type === undefinedType) {
+ return type;
+ }
// If the type to be narrowed is any and we're checking a primitive with assumeTrue=true, return the primitive
if (!!(type.flags & TypeFlags.Any) && typeInfo && assumeTrue) {
return typeInfo.type;
@@ -7793,12 +7926,11 @@ namespace ts {
return type;
}
- /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present.
- function getJsxIntrinsicElementsType() {
- if (!jsxIntrinsicElementsType) {
- jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType;
+ function getJsxType(name: string) {
+ if (jsxTypes[name] === undefined) {
+ return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType;
}
- return jsxIntrinsicElementsType;
+ return jsxTypes[name];
}
/// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if
@@ -7821,7 +7953,7 @@ namespace ts {
return links.resolvedSymbol;
function lookupIntrinsicTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol {
- const intrinsicElementsType = getJsxIntrinsicElementsType();
+ const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
if (intrinsicElementsType !== unknownType) {
// Property case
const intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text);
@@ -7853,7 +7985,7 @@ namespace ts {
// Look up the value in the current scope
if (valueSymbol && valueSymbol !== unknownSymbol) {
- links.jsxFlags |= JsxFlags.ClassElement;
+ links.jsxFlags |= JsxFlags.ValueElement;
if (valueSymbol.flags & SymbolFlags.Alias) {
markAliasSymbolAsReferenced(valueSymbol);
}
@@ -7882,7 +8014,7 @@ namespace ts {
function getJsxElementInstanceType(node: JsxOpeningLikeElement) {
// There is no such thing as an instance type for a non-class element. This
// line shouldn't be hit.
- Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement), "Should not call getJsxElementInstanceType on non-class Element");
+ Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ValueElement), "Should not call getJsxElementInstanceType on non-class Element");
const classSymbol = getJsxElementTagSymbol(node);
if (classSymbol === unknownSymbol) {
@@ -7909,15 +8041,7 @@ namespace ts {
}
}
- const returnType = getUnionType(signatures.map(getReturnTypeOfSignature));
-
- // Issue an error if this return type isn't assignable to JSX.ElementClass
- const elemClassType = getJsxGlobalElementClassType();
- if (elemClassType) {
- checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
- }
-
- return returnType;
+ return getUnionType(signatures.map(getReturnTypeOfSignature));
}
/// e.g. "props" for React.d.ts,
@@ -7966,9 +8090,31 @@ namespace ts {
if (!links.resolvedJsxType) {
const sym = getJsxElementTagSymbol(node);
- if (links.jsxFlags & JsxFlags.ClassElement) {
+ if (links.jsxFlags & JsxFlags.ValueElement) {
+ // Get the element instance type (the result of newing or invoking this tag)
const elemInstanceType = getJsxElementInstanceType(node);
+ // Is this is a stateless function component? See if its single signature is
+ // assignable to the JSX Element Type
+ const callSignature = getSingleCallSignature(getTypeOfSymbol(sym));
+ const callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
+ let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
+ if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType) && (paramType.flags & TypeFlags.ObjectType)) {
+ // Intersect in JSX.IntrinsicAttributes if it exists
+ const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ if (intrinsicAttributes !== unknownType) {
+ paramType = intersectTypes(intrinsicAttributes, paramType);
+ }
+ return paramType;
+ }
+
+ // Issue an error if this return type isn't assignable to JSX.ElementClass
+ const elemClassType = getJsxGlobalElementClassType();
+ if (elemClassType) {
+ checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
+ }
+
+
if (isTypeAny(elemInstanceType)) {
return links.resolvedJsxType = elemInstanceType;
}
@@ -7990,14 +8136,36 @@ namespace ts {
return links.resolvedJsxType = emptyObjectType;
}
else if (isTypeAny(attributesType) || (attributesType === unknownType)) {
+ // Props is of type 'any' or unknown
return links.resolvedJsxType = attributesType;
}
else if (!(attributesType.flags & TypeFlags.ObjectType)) {
+ // Props is not an object type
error(node.tagName, Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType));
return links.resolvedJsxType = anyType;
}
else {
- return links.resolvedJsxType = attributesType;
+ // Normal case -- add in IntrinsicClassElements and IntrinsicElements
+ let apparentAttributesType = attributesType;
+ const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
+ if (intrinsicClassAttribs !== unknownType) {
+ const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
+ if (typeParams) {
+ if (typeParams.length === 1) {
+ apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType);
+ }
+ }
+ else {
+ apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs);
+ }
+ }
+
+ const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ if (intrinsicAttribs !== unknownType) {
+ apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
+ }
+
+ return links.resolvedJsxType = apparentAttributesType;
}
}
}
@@ -8036,7 +8204,7 @@ namespace ts {
/// Returns all the properties of the Jsx.IntrinsicElements interface
function getJsxIntrinsicTagNames(): Symbol[] {
- const intrinsics = getJsxIntrinsicElementsType();
+ const intrinsics = getJsxType(JsxNames.IntrinsicElements);
return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray;
}
@@ -8719,7 +8887,7 @@ namespace ts {
// for the argument. In that case, we should check the argument.
if (argType === undefined) {
argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors
- ? getStringLiteralType(arg)
+ ? getStringLiteralTypeForText((arg).text)
: checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
}
@@ -8914,7 +9082,7 @@ namespace ts {
case SyntaxKind.Identifier:
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
- return getStringLiteralType(element.name);
+ return getStringLiteralTypeForText((element.name).text);
case SyntaxKind.ComputedPropertyName:
const nameType = checkComputedPropertyName(element.name);
@@ -9783,35 +9951,52 @@ namespace ts {
return aggregatedTypes;
}
- // TypeScript Specification 1.0 (6.3) - July 2014
- // 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.
+ /*
+ *TypeScript Specification 1.0 (6.3) - July 2014
+ * 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.
+ * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
+ */
function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration, returnType: Type): void {
if (!produceDiagnostics) {
return;
}
- // Functions that return 'void' or 'any' don't need any return expressions.
+ // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
if (returnType === voidType || isTypeAny(returnType)) {
return;
}
// If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
- // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw
+ // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
if (nodeIsMissing(func.body) || func.body.kind !== SyntaxKind.Block || !(func.flags & NodeFlags.HasImplicitReturn)) {
return;
}
- if (func.flags & NodeFlags.HasExplicitReturn) {
- if (compilerOptions.noImplicitReturns) {
- error(func.type, Diagnostics.Not_all_code_paths_return_a_value);
- }
- }
- else {
- // This function does not conform to the specification.
+ const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn;
+
+ if (returnType && !hasExplicitReturn) {
+ // minimal check: function has syntactic return type annotation and no explicit return statements in the body
+ // this function does not conform to the specification.
+ // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
error(func.type, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
}
+ else if (compilerOptions.noImplicitReturns) {
+ if (!returnType) {
+ // If return type annotation is omitted check if function has any explicit return statements.
+ // If it does not have any - its inferred return type is void - don't do any checks.
+ // Otherwise get inferred return type from function body and report error only if it is not void / anytype
+ const inferredReturnType = hasExplicitReturn
+ ? getReturnTypeOfSignature(getSignatureFromDeclaration(func))
+ : voidType;
+
+ if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) {
+ return;
+ }
+ }
+ error(func.type || func, Diagnostics.Not_all_code_paths_return_a_value);
+ }
}
function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | MethodDeclaration, contextualMapper?: TypeMapper): Type {
@@ -9876,7 +10061,7 @@ namespace ts {
return type;
}
- function checkFunctionExpressionOrObjectLiteralMethodBody(node: FunctionExpression | MethodDeclaration) {
+ function checkFunctionExpressionOrObjectLiteralMethodBody(node: ArrowFunction | FunctionExpression | MethodDeclaration) {
Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
const isAsync = isAsyncFunctionLike(node);
@@ -9884,14 +10069,10 @@ namespace ts {
emitAwaiter = true;
}
- const returnType = node.type && getTypeFromTypeNode(node.type);
- let promisedType: Type;
- if (returnType && isAsync) {
- promisedType = checkAsyncFunctionReturnType(node);
- }
-
- if (returnType && !node.asteriskToken) {
- checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType);
+ const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type));
+ if (!node.asteriskToken) {
+ // return is not necessary in the body of generators
+ checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
if (node.body) {
@@ -9914,13 +10095,13 @@ namespace ts {
// check assignability of the awaited type of the expression body against the promised type of
// its return type annotation.
const exprType = checkExpression(node.body);
- if (returnType) {
+ if (returnOrPromisedType) {
if (isAsync) {
const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member);
- checkTypeAssignableTo(awaitedType, promisedType, node.body);
+ checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
else {
- checkTypeAssignableTo(exprType, returnType, node.body);
+ checkTypeAssignableTo(exprType, returnOrPromisedType, node.body);
}
}
@@ -10180,7 +10361,7 @@ namespace ts {
checkDestructuringAssignment(p, type);
}
else {
- // non-shorthand property assignments should always have initializers
+ // non-shorthand property assignments should always have initializers
checkDestructuringAssignment((p).initializer, type);
}
}
@@ -10536,7 +10717,7 @@ namespace ts {
function checkStringLiteralExpression(node: StringLiteral): Type {
const contextualType = getContextualType(node);
if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
- return getStringLiteralType(node);
+ return getStringLiteralTypeForText(node.text);
}
return stringType;
@@ -11006,6 +11187,7 @@ namespace ts {
const symbol = getSymbolOfNode(node);
const firstDeclaration = getDeclarationOfKind(symbol, node.kind);
+
// Only type check the symbol once
if (node === firstDeclaration) {
checkFunctionOrConstructorSymbol(symbol);
@@ -11358,16 +11540,24 @@ namespace ts {
seen = c === node;
}
});
- if (subsequentNode) {
+ // We may be here because of some extra junk between overloads that could not be parsed into a valid node.
+ // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
+ if (subsequentNode && subsequentNode.pos === node.end) {
if (subsequentNode.kind === node.kind) {
const errorNode: Node = (subsequentNode).name || subsequentNode;
// TODO(jfreeman): These are methods, so handle computed name case
if (node.name && (subsequentNode).name && (node.name).text === ((subsequentNode).name).text) {
- // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members
- Debug.assert(node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature);
- Debug.assert((node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static));
- const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static;
- error(errorNode, diagnostic);
+ const reportError =
+ (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) &&
+ (node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static);
+ // we can get here in two cases
+ // 1. mixed static and instance class members
+ // 2. something with the same name was defined before the set of overloads that prevents them from merging
+ // here we'll report error only for the first case since for second we should already report error in binder
+ if (reportError) {
+ const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static;
+ error(errorNode, diagnostic);
+ }
return;
}
else if (nodeIsPresent((subsequentNode).body)) {
@@ -11825,6 +12015,9 @@ namespace ts {
return unknownType;
}
+ // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced.
+ checkReturnTypeAnnotationAsExpression(node);
+
// Validate the promise constructor type.
const promiseConstructorType = getTypeOfSymbol(promiseConstructor);
if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) {
@@ -11833,11 +12026,11 @@ namespace ts {
// Verify there is no local declaration that could collide with the promise constructor.
const promiseName = getEntityNameFromTypeNode(node.type);
- const root = getFirstIdentifier(promiseName);
- const rootSymbol = getSymbol(node.locals, root.text, SymbolFlags.Value);
+ const promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName);
+ const rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, SymbolFlags.Value);
if (rootSymbol) {
error(rootSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions,
- root.text,
+ promiseNameOrNamespaceRoot.text,
getFullyQualifiedName(promiseConstructor));
return unknownType;
}
@@ -11921,24 +12114,12 @@ namespace ts {
* Checks the type annotation of an accessor declaration or property declaration as
* an expression if it is a type reference to a type with a value declaration.
*/
- function checkTypeAnnotationAsExpression(node: AccessorDeclaration | PropertyDeclaration | ParameterDeclaration | MethodDeclaration) {
- switch (node.kind) {
- case SyntaxKind.PropertyDeclaration:
- checkTypeNodeAsExpression((node).type);
- break;
- case SyntaxKind.Parameter:
- checkTypeNodeAsExpression((node).type);
- break;
- case SyntaxKind.MethodDeclaration:
- checkTypeNodeAsExpression((node).type);
- break;
- case SyntaxKind.GetAccessor:
- checkTypeNodeAsExpression((node).type);
- break;
- case SyntaxKind.SetAccessor:
- checkTypeNodeAsExpression(getSetAccessorTypeAnnotationNode(node));
- break;
- }
+ function checkTypeAnnotationAsExpression(node: VariableLikeDeclaration) {
+ checkTypeNodeAsExpression((node).type);
+ }
+
+ function checkReturnTypeAnnotationAsExpression(node: FunctionLikeDeclaration) {
+ checkTypeNodeAsExpression(node.type);
}
/** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */
@@ -11976,11 +12157,12 @@ namespace ts {
break;
case SyntaxKind.MethodDeclaration:
- checkParameterTypeAnnotationsAsExpressions(node);
- // fall-through
-
- case SyntaxKind.SetAccessor:
case SyntaxKind.GetAccessor:
+ case SyntaxKind.SetAccessor:
+ checkParameterTypeAnnotationsAsExpressions(node);
+ checkReturnTypeAnnotationAsExpression(node);
+ break;
+
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.Parameter:
checkTypeAnnotationAsExpression(node);
@@ -12030,7 +12212,14 @@ namespace ts {
const symbol = getSymbolOfNode(node);
const localSymbol = node.localSymbol || symbol;
- const firstDeclaration = getDeclarationOfKind(localSymbol, node.kind);
+ // Since the javascript won't do semantic analysis like typescript,
+ // if the javascript file comes before the typescript file and both contain same name functions,
+ // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
+ const firstDeclaration = forEach(localSymbol.declarations,
+ // Get first non javascript function declaration
+ declaration => declaration.kind === node.kind && !isSourceFileJavaScript(getSourceFile(declaration)) ?
+ declaration : undefined);
+
// Only type check the symbol once
if (node === firstDeclaration) {
checkFunctionOrConstructorSymbol(localSymbol);
@@ -12046,14 +12235,9 @@ namespace ts {
}
checkSourceElement(node.body);
- if (node.type && !isAccessor(node.kind) && !node.asteriskToken) {
- const returnType = getTypeFromTypeNode(node.type);
- let promisedType: Type;
- if (isAsync) {
- promisedType = checkAsyncFunctionReturnType(node);
- }
-
- checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType);
+ if (!isAccessor(node.kind) && !node.asteriskToken) {
+ const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type));
+ checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
if (produceDiagnostics && !node.type) {
@@ -12902,13 +13086,13 @@ namespace ts {
// In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression.
const caseType = checkExpression(caseClause.expression);
- // Permit 'number[] | "foo"' to be asserted to 'string'.
- if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, TypeFlags.StringLike)) {
- return;
- }
+ const expressionTypeIsAssignableToCaseType =
+ // Permit 'number[] | "foo"' to be asserted to 'string'.
+ (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, TypeFlags.StringLike)) ||
+ isTypeAssignableTo(expressionType, caseType);
- if (!isTypeAssignableTo(expressionType, caseType)) {
- // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails
+ if (!expressionTypeIsAssignableToCaseType) {
+ // 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined);
}
}
@@ -14006,8 +14190,29 @@ namespace ts {
const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
}
+ // Checks for export * conflicts
+ const exports = getExportsOfModule(moduleSymbol);
+ for (const id in exports) {
+ if (id === "__export") {
+ continue;
+ }
+ const { declarations, flags } = exports[id];
+ // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. (TS Exceptions: namespaces, function overloads, enums, and interfaces)
+ if (!(flags & (SymbolFlags.Namespace | SymbolFlags.Interface | SymbolFlags.Enum)) && declarations.length > 1) {
+ const exportedDeclarations: Declaration[] = filter(declarations, isNotOverload);
+ if (exportedDeclarations.length > 1) {
+ for (const declaration of exportedDeclarations) {
+ diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, id));
+ }
+ }
+ }
+ }
links.exportsChecked = true;
}
+
+ function isNotOverload(declaration: Declaration): boolean {
+ return declaration.kind !== SyntaxKind.FunctionDeclaration || !!(declaration as FunctionDeclaration).body;
+ }
}
function checkTypePredicate(node: TypePredicateNode) {
@@ -14279,6 +14484,7 @@ namespace ts {
emitExtends = false;
emitDecorate = false;
emitParam = false;
+ emitAwaiter = false;
potentialThisCollisions.length = 0;
forEach(node.statements, checkSourceElement);
@@ -14648,6 +14854,9 @@ namespace ts {
const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node);
return type.symbol;
+ case SyntaxKind.ThisType:
+ return getTypeFromTypeNode(node).symbol;
+
case SyntaxKind.ConstructorKeyword:
// constructor keyword for an overload, should take us to the definition if it exist
const constructorDeclaration = node.parent;
@@ -15837,13 +16046,27 @@ namespace ts {
if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
const variableList = forInOrOfStatement.initializer;
if (!checkGrammarVariableDeclarationList(variableList)) {
- if (variableList.declarations.length > 1) {
+ const declarations = variableList.declarations;
+
+ // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
+ // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
+ // For example:
+ // var let = 10;
+ // for (let of [1,2,3]) {} // this is invalid ES6 syntax
+ // for (let in [1,2,3]) {} // this is invalid ES6 syntax
+ // We will then want to skip on grammar checking on variableList declaration
+ if (!declarations.length) {
+ return false;
+ }
+
+ if (declarations.length > 1) {
const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement
? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
: Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
}
- const firstDeclaration = variableList.declarations[0];
+ const firstDeclaration = declarations[0];
+
if (firstDeclaration.initializer) {
const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement
? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
@@ -16042,7 +16265,7 @@ namespace ts {
}
}
- const checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node));
+ const checkLetConstNames = (isLet(node) || isConst(node));
// 1. LexicalDeclaration : LetOrConst BindingList ;
// It is a Syntax Error if the BoundNames of BindingList contains "let".
@@ -16056,7 +16279,7 @@ namespace ts {
function checkGrammarNameInLetOrConstDeclarations(name: Identifier | BindingPattern): boolean {
if (name.kind === SyntaxKind.Identifier) {
- if ((name).text === "let") {
+ if ((name).originalKeywordKind === SyntaxKind.LetKeyword) {
return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
}
}
@@ -16184,11 +16407,17 @@ namespace ts {
if (checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) {
return true;
}
+ if (node.initializer) {
+ return grammarErrorOnNode(node.initializer, Diagnostics.An_interface_property_cannot_have_an_initializer);
+ }
}
else if (node.parent.kind === SyntaxKind.TypeLiteral) {
if (checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) {
return true;
}
+ if (node.initializer) {
+ return grammarErrorOnNode(node.initializer, Diagnostics.A_type_literal_property_cannot_have_an_initializer);
+ }
}
if (isInAmbientContext(node) && node.initializer) {
diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts
index 3fca97c0450..034b7022e82 100644
--- a/src/compiler/commandLineParser.ts
+++ b/src/compiler/commandLineParser.ts
@@ -279,6 +279,16 @@ namespace ts {
name: "forceConsistentCasingInFileNames",
type: "boolean",
description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
+ },
+ {
+ name: "allowSyntheticDefaultImports",
+ type: "boolean",
+ description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
+ },
+ {
+ name: "allowJs",
+ type: "boolean",
+ description: Diagnostics.Allow_javascript_files_to_be_compiled
}
];
@@ -474,9 +484,10 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine {
- const { options, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath);
+ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}): ParsedCommandLine {
+ const { options: optionsFromJsonConfigFile, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath);
+ const options = extend(existingOptions, optionsFromJsonConfigFile);
return {
options,
fileNames: getFileNames(),
@@ -494,23 +505,32 @@ namespace ts {
}
}
else {
+ const filesSeen: Map = {};
const exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined;
- const sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
- for (let i = 0; i < sysFiles.length; i++) {
- const name = sysFiles[i];
- if (fileExtensionIs(name, ".d.ts")) {
- const baseName = name.substr(0, name.length - ".d.ts".length);
- if (!contains(sysFiles, baseName + ".tsx") && !contains(sysFiles, baseName + ".ts")) {
- fileNames.push(name);
+ const supportedExtensions = getSupportedExtensions(options);
+ Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick");
+
+ // Get files of supported extensions in their order of resolution
+ for (const extension of supportedExtensions) {
+ const filesInDirWithExtension = host.readDirectory(basePath, extension, exclude);
+ for (const fileName of filesInDirWithExtension) {
+ // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension,
+ // lets pick them when its turn comes up
+ if (extension === ".ts" && fileExtensionIs(fileName, ".d.ts")) {
+ continue;
}
- }
- else if (fileExtensionIs(name, ".ts")) {
- if (!contains(sysFiles, name + "x")) {
- fileNames.push(name);
+
+ // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files)
+ // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation
+ if (extension === ".d.ts" || (options.allowJs && contains(supportedJavascriptExtensions, extension))) {
+ const baseName = fileName.substr(0, fileName.length - extension.length);
+ if (hasProperty(filesSeen, baseName + ".ts") || hasProperty(filesSeen, baseName + ".tsx")) {
+ continue;
+ }
}
- }
- else {
- fileNames.push(name);
+
+ filesSeen[fileName] = true;
+ fileNames.push(fileName);
}
}
}
diff --git a/src/compiler/core.ts b/src/compiler/core.ts
index c866cf41a92..cae7bd82103 100644
--- a/src/compiler/core.ts
+++ b/src/compiler/core.ts
@@ -297,8 +297,8 @@ namespace ts {
return result;
}
- export function extend(first: Map, second: Map): Map {
- const result: Map = {};
+ export function extend, T2 extends Map<{}>>(first: T1 , second: T2): T1 & T2 {
+ const result: T1 & T2 = {};
for (const id in first) {
(result as any)[id] = first[id];
}
@@ -356,6 +356,33 @@ namespace ts {
return result;
}
+ /**
+ * Reduce the properties of a map.
+ *
+ * @param map The map to reduce
+ * @param callback An aggregation function that is called for each entry in the map
+ * @param initial The initial value for the reduction.
+ */
+ export function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
+ let result = initial;
+ if (map) {
+ for (const key in map) {
+ if (hasProperty(map, key)) {
+ result = callback(result, map[key], String(key));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Tests whether a value is an array.
+ */
+ export function isArray(value: any): value is any[] {
+ return Array.isArray ? Array.isArray(value) : value instanceof Array;
+ }
+
export function memoize(callback: () => T): () => T {
let value: T;
return () => {
@@ -714,7 +741,7 @@ namespace ts {
}
export function getBaseFileName(path: string) {
- if (!path) {
+ if (path === undefined) {
return undefined;
}
const i = path.lastIndexOf(directorySeparator);
@@ -738,13 +765,18 @@ namespace ts {
/**
* List of supported extensions in order of file resolution precedence.
*/
- export const supportedExtensions = [".ts", ".tsx", ".d.ts"];
- export const supportedJsExtensions = supportedExtensions.concat(".js", ".jsx");
+ export const supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"];
+ export const supportedJavascriptExtensions = [".js", ".jsx"];
+ const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
- export function isSupportedSourceFileName(fileName: string) {
+ export function getSupportedExtensions(options?: CompilerOptions): string[] {
+ return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
+ }
+
+ export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
if (!fileName) { return false; }
- for (const extension of supportedExtensions) {
+ for (const extension of getSupportedExtensions(compilerOptions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
@@ -842,7 +874,7 @@ namespace ts {
}
export function fail(message?: string): void {
- Debug.assert(false, message);
+ Debug.assert(/*expression*/ false, message);
}
}
diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts
index 669cbcbcf0c..6e09a398ea6 100644
--- a/src/compiler/declarationEmitter.ts
+++ b/src/compiler/declarationEmitter.ts
@@ -31,13 +31,17 @@ namespace ts {
}
export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {
- const diagnostics: Diagnostic[] = [];
- const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js");
- emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile);
- return diagnostics;
+ const declarationDiagnostics = createDiagnosticCollection();
+ forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
+ return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName);
+
+ function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
+ }
}
- function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit {
+ function emitDeclarations(host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, declarationFilePath: string,
+ sourceFiles: SourceFile[], isBundledEmit: boolean): DeclarationEmit {
const newLine = host.getNewLine();
const compilerOptions = host.getCompilerOptions();
@@ -58,7 +62,7 @@ namespace ts {
let errorNameNode: DeclarationName;
const emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments;
const emit = compilerOptions.stripInternal ? stripInternal : emitNode;
- let noDeclare = !root;
+ let noDeclare: boolean;
let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = [];
let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[];
@@ -68,105 +72,78 @@ namespace ts {
// and we could be collecting these paths from multiple files into single one with --out option
let referencePathsOutput = "";
- if (root) {
- // Emitting just a single file, so emit references in this file only
+ // Emit references corresponding to each file
+ const emittedReferencedFiles: SourceFile[] = [];
+ let addedGlobalFileReference = false;
+ let allSourcesModuleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = [];
+ forEach(sourceFiles, sourceFile => {
+ // Dont emit for javascript file
+ if (isSourceFileJavaScript(sourceFile)) {
+ return;
+ }
+
+ // Check what references need to be added
if (!compilerOptions.noResolve) {
- let addedGlobalFileReference = false;
- forEach(root.referencedFiles, fileReference => {
- const referencedFile = tryResolveScriptReference(host, root, fileReference);
+ forEach(sourceFile.referencedFiles, fileReference => {
+ const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference);
- // All the references that are not going to be part of same file
- if (referencedFile && ((referencedFile.flags & NodeFlags.DeclarationFile) || // This is a declare file reference
- shouldEmitToOwnFile(referencedFile, compilerOptions) || // This is referenced file is emitting its own js file
- !addedGlobalFileReference)) { // Or the global out file corresponding to this reference was not added
-
- writeReferencePath(referencedFile);
- if (!isExternalModuleOrDeclarationFile(referencedFile)) {
+ // Emit reference in dts, if the file reference was not already emitted
+ if (referencedFile && !contains(emittedReferencedFiles, referencedFile)) {
+ // Add a reference to generated dts file,
+ // global file reference is added only
+ // - if it is not bundled emit (because otherwise it would be self reference)
+ // - and it is not already added
+ if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) {
addedGlobalFileReference = true;
}
+ emittedReferencedFiles.push(referencedFile);
}
});
}
- emitSourceFile(root);
+ if (!isBundledEmit || !isExternalModule(sourceFile)) {
+ noDeclare = false;
+ emitSourceFile(sourceFile);
+ }
+ else if (isExternalModule(sourceFile)) {
+ noDeclare = true;
+ write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`);
+ writeLine();
+ increaseIndent();
+ emitSourceFile(sourceFile);
+ decreaseIndent();
+ write("}");
+ writeLine();
+ }
// create asynchronous output for the importDeclarations
if (moduleElementDeclarationEmitInfo.length) {
const oldWriter = writer;
forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => {
- if (aliasEmitInfo.isVisible) {
+ if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
Debug.assert(aliasEmitInfo.node.kind === SyntaxKind.ImportDeclaration);
createAndSetNewTextWriterWithSymbolWriter();
- Debug.assert(aliasEmitInfo.indent === 0);
+ Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit));
+ for (let i = 0; i < aliasEmitInfo.indent; i++) {
+ increaseIndent();
+ }
writeImportDeclaration(aliasEmitInfo.node);
aliasEmitInfo.asynchronousOutput = writer.getText();
+ for (let i = 0; i < aliasEmitInfo.indent; i++) {
+ decreaseIndent();
+ }
}
});
setWriter(oldWriter);
+
+ allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
+ moduleElementDeclarationEmitInfo = [];
}
- }
- else {
- // Emit references corresponding to this file
- const emittedReferencedFiles: SourceFile[] = [];
- let prevModuleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = [];
- forEach(host.getSourceFiles(), sourceFile => {
- if (!isDeclarationFile(sourceFile)) {
- // Check what references need to be added
- if (!compilerOptions.noResolve) {
- forEach(sourceFile.referencedFiles, fileReference => {
- const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference);
-
- // If the reference file is a declaration file, emit that reference
- if (referencedFile && (isDeclarationFile(referencedFile) &&
- !contains(emittedReferencedFiles, referencedFile))) { // If the file reference was not already emitted
-
- writeReferencePath(referencedFile);
- emittedReferencedFiles.push(referencedFile);
- }
- });
- }
- }
-
- if (!isExternalModuleOrDeclarationFile(sourceFile)) {
- noDeclare = false;
- emitSourceFile(sourceFile);
- }
- else if (isExternalModule(sourceFile)) {
- noDeclare = true;
- write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`);
- writeLine();
- increaseIndent();
- emitSourceFile(sourceFile);
- decreaseIndent();
- write("}");
- writeLine();
-
- // create asynchronous output for the importDeclarations
- if (moduleElementDeclarationEmitInfo.length) {
- const oldWriter = writer;
- forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => {
- if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
- Debug.assert(aliasEmitInfo.node.kind === SyntaxKind.ImportDeclaration);
- createAndSetNewTextWriterWithSymbolWriter();
- Debug.assert(aliasEmitInfo.indent === 1);
- increaseIndent();
- writeImportDeclaration(aliasEmitInfo.node);
- aliasEmitInfo.asynchronousOutput = writer.getText();
- decreaseIndent();
- }
- });
- setWriter(oldWriter);
- }
- prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
- moduleElementDeclarationEmitInfo = [];
- }
- });
- moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo);
- }
+ });
return {
reportedDeclarationError,
- moduleElementDeclarationEmitInfo,
+ moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo,
synchronousDeclarationOutput: writer.getText(),
referencePathsOutput,
};
@@ -278,14 +255,14 @@ namespace ts {
const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
- diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
+ emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
getTextOfNodeFromSourceText(currentText, errorInfo.typeName),
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
}
else {
- diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
+ emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
@@ -300,7 +277,8 @@ namespace ts {
function reportInaccessibleThisError() {
if (errorNameNode) {
- diagnostics.push(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary,
+ reportedDeclarationError = true;
+ emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary,
declarationNameToString(errorNameNode)));
}
}
@@ -378,8 +356,8 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
- case SyntaxKind.ThisKeyword:
- case SyntaxKind.StringLiteral:
+ case SyntaxKind.ThisType:
+ case SyntaxKind.StringLiteralType:
return writeTextOfNode(currentText, type);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(type);
@@ -680,7 +658,7 @@ namespace ts {
}
else {
write("require(");
- writeTextOfNode(currentText, getExternalModuleImportEqualsDeclarationExpression(node));
+ emitExternalModuleSpecifier(node);
write(");");
}
writer.writeLine();
@@ -737,14 +715,23 @@ namespace ts {
}
write(" from ");
}
- emitExternalModuleSpecifier(node.moduleSpecifier);
+ emitExternalModuleSpecifier(node);
write(";");
writer.writeLine();
}
- function emitExternalModuleSpecifier(moduleSpecifier: Expression) {
- if (moduleSpecifier.kind === SyntaxKind.StringLiteral && (!root) && (compilerOptions.out || compilerOptions.outFile)) {
- const moduleName = getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent as (ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration));
+ function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration) {
+ let moduleSpecifier: Node;
+ if (parent.kind === SyntaxKind.ImportEqualsDeclaration) {
+ const node = parent as ImportEqualsDeclaration;
+ moduleSpecifier = getExternalModuleImportEqualsDeclarationExpression(node);
+ }
+ else {
+ const node = parent as (ImportDeclaration | ExportDeclaration);
+ moduleSpecifier = node.moduleSpecifier;
+ }
+ if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) {
+ const moduleName = getExternalModuleNameFromDeclaration(host, resolver, parent);
if (moduleName) {
write("\"");
write(moduleName);
@@ -787,7 +774,7 @@ namespace ts {
}
if (node.moduleSpecifier) {
write(" from ");
- emitExternalModuleSpecifier(node.moduleSpecifier);
+ emitExternalModuleSpecifier(node);
}
write(";");
writer.writeLine();
@@ -1643,34 +1630,58 @@ namespace ts {
}
}
- function writeReferencePath(referencedFile: SourceFile) {
- let declFileName = referencedFile.flags & NodeFlags.DeclarationFile
- ? referencedFile.fileName // Declaration file, use declaration file name
- : shouldEmitToOwnFile(referencedFile, compilerOptions)
- ? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file
- : removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file
+ /**
+ * Adds the reference to referenced file, returns true if global file reference was emitted
+ * @param referencedFile
+ * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not
+ */
+ function writeReferencePath(referencedFile: SourceFile, addBundledFileReference: boolean): boolean {
+ let declFileName: string;
+ let addedBundledEmitReference = false;
+ if (isDeclarationFile(referencedFile)) {
+ // Declaration file, use declaration file name
+ declFileName = referencedFile.fileName;
+ }
+ else {
+ // Get the declaration file path
+ forEachExpectedEmitFile(host, getDeclFileName, referencedFile);
+ }
- declFileName = getRelativePathToDirectoryOrUrl(
- getDirectoryPath(normalizeSlashes(jsFilePath)),
- declFileName,
- host.getCurrentDirectory(),
- host.getCanonicalFileName,
- /*isAbsolutePathAnUrl*/ false);
+ if (declFileName) {
+ declFileName = getRelativePathToDirectoryOrUrl(
+ getDirectoryPath(normalizeSlashes(declarationFilePath)),
+ declFileName,
+ host.getCurrentDirectory(),
+ host.getCanonicalFileName,
+ /*isAbsolutePathAnUrl*/ false);
- referencePathsOutput += "/// " + newLine;
+ referencePathsOutput += "/// " + newLine;
+ }
+ return addedBundledEmitReference;
+
+ function getDeclFileName(emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) {
+ // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path
+ if (isBundledEmit && !addBundledFileReference) {
+ return;
+ }
+
+ Debug.assert(!!emitFileNames.declarationFilePath || isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files");
+ declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath;
+ addedBundledEmitReference = isBundledEmit;
+ }
}
}
/* @internal */
- export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) {
- const emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile);
- // TODO(shkamat): Should we not write any declaration file if any of them can produce error,
- // or should we just not write this file like we are doing now
- if (!emitDeclarationResult.reportedDeclarationError) {
+ export function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection) {
+ const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
+ const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
+ if (!emitSkipped) {
const declarationOutput = emitDeclarationResult.referencePathsOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
- writeFile(host, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM);
+ writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM);
}
+ return emitSkipped;
function getDeclarationOutput(synchronousDeclarationOutput: string, moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]) {
let appliedSyncOutputPos = 0;
diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json
index 6dcb65d55c4..86f0767c961 100644
--- a/src/compiler/diagnosticMessages.json
+++ b/src/compiler/diagnosticMessages.json
@@ -783,6 +783,14 @@
"category": "Error",
"code": 1245
},
+ "An interface property cannot have an initializer.": {
+ "category": "Error",
+ "code": 1246
+ },
+ "A type literal property cannot have an initializer.": {
+ "category": "Error",
+ "code": 1247
+ },
"'with' statements are not allowed in an async function block.": {
"category": "Error",
@@ -836,6 +844,10 @@
"category": "Error",
"code": 2307
},
+ "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity.": {
+ "category": "Error",
+ "code": 2308
+ },
"An export assignment cannot be used in a module with other exported elements.": {
"category": "Error",
"code": 2309
@@ -892,6 +904,10 @@
"category": "Error",
"code": 2322
},
+ "Cannot redeclare exported variable '{0}'.": {
+ "category": "Error",
+ "code": 2323
+ },
"Property '{0}' is missing in type '{1}'.": {
"category": "Error",
"code": 2324
@@ -1626,7 +1642,7 @@
},
"Cannot assign an abstract constructor type to a non-abstract constructor type.": {
"category": "Error",
- "code":2517
+ "code": 2517
},
"Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": {
"category": "Error",
@@ -1728,6 +1744,10 @@
"category": "Error",
"code": 2657
},
+ "Type '{0}' provides no match for the signature '{1}'": {
+ "category": "Error",
+ "code": 2658
+ },
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2064,6 +2084,22 @@
"category": "Error",
"code": 5054
},
+ "Cannot write file '{0}' because it would overwrite input file.": {
+ "category": "Error",
+ "code": 5055
+ },
+ "Cannot write file '{0}' because it would be overwritten by multiple input files.": {
+ "category": "Error",
+ "code": 5056
+ },
+ "Cannot find a tsconfig.json file at the specified directory: '{0}'": {
+ "category": "Error",
+ "code": 5057
+ },
+ "The specified path does not exist: '{0}'": {
+ "category": "Error",
+ "code": 5058
+ },
"Concatenate and emit output to single file.": {
"category": "Message",
@@ -2105,6 +2141,10 @@
"category": "Message",
"code": 6010
},
+ "Allow default imports from modules with no default export. This does not affect code emit, just typechecking.": {
+ "category": "Message",
+ "code": 6011
+ },
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": {
"category": "Message",
"code": 6015
@@ -2326,6 +2366,11 @@
"category": "Error",
"code": 6082
},
+ "Allow javascript files to be compiled.": {
+ "category": "Message",
+ "code": 6083
+ },
+
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2409,7 +2454,7 @@
"Not all code paths return a value.": {
"category": "Error",
"code": 7030
- },
+ },
"You cannot rename this element.": {
"category": "Error",
"code": 8000
diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts
index d0314649b88..dcfce6a2c81 100644
--- a/src/compiler/emitter.ts
+++ b/src/compiler/emitter.ts
@@ -1,12 +1,9 @@
///
+///
///
/* @internal */
namespace ts {
- export function isExternalModuleOrDeclarationFile(sourceFile: SourceFile) {
- return isExternalModule(sourceFile) || isDeclarationFile(sourceFile);
- }
-
export function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string {
return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
}
@@ -337,47 +334,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
};`;
const compilerOptions = host.getCompilerOptions();
- const languageVersion = compilerOptions.target || ScriptTarget.ES3;
- const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None;
+ const languageVersion = getEmitScriptTarget(compilerOptions);
+ const modulekind = getEmitModuleKind(compilerOptions);
const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
- let diagnostics: Diagnostic[] = [];
+ const emitterDiagnostics = createDiagnosticCollection();
+ let emitSkipped = false;
const newLine = host.getNewLine();
- const jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve;
- const shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring);
- const outFile = compilerOptions.outFile || compilerOptions.out;
const emitJavaScript = createFileEmitter();
-
- if (targetSourceFile === undefined) {
- if (outFile) {
- emitFile(outFile);
- }
- else {
- forEach(host.getSourceFiles(), sourceFile => {
- if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
- const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
- emitFile(jsFilePath, sourceFile);
- }
- });
- }
- }
- else {
- // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service)
- if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {
- const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js");
- emitFile(jsFilePath, targetSourceFile);
- }
- else if (!isDeclarationFile(targetSourceFile) && outFile) {
- emitFile(outFile);
- }
- }
-
- // Sort and make the unique list of diagnostics
- diagnostics = sortAndDeduplicateDiagnostics(diagnostics);
+ forEachExpectedEmitFile(host, emitFile, targetSourceFile);
return {
- emitSkipped: false,
- diagnostics,
+ emitSkipped,
+ diagnostics: emitterDiagnostics.getDiagnostics(),
sourceMaps: sourceMapDataList
};
@@ -428,18 +397,23 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
* var loop = function(x) { }
* var arguments_1 = arguments
* for (var x;;) loop(x);
- * otherwise semantics of the code will be different since 'arguments' inside converted loop body
+ * otherwise semantics of the code will be different since 'arguments' inside converted loop body
* will refer to function that holds converted loop.
* This value is set on demand.
*/
argumentsName?: string;
+ /*
+ * alias for 'this' from the calling code stack frame in case if this was used inside the converted loop
+ */
+ thisName?: string;
+
/*
* list of non-block scoped variable declarations that appear inside converted loop
- * such variable declarations should be moved outside the loop body
+ * such variable declarations should be moved outside the loop body
* for (let x;;) {
* var y = 1;
- * ...
+ * ...
* }
* should be converted to
* var loop = function(x) {
@@ -486,10 +460,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function createFileEmitter(): (jsFilePath: string, root?: SourceFile) => void {
- const writer: EmitTextWriter = createTextWriter(newLine);
+ function createFileEmitter(): (jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void {
+ const writer = createTextWriter(newLine);
const { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer;
+ const sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? createSourceMapWriter(host, writer) : getNullSourceMapWriter();
+ const { setSourceFile, emitStart, emitEnd, emitPos } = sourceMap;
+
let currentSourceFile: SourceFile;
let currentText: string;
let currentLineMap: number[];
@@ -516,7 +493,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let decorateEmitted: boolean;
let paramEmitted: boolean;
let awaiterEmitted: boolean;
- let tempFlags: TempFlags;
+ let tempFlags: TempFlags = 0;
let tempVariables: Identifier[];
let tempParameters: Identifier[];
let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
@@ -524,43 +501,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let exportEquals: ExportAssignment;
let hasExportStars: boolean;
- /** Write emitted output to disk */
- let writeEmittedFiles = writeJavaScriptFile;
-
let detachedCommentsInfo: { nodePos: number; detachedCommentEndPos: number }[];
- let writeComment = writeCommentRange;
-
- /** Emit a node */
- let emit = emitNodeWithCommentsAndWithoutSourcemap;
-
- /** Called just before starting emit of a node */
- let emitStart = function (node: Node) { };
-
- /** Called once the emit of the node is done */
- let emitEnd = function (node: Node) { };
-
- /** Emit the text for the given token that comes after startPos
- * This by default writes the text provided with the given tokenKind
- * but if optional emitFn callback is provided the text is emitted using the callback instead of default text
- * @param tokenKind the kind of the token to search and emit
- * @param startPos the position in the source to start searching for the token
- * @param emitFn if given will be invoked to emit the text instead of actual token emit */
- let emitToken = emitTokenText;
-
- /** Called to before starting the lexical scopes as in function/class in the emitted code because of node
- * @param scopeDeclaration node that starts the lexical scope
- * @param scopeName Optional name of this scope instead of deducing one from the declaration node */
- let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { };
-
- /** Called after coming out of the scope */
- let scopeEmitEnd = function() { };
-
/** Sourcemap data that will get encoded */
let sourceMapData: SourceMapData;
- /** The root file passed to the emit function (if present) */
- let root: SourceFile;
+ /** Is the file being emitted into its own file */
+ let isOwnFileEmit: boolean;
/** If removeComments is true, no leading-comments needed to be emitted **/
const emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker;
@@ -583,18 +530,40 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return doEmit;
- function doEmit(jsFilePath: string, rootFile?: SourceFile) {
+ function doEmit(jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
+ sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
+ generatedNameSet = {};
+ nodeToGeneratedName = [];
+ isOwnFileEmit = !isBundledEmit;
+
+ // Emit helpers from all the files
+ if (isBundledEmit && modulekind) {
+ forEach(sourceFiles, emitEmitHelpers);
+ }
+
+ // Do not call emit directly. It does not set the currentSourceFile.
+ forEach(sourceFiles, emitSourceFile);
+
+ writeLine();
+
+ const sourceMappingURL = sourceMap.getSourceMappingURL();
+ if (sourceMappingURL) {
+ write(`//# sourceMappingURL=${sourceMappingURL}`);
+ }
+
+ writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM);
+
// reset the state
+ sourceMap.reset();
writer.reset();
currentSourceFile = undefined;
currentText = undefined;
currentLineMap = undefined;
exportFunctionForFile = undefined;
- generatedNameSet = {};
- nodeToGeneratedName = [];
+ generatedNameSet = undefined;
+ nodeToGeneratedName = undefined;
computedPropertyNamesToGeneratedNames = undefined;
convertedLoopState = undefined;
-
extendsEmitted = false;
decorateEmitted = false;
paramEmitted = false;
@@ -611,29 +580,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
isEs6Module = false;
renamedDependencies = undefined;
isCurrentFileExternalModule = false;
- root = rootFile;
-
- if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
- initializeEmitterWithSourceMaps(jsFilePath, root);
- }
-
- if (root) {
- // Do not call emit directly. It does not set the currentSourceFile.
- emitSourceFile(root);
- }
- else {
- if (modulekind) {
- forEach(host.getSourceFiles(), emitEmitHelpers);
- }
- forEach(host.getSourceFiles(), sourceFile => {
- if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && isExternalModule(sourceFile))) {
- emitSourceFile(sourceFile);
- }
- });
- }
-
- writeLine();
- writeEmittedFiles(writer.getText(), jsFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM);
}
function emitSourceFile(sourceFile: SourceFile): void {
@@ -647,7 +593,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
currentFileIdentifiers = sourceFile.identifiers;
isCurrentFileExternalModule = isExternalModule(sourceFile);
- emit(sourceFile);
+ setSourceFile(sourceFile);
+ emitNodeWithCommentsAndWithoutSourcemap(sourceFile);
}
function isUniqueName(name: string): boolean {
@@ -744,400 +691,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = unescapeIdentifier(generateNameForNode(node)));
}
- function initializeEmitterWithSourceMaps(jsFilePath: string, root?: SourceFile) {
- let sourceMapDir: string; // The directory in which sourcemap will be
-
- // Current source map file and its index in the sources list
- let sourceMapSourceIndex = -1;
-
- // Names and its index map
- const sourceMapNameIndexMap: Map = {};
- const sourceMapNameIndices: number[] = [];
- function getSourceMapNameIndex() {
- return sourceMapNameIndices.length ? lastOrUndefined(sourceMapNameIndices) : -1;
+ /** Write emitted output to disk */
+ function writeEmittedFiles(emitOutput: string, jsFilePath: string, sourceMapFilePath: string, writeByteOrderMark: boolean) {
+ if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
+ writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false);
}
- // Last recorded and encoded spans
- let lastRecordedSourceMapSpan: SourceMapSpan;
- let lastEncodedSourceMapSpan: SourceMapSpan = {
- emittedLine: 1,
- emittedColumn: 1,
- sourceLine: 1,
- sourceColumn: 1,
- sourceIndex: 0
- };
- let lastEncodedNameIndex = 0;
-
- // Encoding for sourcemap span
- function encodeLastRecordedSourceMapSpan() {
- if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {
- return;
- }
-
- let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
- // Line/Comma delimiters
- if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
- // Emit comma to separate the entry
- if (sourceMapData.sourceMapMappings) {
- sourceMapData.sourceMapMappings += ",";
- }
- }
- else {
- // Emit line delimiters
- for (let encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
- sourceMapData.sourceMapMappings += ";";
- }
- prevEncodedEmittedColumn = 1;
- }
-
- // 1. Relative Column 0 based
- sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);
-
- // 2. Relative sourceIndex
- sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);
-
- // 3. Relative sourceLine 0 based
- sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);
-
- // 4. Relative sourceColumn 0 based
- sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);
-
- // 5. Relative namePosition 0 based
- if (lastRecordedSourceMapSpan.nameIndex >= 0) {
- sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);
- lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;
- }
-
- lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;
- sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);
-
- function base64VLQFormatEncode(inValue: number) {
- function base64FormatEncode(inValue: number) {
- if (inValue < 64) {
- return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue);
- }
- throw TypeError(inValue + ": not a 64 based value");
- }
-
- // Add a new least significant bit that has the sign of the value.
- // if negative number the least significant bit that gets added to the number has value 1
- // else least significant bit value that gets added is 0
- // eg. -1 changes to binary : 01 [1] => 3
- // +1 changes to binary : 01 [0] => 2
- if (inValue < 0) {
- inValue = ((-inValue) << 1) + 1;
- }
- else {
- inValue = inValue << 1;
- }
-
- // Encode 5 bits at a time starting from least significant bits
- let encodedStr = "";
- do {
- let currentDigit = inValue & 31; // 11111
- inValue = inValue >> 5;
- if (inValue > 0) {
- // There are still more digits to decode, set the msb (6th bit)
- currentDigit = currentDigit | 32;
- }
- encodedStr = encodedStr + base64FormatEncode(currentDigit);
- } while (inValue > 0);
-
- return encodedStr;
- }
+ if (sourceMapDataList) {
+ sourceMapDataList.push(sourceMap.getSourceMapData());
}
- function recordSourceMapSpan(pos: number) {
- const sourceLinePos = computeLineAndCharacterOfPosition(currentLineMap, pos);
-
- // Convert the location to be one-based.
- sourceLinePos.line++;
- sourceLinePos.character++;
-
- const emittedLine = writer.getLine();
- const emittedColumn = writer.getColumn();
-
- // If this location wasn't recorded or the location in source is going backwards, record the span
- if (!lastRecordedSourceMapSpan ||
- lastRecordedSourceMapSpan.emittedLine !== emittedLine ||
- lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||
- (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&
- (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||
- (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {
- // Encode the last recordedSpan before assigning new
- encodeLastRecordedSourceMapSpan();
-
- // New span
- lastRecordedSourceMapSpan = {
- emittedLine: emittedLine,
- emittedColumn: emittedColumn,
- sourceLine: sourceLinePos.line,
- sourceColumn: sourceLinePos.character,
- nameIndex: getSourceMapNameIndex(),
- sourceIndex: sourceMapSourceIndex
- };
- }
- else {
- // Take the new pos instead since there is no change in emittedLine and column since last location
- lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;
- lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;
- lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;
- }
- }
-
- function recordEmitNodeStartSpan(node: Node) {
- // Get the token pos after skipping to the token (ignoring the leading trivia)
- recordSourceMapSpan(skipTrivia(currentText, node.pos));
- }
-
- function recordEmitNodeEndSpan(node: Node) {
- recordSourceMapSpan(node.end);
- }
-
- function writeTextWithSpanRecord(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) {
- const tokenStartPos = ts.skipTrivia(currentText, startPos);
- recordSourceMapSpan(tokenStartPos);
- const tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);
- recordSourceMapSpan(tokenEndPos);
- return tokenEndPos;
- }
-
- function recordNewSourceFileStart(node: SourceFile) {
- // Add the file to tsFilePaths
- // If sourceroot option: Use the relative path corresponding to the common directory path
- // otherwise source locations relative to map file location
- const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
-
- sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath,
- node.fileName,
- host.getCurrentDirectory(),
- host.getCanonicalFileName,
- /*isAbsolutePathAnUrl*/ true));
- sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1;
-
- // The one that can be used from program to get the actual source file
- sourceMapData.inputSourceFileNames.push(node.fileName);
-
- if (compilerOptions.inlineSources) {
- if (!sourceMapData.sourceMapSourcesContent) {
- sourceMapData.sourceMapSourcesContent = [];
- }
- sourceMapData.sourceMapSourcesContent.push(node.text);
- }
- }
-
- function recordScopeNameOfNode(node: Node, scopeName?: string) {
- function recordScopeNameIndex(scopeNameIndex: number) {
- sourceMapNameIndices.push(scopeNameIndex);
- }
-
- function recordScopeNameStart(scopeName: string) {
- let scopeNameIndex = -1;
- if (scopeName) {
- const parentIndex = getSourceMapNameIndex();
- if (parentIndex !== -1) {
- // Child scopes are always shown with a dot (even if they have no name),
- // unless it is a computed property. Then it is shown with brackets,
- // but the brackets are included in the name.
- const name = (node).name;
- if (!name || name.kind !== SyntaxKind.ComputedPropertyName) {
- scopeName = "." + scopeName;
- }
- scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName;
- }
-
- scopeNameIndex = getProperty(sourceMapNameIndexMap, scopeName);
- if (scopeNameIndex === undefined) {
- scopeNameIndex = sourceMapData.sourceMapNames.length;
- sourceMapData.sourceMapNames.push(scopeName);
- sourceMapNameIndexMap[scopeName] = scopeNameIndex;
- }
- }
- recordScopeNameIndex(scopeNameIndex);
- }
-
- if (scopeName) {
- // The scope was already given a name use it
- recordScopeNameStart(scopeName);
- }
- else if (node.kind === SyntaxKind.FunctionDeclaration ||
- node.kind === SyntaxKind.FunctionExpression ||
- node.kind === SyntaxKind.MethodDeclaration ||
- node.kind === SyntaxKind.MethodSignature ||
- node.kind === SyntaxKind.GetAccessor ||
- node.kind === SyntaxKind.SetAccessor ||
- node.kind === SyntaxKind.ModuleDeclaration ||
- node.kind === SyntaxKind.ClassDeclaration ||
- node.kind === SyntaxKind.EnumDeclaration) {
- // Declaration and has associated name use it
- if ((node).name) {
- const name = (node).name;
- // For computed property names, the text will include the brackets
- scopeName = name.kind === SyntaxKind.ComputedPropertyName
- ? getTextOfNode(name)
- : ((node).name).text;
- }
- recordScopeNameStart(scopeName);
- }
- else {
- // Block just use the name from upper level scope
- recordScopeNameIndex(getSourceMapNameIndex());
- }
- }
-
- function recordScopeNameEnd() {
- sourceMapNameIndices.pop();
- };
-
- function writeCommentRangeWithMap(currentText: string, currentLineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) {
- recordSourceMapSpan(comment.pos);
- writeCommentRange(currentText, currentLineMap, writer, comment, newLine);
- recordSourceMapSpan(comment.end);
- }
-
- function serializeSourceMapContents(version: number, file: string, sourceRoot: string, sources: string[], names: string[], mappings: string, sourcesContent?: string[]) {
- if (typeof JSON !== "undefined") {
- const map: any = {
- version,
- file,
- sourceRoot,
- sources,
- names,
- mappings
- };
-
- if (sourcesContent !== undefined) {
- map.sourcesContent = sourcesContent;
- }
-
- return JSON.stringify(map);
- }
-
- return "{\"version\":" + version + ",\"file\":\"" + escapeString(file) + "\",\"sourceRoot\":\"" + escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}";
-
- function serializeStringArray(list: string[]): string {
- let output = "";
- for (let i = 0, n = list.length; i < n; i++) {
- if (i) {
- output += ",";
- }
- output += "\"" + escapeString(list[i]) + "\"";
- }
- return output;
- }
- }
-
- function writeJavaScriptAndSourceMapFile(emitOutput: string, jsFilePath: string, writeByteOrderMark: boolean) {
- encodeLastRecordedSourceMapSpan();
-
- const sourceMapText = serializeSourceMapContents(
- 3,
- sourceMapData.sourceMapFile,
- sourceMapData.sourceMapSourceRoot,
- sourceMapData.sourceMapSources,
- sourceMapData.sourceMapNames,
- sourceMapData.sourceMapMappings,
- sourceMapData.sourceMapSourcesContent);
-
- sourceMapDataList.push(sourceMapData);
-
- let sourceMapUrl: string;
- if (compilerOptions.inlineSourceMap) {
- // Encode the sourceMap into the sourceMap url
- const base64SourceMapText = convertToBase64(sourceMapText);
- sourceMapUrl = `//# sourceMappingURL=data:application/json;base64,${base64SourceMapText}`;
- }
- else {
- // Write source map file
- writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false);
- sourceMapUrl = `//# sourceMappingURL=${sourceMapData.jsSourceMappingURL}`;
- }
-
- // Write sourcemap url to the js file and write the js file
- writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark);
- }
-
- // Initialize source map data
- const sourceMapJsFile = getBaseFileName(normalizeSlashes(jsFilePath));
- sourceMapData = {
- sourceMapFilePath: jsFilePath + ".map",
- jsSourceMappingURL: sourceMapJsFile + ".map",
- sourceMapFile: sourceMapJsFile,
- sourceMapSourceRoot: compilerOptions.sourceRoot || "",
- sourceMapSources: [],
- inputSourceFileNames: [],
- sourceMapNames: [],
- sourceMapMappings: "",
- sourceMapSourcesContent: undefined,
- sourceMapDecodedMappings: []
- };
-
- // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
- // relative paths of the sources list in the sourcemap
- sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);
- if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== CharacterCodes.slash) {
- sourceMapData.sourceMapSourceRoot += directorySeparator;
- }
-
- if (compilerOptions.mapRoot) {
- sourceMapDir = normalizeSlashes(compilerOptions.mapRoot);
- if (root) { // emitting single module file
- // For modules or multiple emit files the mapRoot will have directory structure like the sources
- // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
- sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(root, host, sourceMapDir));
- }
-
- if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) {
- // The relative paths are relative to the common directory
- sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
- sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl(
- getDirectoryPath(normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath
- combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
- host.getCurrentDirectory(),
- host.getCanonicalFileName,
- /*isAbsolutePathAnUrl*/ true);
- }
- else {
- sourceMapData.jsSourceMappingURL = combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);
- }
- }
- else {
- sourceMapDir = getDirectoryPath(normalizePath(jsFilePath));
- }
-
- function emitNodeWithSourceMap(node: Node) {
- if (node) {
- if (nodeIsSynthesized(node)) {
- return emitNodeWithoutSourceMap(node);
- }
- if (node.kind !== SyntaxKind.SourceFile) {
- recordEmitNodeStartSpan(node);
- emitNodeWithoutSourceMap(node);
- recordEmitNodeEndSpan(node);
- }
- else {
- recordNewSourceFileStart(node);
- emitNodeWithoutSourceMap(node);
- }
- }
- }
-
- function emitNodeWithCommentsAndWithSourcemap(node: Node) {
- emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap);
- }
-
- writeEmittedFiles = writeJavaScriptAndSourceMapFile;
- emit = emitNodeWithCommentsAndWithSourcemap;
- emitStart = recordEmitNodeStartSpan;
- emitEnd = recordEmitNodeEndSpan;
- emitToken = writeTextWithSpanRecord;
- scopeEmitStart = recordScopeNameOfNode;
- scopeEmitEnd = recordScopeNameEnd;
- writeComment = writeCommentRangeWithMap;
- }
-
- function writeJavaScriptFile(emitOutput: string, jsFilePath: string, writeByteOrderMark: boolean) {
- writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
+ writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
// Create a temporary variable with a unique unused name.
@@ -1175,7 +739,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function emitTokenText(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) {
+ /** Emit the text for the given token that comes after startPos
+ * This by default writes the text provided with the given tokenKind
+ * but if optional emitFn callback is provided the text is emitted using the callback instead of default text
+ * @param tokenKind the kind of the token to search and emit
+ * @param startPos the position in the source to start searching for the token
+ * @param emitFn if given will be invoked to emit the text instead of actual token emit */
+ function emitToken(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) {
+ const tokenStartPos = skipTrivia(currentText, startPos);
+ emitPos(tokenStartPos);
+
const tokenString = tokenToString(tokenKind);
if (emitFn) {
emitFn();
@@ -1183,7 +756,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
write(tokenString);
}
- return startPos + tokenString.length;
+
+ const tokenEndPos = tokenStartPos + tokenString.length;
+ emitPos(tokenEndPos);
+ return tokenEndPos;
}
function emitOptional(prefix: string, node: Node) {
@@ -1292,7 +868,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitCommaList(nodes: Node[]) {
if (nodes) {
- emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false);
+ emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false);
}
}
@@ -1307,7 +883,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function isBinaryOrOctalIntegerLiteral(node: LiteralExpression, text: string): boolean {
+ function isBinaryOrOctalIntegerLiteral(node: LiteralLikeNode, text: string): boolean {
if (node.kind === SyntaxKind.NumericLiteral && text.length > 1) {
switch (text.charCodeAt(1)) {
case CharacterCodes.b:
@@ -1321,7 +897,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return false;
}
- function emitLiteral(node: LiteralExpression) {
+ function emitLiteral(node: LiteralExpression | TemplateLiteralFragment) {
const text = getLiteralText(node);
if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) {
@@ -1336,7 +912,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function getLiteralText(node: LiteralExpression) {
+ function getLiteralText(node: LiteralExpression | TemplateLiteralFragment) {
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
@@ -1395,7 +971,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`"${text}"`);
}
- function emitDownlevelTaggedTemplateArray(node: TaggedTemplateExpression, literalEmitter: (literal: LiteralExpression) => void) {
+ function emitDownlevelTaggedTemplateArray(node: TaggedTemplateExpression, literalEmitter: (literal: LiteralExpression | TemplateLiteralFragment) => void) {
write("[");
if (node.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral) {
literalEmitter(node.template);
@@ -1592,13 +1168,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/// these emit into an object literal property name, we don't need to be worried
/// about keywords, just non-identifier characters
function emitAttributeName(name: Identifier) {
- if (/[A-Za-z_]+[\w*]/.test(name.text)) {
- write("\"");
+ if (/^[A-Za-z_]\w*$/.test(name.text)) {
emit(name);
- write("\"");
}
else {
+ write("\"");
emit(name);
+ write("\"");
}
}
@@ -2028,6 +1604,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.LexicalThis) {
write("_this");
}
+ else if (convertedLoopState) {
+ write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this")));
+ }
else {
write("this");
}
@@ -2191,7 +1770,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else if (languageVersion >= ScriptTarget.ES6 || !forEach(elements, isSpreadElementExpression)) {
write("[");
- emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false);
+ emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false);
write("]");
}
else {
@@ -2215,7 +1794,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// then try to preserve the original shape of the object literal.
// Otherwise just try to preserve the formatting.
if (numElements === properties.length) {
- emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= ScriptTarget.ES5, /* spacesBetweenBraces */ true);
+ emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= ScriptTarget.ES5, /*spacesBetweenBraces*/ true);
}
else {
const multiLine = (node.flags & NodeFlags.MultiLine) !== 0;
@@ -2611,7 +2190,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.right);
}
- function emitEntityNameAsExpression(node: EntityName, useFallback: boolean) {
+ function emitEntityNameAsExpression(node: EntityName | Expression, useFallback: boolean) {
switch (node.kind) {
case SyntaxKind.Identifier:
if (useFallback) {
@@ -2626,6 +2205,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
case SyntaxKind.QualifiedName:
emitQualifiedNameAsExpression(node, useFallback);
break;
+
+ default:
+ emitNodeWithoutSourceMap(node);
+ break;
}
}
@@ -2765,7 +2348,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(".bind.apply(");
emit(target);
write(", [void 0].concat(");
- emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false);
+ emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false);
write(")))");
write("()");
}
@@ -2982,7 +2565,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
synthesizedLHS = createSynthesizedNode(SyntaxKind.ElementAccessExpression, /*startsOnNewLine*/ false);
- const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false);
+ const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false);
synthesizedLHS.expression = identifier;
if (leftHandSideExpression.argumentExpression.kind !== SyntaxKind.NumericLiteral &&
@@ -3001,7 +2584,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("(");
synthesizedLHS = createSynthesizedNode(SyntaxKind.PropertyAccessExpression, /*startsOnNewLine*/ false);
- const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false);
+ const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false);
synthesizedLHS.expression = identifier;
(synthesizedLHS).dotToken = leftHandSideExpression.dotToken;
@@ -3121,7 +2704,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitToken(SyntaxKind.OpenBraceToken, node.pos);
increaseIndent();
- scopeEmitStart(node.parent);
if (node.kind === SyntaxKind.ModuleBlock) {
Debug.assert(node.parent.kind === SyntaxKind.ModuleDeclaration);
emitCaptureThisForNodeIfNecessary(node.parent);
@@ -3133,7 +2715,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
decreaseIndent();
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.statements.end);
- scopeEmitEnd();
}
function emitEmbeddedStatement(node: Node) {
@@ -3181,10 +2762,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitDoStatementWorker(node: DoStatement, loop: ConvertedLoop) {
write("do");
if (loop) {
- emitConvertedLoopCall(loop, /* emitAsBlock */ true);
+ emitConvertedLoopCall(loop, /*emitAsBlock*/ true);
}
else {
- emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true);
+ emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true);
}
if (node.statement.kind === SyntaxKind.Block) {
write(" ");
@@ -3207,10 +2788,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(")");
if (loop) {
- emitConvertedLoopCall(loop, /* emitAsBlock */ true);
+ emitConvertedLoopCall(loop, /*emitAsBlock*/ true);
}
else {
- emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true);
+ emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true);
}
}
@@ -3226,7 +2807,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (convertedLoopState && (getCombinedNodeFlags(decl) & NodeFlags.BlockScoped) === 0) {
- // we are inside a converted loop - this can only happen in downlevel scenarios
+ // we are inside a converted loop - this can only happen in downlevel scenarios
// record names for all variable declarations
for (const varDecl of decl.declarations) {
hoistVariableDeclarationFromLoop(convertedLoopState, varDecl);
@@ -3358,6 +2939,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName;
}
+ if (convertedOuterLoopState.thisName) {
+ // outer loop has already used 'this' so we've already have some name to alias it
+ // use the same name in all nested loops
+ convertedLoopState.thisName = convertedOuterLoopState.thisName;
+ }
+
if (convertedOuterLoopState.hoistedLocalVariables) {
// we've already collected some non-block scoped variable declarations in enclosing loop
// use the same storage in nested loop
@@ -3387,6 +2974,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
}
}
+ if (convertedLoopState.thisName) {
+ // if alias for this is set
+ if (convertedOuterLoopState) {
+ // pass it to outer converted loop
+ convertedOuterLoopState.thisName = convertedLoopState.thisName;
+ }
+ else {
+ // this is top level converted loop so we need to create an alias for 'this' here
+ // NOTE:
+ // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
+ // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
+ write(`var ${convertedLoopState.thisName} = this;`);
+ writeLine();
+ }
+ }
if (convertedLoopState.hoistedLocalVariables) {
// if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
@@ -3532,8 +3134,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`switch(${loopResultVariable}) {`);
increaseIndent();
- emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /* isBreak */ true, loopResultVariable, outerLoop);
- emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /* isBreak */ false, loopResultVariable, outerLoop);
+ emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop);
+ emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop);
decreaseIndent();
writeLine();
@@ -3551,7 +3153,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`case "${labelMarker}": `);
// if there are no outer converted loop or outer label in question is located inside outer converted loop
// then emit labeled break\continue
- // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
+ // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) {
if (isBreak) {
write("break ");
@@ -3597,10 +3199,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(")");
if (loop) {
- emitConvertedLoopCall(loop, /* emitAsBlock */ true);
+ emitConvertedLoopCall(loop, /*emitAsBlock*/ true);
}
else {
- emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true);
+ emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true);
}
}
@@ -3638,10 +3240,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitToken(SyntaxKind.CloseParenToken, node.expression.end);
if (loop) {
- emitConvertedLoopCall(loop, /* emitAsBlock */ true);
+ emitConvertedLoopCall(loop, /*emitAsBlock*/ true);
}
else {
- emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true);
+ emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true);
}
}
@@ -3781,10 +3383,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (loop) {
writeLine();
- emitConvertedLoopCall(loop, /* emitAsBlock */ false);
+ emitConvertedLoopCall(loop, /*emitAsBlock*/ false);
}
else {
- emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ false);
+ emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false);
}
writeLine();
@@ -3818,11 +3420,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let labelMarker: string;
if (node.kind === SyntaxKind.BreakStatement) {
labelMarker = `break-${node.label.text}`;
- setLabeledJump(convertedLoopState, /* isBreak */ true, node.label.text, labelMarker);
+ setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker);
}
else {
labelMarker = `continue-${node.label.text}`;
- setLabeledJump(convertedLoopState, /* isBreak */ false, node.label.text, labelMarker);
+ setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker);
}
write(`return "${labelMarker}";`);
}
@@ -4026,12 +3628,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// only allow export default at a source file level
if (modulekind === ModuleKind.CommonJS || modulekind === ModuleKind.AMD || modulekind === ModuleKind.UMD) {
if (!isEs6Module) {
- if (languageVersion === ScriptTarget.ES5) {
+ if (languageVersion !== ScriptTarget.ES3) {
// default value of configurable, enumerable, writable are `false`.
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
writeLine();
}
- else if (languageVersion === ScriptTarget.ES3) {
+ else {
write("exports.__esModule = true;");
writeLine();
}
@@ -4248,7 +3850,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let index: Expression;
const nameIsComputed = propName.kind === SyntaxKind.ComputedPropertyName;
if (nameIsComputed) {
- index = ensureIdentifier((propName).expression, /* reuseIdentifierExpression */ false);
+ index = ensureIdentifier((propName).expression, /*reuseIdentifierExpressions*/ false);
}
else {
// We create a synthetic copy of the identifier in order to avoid the rewriting that might
@@ -4675,7 +4277,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
// Emit name if one is present, or emit generated name in down-level case (for export default case)
- return !!node.name || languageVersion < ScriptTarget.ES6;
+ return !!node.name || modulekind !== ModuleKind.ES6;
}
}
@@ -4857,18 +4459,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(" __awaiter(this");
if (hasLexicalArguments) {
- write(", arguments");
+ write(", arguments, ");
}
else {
- write(", void 0");
+ write(", void 0, ");
}
if (promiseConstructor) {
- write(", ");
- emitNodeWithoutSourceMap(promiseConstructor);
+ emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false);
}
else {
- write(", Promise");
+ write("Promise");
}
// Emit the call to __awaiter.
@@ -4929,7 +4530,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
const isAsync = isAsyncFunctionLike(node);
- if (isAsync && languageVersion === ScriptTarget.ES6) {
+ if (isAsync) {
emitAsyncFunctionBodyForES6(node);
}
else {
@@ -4978,8 +4579,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitDownLevelExpressionFunctionBody(node: FunctionLikeDeclaration, body: Expression) {
write(" {");
- scopeEmitStart(node);
-
increaseIndent();
const outPos = writer.getTextPos();
emitDetachedCommentsAndUpdateCommentsInfo(node.body);
@@ -5003,8 +4602,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
increaseIndent();
writeLine();
emitLeadingComments(node.body);
+ emitStart(body);
write("return ");
emit(body);
+ emitEnd(body);
write(";");
emitTrailingComments(node.body);
@@ -5016,14 +4617,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitStart(node.body);
write("}");
emitEnd(node.body);
-
- scopeEmitEnd();
}
function emitBlockFunctionBody(node: FunctionLikeDeclaration, body: Block) {
write(" {");
- scopeEmitStart(node);
-
const initialTextPos = writer.getTextPos();
increaseIndent();
@@ -5057,7 +4654,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
emitToken(SyntaxKind.CloseBraceToken, body.statements.end);
- scopeEmitEnd();
}
function findInitialSuperCall(ctor: ConstructorDeclaration): ExpressionStatement {
@@ -5343,7 +4939,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let startIndex = 0;
write(" {");
- scopeEmitStart(node, "constructor");
increaseIndent();
if (ctor) {
// Emit all the directive prologues (like "use strict"). These have to come before
@@ -5378,7 +4973,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitEnd(baseTypeElement);
}
}
- emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false));
+ emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false));
if (ctor) {
let statements: Node[] = (ctor.body).statements;
if (superCall) {
@@ -5393,7 +4988,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
decreaseIndent();
emitToken(SyntaxKind.CloseBraceToken, ctor ? (ctor.body).statements.end : node.members.end);
- scopeEmitEnd();
emitEnd(ctor || node);
if (ctor) {
emitTrailingComments(ctor);
@@ -5500,7 +5094,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
- const staticProperties = getInitializedProperties(node, /*static:*/ true);
+ const staticProperties = getInitializedProperties(node, /*isStatic*/ true);
const isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === SyntaxKind.ClassExpression;
let tempVariable: Identifier;
@@ -5517,7 +5111,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// emit name if
// - node has a name
// - this is default export with static initializers
- if ((node.name || (node.flags & NodeFlags.Default && staticProperties.length > 0)) && !thisNodeIsDecorated) {
+ if ((node.name || (node.flags & NodeFlags.Default && (staticProperties.length > 0 || modulekind !== ModuleKind.ES6))) && !thisNodeIsDecorated) {
write(" ");
emitDeclarationName(node);
}
@@ -5530,14 +5124,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(" {");
increaseIndent();
- scopeEmitStart(node);
writeLine();
emitConstructor(node, baseTypeNode);
emitMemberFunctionsForES6AndHigher(node);
decreaseIndent();
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
- scopeEmitEnd();
// TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now.
@@ -5562,7 +5154,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
for (var property of staticProperties) {
write(",");
writeLine();
- emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true);
+ emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true);
}
write(",");
writeLine();
@@ -5576,23 +5168,33 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDecoratorsOfClass(node);
}
- // If this is an exported class, but not on the top level (i.e. on an internal
- // module), export it
- if (!isES6ExportedDeclaration(node) && (node.flags & NodeFlags.Export)) {
- writeLine();
- emitStart(node);
- emitModuleMemberName(node);
- write(" = ");
- emitDeclarationName(node);
- emitEnd(node);
- write(";");
+ if (!(node.flags & NodeFlags.Export)) {
+ return;
}
- else if (isES6ExportedDeclaration(node) && (node.flags & NodeFlags.Default) && thisNodeIsDecorated) {
- // if this is a top level default export of decorated class, write the export after the declaration.
- writeLine();
- write("export default ");
- emitDeclarationName(node);
- write(";");
+ if (modulekind !== ModuleKind.ES6) {
+ emitExportMemberAssignment(node as ClassDeclaration);
+ }
+ else {
+ // If this is an exported class, but not on the top level (i.e. on an internal
+ // module), export it
+ if (node.flags & NodeFlags.Default) {
+ // if this is a top level default export of decorated class, write the export after the declaration.
+ if (thisNodeIsDecorated) {
+ writeLine();
+ write("export default ");
+ emitDeclarationName(node);
+ write(";");
+ }
+ }
+ else if (node.parent.kind !== SyntaxKind.SourceFile) {
+ writeLine();
+ emitStart(node);
+ emitModuleMemberName(node);
+ write(" = ");
+ emitDeclarationName(node);
+ emitEnd(node);
+ write(";");
+ }
}
}
@@ -5624,7 +5226,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
tempParameters = undefined;
computedPropertyNamesToGeneratedNames = undefined;
increaseIndent();
- scopeEmitStart(node);
if (baseTypeNode) {
writeLine();
emitStart(baseTypeNode);
@@ -5636,7 +5237,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
emitConstructor(node, baseTypeNode);
emitMemberFunctionsForES5AndLower(node);
- emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true));
+ emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true));
writeLine();
emitDecoratorsOfClass(node);
writeLine();
@@ -5657,7 +5258,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
decreaseIndent();
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
- scopeEmitEnd();
emitStart(node);
write(")(");
if (baseTypeNode) {
@@ -5690,10 +5290,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitDecoratorsOfConstructor(node: ClassLikeDeclaration) {
const decorators = node.decorators;
const constructor = getFirstConstructorWithBody(node);
- const hasDecoratedParameters = constructor && forEach(constructor.parameters, nodeIsDecorated);
+ const firstParameterDecorator = constructor && forEach(constructor.parameters, parameter => parameter.decorators);
// skip decoration of the constructor if neither it nor its parameters are decorated
- if (!decorators && !hasDecoratedParameters) {
+ if (!decorators && !firstParameterDecorator) {
return;
}
@@ -5709,28 +5309,27 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
//
writeLine();
- emitStart(node);
+ emitStart(node.decorators || firstParameterDecorator);
emitDeclarationName(node);
write(" = __decorate([");
increaseIndent();
writeLine();
const decoratorCount = decorators ? decorators.length : 0;
- let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, decorator => {
- emitStart(decorator);
- emit(decorator.expression);
- emitEnd(decorator);
- });
-
- argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0);
+ let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true,
+ decorator => emit(decorator.expression));
+ if (firstParameterDecorator) {
+ argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0);
+ }
emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0);
decreaseIndent();
writeLine();
write("], ");
emitDeclarationName(node);
- write(");");
- emitEnd(node);
+ write(")");
+ emitEnd(node.decorators || firstParameterDecorator);
+ write(";");
writeLine();
}
@@ -5746,11 +5345,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
continue;
}
- // skip a member if it or any of its parameters are not decorated
- if (!nodeOrChildIsDecorated(member)) {
- continue;
- }
-
// skip an accessor declaration if it is not the first accessor
let decorators: NodeArray;
let functionLikeMember: FunctionLikeDeclaration;
@@ -5777,6 +5371,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
functionLikeMember = member;
}
}
+ const firstParameterDecorator = functionLikeMember && forEach(functionLikeMember.parameters, parameter => parameter.decorators);
+
+ // skip a member if it or any of its parameters are not decorated
+ if (!decorators && !firstParameterDecorator) {
+ continue;
+ }
// Emit the call to __decorate. Given the following:
//
@@ -5810,29 +5410,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
//
writeLine();
- emitStart(member);
+ emitStart(decorators || firstParameterDecorator);
write("__decorate([");
increaseIndent();
writeLine();
const decoratorCount = decorators ? decorators.length : 0;
- let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, decorator => {
- emitStart(decorator);
- emit(decorator.expression);
- emitEnd(decorator);
- });
+ let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true,
+ decorator => emit(decorator.expression));
- argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0);
+ if (firstParameterDecorator) {
+ argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0);
+ }
emitSerializedTypeMetadata(member, argumentsWritten > 0);
decreaseIndent();
writeLine();
write("], ");
- emitStart(member.name);
emitClassMemberPrefix(node, member);
write(", ");
emitExpressionForPropertyName(member.name);
- emitEnd(member.name);
if (languageVersion > ScriptTarget.ES3) {
if (member.kind !== SyntaxKind.PropertyDeclaration) {
@@ -5847,8 +5444,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- write(");");
- emitEnd(member);
+ write(")");
+ emitEnd(decorators || firstParameterDecorator);
+ write(";");
writeLine();
}
}
@@ -5861,11 +5459,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (nodeIsDecorated(parameter)) {
const decorators = parameter.decorators;
argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, decorator => {
- emitStart(decorator);
write(`__param(${parameterIndex}, `);
emit(decorator.expression);
write(")");
- emitEnd(decorator);
});
leadingComma = true;
}
@@ -5959,7 +5555,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitSerializedTypeNode(node: TypeNode) {
if (node) {
-
switch (node.kind) {
case SyntaxKind.VoidKeyword:
write("void 0");
@@ -5985,7 +5580,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return;
case SyntaxKind.StringKeyword:
- case SyntaxKind.StringLiteral:
+ case SyntaxKind.StringLiteralType:
write("String");
return;
@@ -6006,6 +5601,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.AnyKeyword:
+ case SyntaxKind.ThisType:
break;
default:
@@ -6024,9 +5620,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
// Clone the type name and parent it to a location outside of the current declaration.
- const typeName = cloneEntityName(node.typeName);
- typeName.parent = location;
-
+ const typeName = cloneEntityName(node.typeName, location);
const result = resolver.getTypeReferenceSerializationKind(typeName);
switch (result) {
case TypeReferenceSerializationKind.Unknown:
@@ -6133,7 +5727,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
/** Serializes the return type of function. Used by the __metadata decorator for a method. */
- function emitSerializedReturnTypeOfNode(node: Node): string | string[] {
+ function emitSerializedReturnTypeOfNode(node: Node) {
if (node && isFunctionLike(node) && (node).type) {
emitSerializedTypeNode((node).type);
return;
@@ -6201,9 +5795,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (!shouldHoistDeclarationInSystemJsModule(node)) {
// do not emit var if variable was already hoisted
- if (!(node.flags & NodeFlags.Export) || isES6ExportedDeclaration(node)) {
+
+ const isES6ExportedEnum = isES6ExportedDeclaration(node);
+ if (!(node.flags & NodeFlags.Export) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, SyntaxKind.EnumDeclaration))) {
emitStart(node);
- if (isES6ExportedDeclaration(node)) {
+ if (isES6ExportedEnum) {
write("export ");
}
write("var ");
@@ -6220,12 +5816,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitEnd(node.name);
write(") {");
increaseIndent();
- scopeEmitStart(node);
emitLines(node.members);
decreaseIndent();
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
- scopeEmitEnd();
write(")(");
emitModuleMemberName(node);
write(" || (");
@@ -6302,6 +5896,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return languageVersion === ScriptTarget.ES6 && !!(resolver.getNodeCheckFlags(node) & NodeCheckFlags.LexicalModuleMergesWithClass);
}
+ function isFirstDeclarationOfKind(node: Declaration, declarations: Declaration[], kind: SyntaxKind) {
+ return !forEach(declarations, declaration => declaration.kind === kind && declaration.pos < node.pos);
+ }
+
function emitModuleDeclaration(node: ModuleDeclaration) {
// Emit only if this module is non-ambient.
const shouldEmit = shouldEmitModuleDeclaration(node);
@@ -6313,15 +5911,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
const emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node);
if (emitVarForModule) {
- emitStart(node);
- if (isES6ExportedDeclaration(node)) {
- write("export ");
+ const isES6ExportedNamespace = isES6ExportedDeclaration(node);
+ if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, SyntaxKind.ModuleDeclaration)) {
+ emitStart(node);
+ if (isES6ExportedNamespace) {
+ write("export ");
+ }
+ write("var ");
+ emit(node.name);
+ write(";");
+ emitEnd(node);
+ writeLine();
}
- write("var ");
- emit(node.name);
- write(";");
- emitEnd(node);
- writeLine();
}
emitStart(node);
@@ -6349,7 +5950,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
write("{");
increaseIndent();
- scopeEmitStart(node);
emitCaptureThisForNodeIfNecessary(node);
writeLine();
emit(node.body);
@@ -6357,7 +5957,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
const moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
emitToken(SyntaxKind.CloseBraceToken, moduleBlock.statements.end);
- scopeEmitEnd();
}
write(")(");
// write moduleDecl = containingModule.m only if it is not exported es6 module member
@@ -6802,7 +6401,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string {
+ function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, emitRelativePathAsModuleName: boolean): string {
+ if (emitRelativePathAsModuleName) {
+ const name = getExternalModuleNameFromDeclaration(host, resolver, importNode);
+ if (name) {
+ return `"${name}"`;
+ }
+ }
const moduleName = getExternalModuleName(importNode);
if (moduleName.kind === SyntaxKind.StringLiteral) {
return tryRenameExternalModule(moduleName) || getLiteralText(moduleName);
@@ -7362,7 +6967,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; ++i) {
- let text = getExternalModuleNameText(externalImports[i]);
+ const text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName);
if (hasProperty(groupIndices, text)) {
// deduplicate/group entries in dependency list by the dependency name
const groupIndex = groupIndices[text];
@@ -7378,18 +6983,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(", ");
}
- if (emitRelativePathAsModuleName) {
- const name = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
- if (name) {
- text = `"${name}"`;
- }
- }
write(text);
}
write(`], function(${exportFunctionForFile}) {`);
writeLine();
increaseIndent();
- const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
+ const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitSystemModuleBody(node, dependencyGroups, startIndex);
@@ -7426,14 +7025,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
for (const importNode of externalImports) {
// Find the name of the external module
- let externalModuleName = getExternalModuleNameText(importNode);
-
- if (emitRelativePathAsModuleName) {
- const name = getExternalModuleNameFromDeclaration(host, resolver, importNode);
- if (name) {
- externalModuleName = `"${name}"`;
- }
- }
+ const externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName);
// Find the name of the module alias, if there is one
const importAliasName = getLocalNameForExternalImport(importNode);
@@ -7499,7 +7091,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeModuleName(node, emitRelativePathAsModuleName);
emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName);
increaseIndent();
- const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
+ const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
@@ -7511,7 +7103,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitCommonJSModule(node: SourceFile) {
- const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
+ const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ true);
emitEmitHelpers(node);
collectExternalModuleInfo(node);
emitExportStarHelper();
@@ -7540,7 +7132,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
})(`);
emitAMDFactoryHeader(dependencyNames);
increaseIndent();
- const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
+ const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
@@ -7682,19 +7274,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean): number {
+ function isUseStrictPrologue(node: ExpressionStatement): boolean {
+ return !!(node.expression as StringLiteral).text.match(/use strict/);
+ }
+
+ function ensureUseStrictPrologue(startWithNewLine: boolean, writeUseStrict: boolean) {
+ if (writeUseStrict) {
+ if (startWithNewLine) {
+ writeLine();
+ }
+ write("\"use strict\";");
+ }
+ }
+
+ function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean, ensureUseStrict?: boolean): number {
+ let foundUseStrict = false;
for (let i = 0; i < statements.length; ++i) {
if (isPrologueDirective(statements[i])) {
+ if (isUseStrictPrologue(statements[i] as ExpressionStatement)) {
+ foundUseStrict = true;
+ }
if (startWithNewLine || i > 0) {
writeLine();
}
emit(statements[i]);
}
else {
+ ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict);
// return index of the first non prologue directive
return i;
}
}
+ ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict);
return statements.length;
}
@@ -7746,7 +7357,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDetachedCommentsAndUpdateCommentsInfo(node);
if (isExternalModule(node) || compilerOptions.isolatedModules) {
- if (root || (!isExternalModule(node) && compilerOptions.isolatedModules)) {
+ if (isOwnFileEmit || (!isExternalModule(node) && compilerOptions.isolatedModules)) {
const emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS];
emitModule(node);
}
@@ -7770,6 +7381,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitLeadingComments(node.endOfFileToken);
}
+ function emit(node: Node): void {
+ emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap);
+ }
+
function emitNodeWithCommentsAndWithoutSourcemap(node: Node): void {
emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap);
}
@@ -7798,6 +7413,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
+ function emitNodeWithSourceMap(node: Node): void {
+ if (node) {
+ emitStart(node);
+ emitNodeWithoutSourceMap(node);
+ emitEnd(node);
+ }
+ }
+
function emitNodeWithoutSourceMap(node: Node): void {
if (node) {
emitJavaScriptWorker(node);
@@ -8092,11 +7715,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
* Emit comments associated with node that will not be emitted into JS file
*/
function emitCommentsOnNotEmittedNode(node: Node) {
- emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false);
+ emitLeadingCommentsWorker(node, /*isEmittedNode*/ false);
}
function emitLeadingComments(node: Node) {
- return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true);
+ return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true);
}
function emitLeadingCommentsWorker(node: Node, isEmittedNode: boolean) {
@@ -8125,7 +7748,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
- emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
+ emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitTrailingComments(node: Node) {
@@ -8190,19 +7813,33 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
+ function writeComment(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) {
+ emitPos(comment.pos);
+ writeCommentRange(text, lineMap, writer, comment, newLine);
+ emitPos(comment.end);
+ }
+
function emitShebang() {
const shebang = getShebang(currentText);
if (shebang) {
write(shebang);
+ writeLine();
}
}
}
- function emitFile(jsFilePath: string, sourceFile?: SourceFile) {
- emitJavaScript(jsFilePath, sourceFile);
+ function emitFile({ jsFilePath, sourceMapFilePath, declarationFilePath}: { jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string },
+ sourceFiles: SourceFile[], isBundledEmit: boolean) {
+ // Make sure not to write js File and source map file if any of them cannot be written
+ if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) {
+ emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
+ }
+ else {
+ emitSkipped = true;
+ }
- if (compilerOptions.declaration) {
- writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics);
+ if (declarationFilePath) {
+ emitSkipped = writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
}
}
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts
index ac37f608417..ee942a17390 100644
--- a/src/compiler/parser.ts
+++ b/src/compiler/parser.ts
@@ -544,6 +544,11 @@ namespace ts {
return result;
}
+ 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;
+ }
+
function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, isJavaScriptFile: boolean, _syntaxCursor: IncrementalParser.SyntaxCursor) {
NodeConstructor = objectAllocator.getNodeConstructor();
SourceFileConstructor = objectAllocator.getSourceFileConstructor();
@@ -564,7 +569,7 @@ namespace ts {
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
- scanner.setLanguageVariant(allowsJsxExpressions(fileName) ? LanguageVariant.JSX : LanguageVariant.Standard);
+ scanner.setLanguageVariant(getLanguageVariant(fileName));
}
function clearState() {
@@ -682,7 +687,7 @@ namespace ts {
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = normalizePath(fileName);
sourceFile.flags = fileExtensionIs(sourceFile.fileName, ".d.ts") ? NodeFlags.DeclarationFile : 0;
- sourceFile.languageVariant = allowsJsxExpressions(sourceFile.fileName) ? LanguageVariant.JSX : LanguageVariant.Standard;
+ sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName);
return sourceFile;
}
@@ -722,10 +727,10 @@ namespace ts {
const contextFlagsToClear = context & contextFlags;
if (contextFlagsToClear) {
// clear the requested context flags
- setContextFlag(false, contextFlagsToClear);
+ setContextFlag(/*val*/ false, contextFlagsToClear);
const result = func();
// restore the context flags we just cleared
- setContextFlag(true, contextFlagsToClear);
+ setContextFlag(/*val*/ true, contextFlagsToClear);
return result;
}
@@ -743,10 +748,10 @@ namespace ts {
const contextFlagsToSet = context & ~contextFlags;
if (contextFlagsToSet) {
// set the requested context flags
- setContextFlag(true, contextFlagsToSet);
+ setContextFlag(/*val*/ true, contextFlagsToSet);
const result = func();
// reset the context flags we just set
- setContextFlag(false, contextFlagsToSet);
+ setContextFlag(/*val*/ false, contextFlagsToSet);
return result;
}
@@ -1098,11 +1103,11 @@ namespace ts {
}
function parsePropertyName(): PropertyName {
- return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true);
+ return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
}
function parseSimplePropertyName(): Identifier | LiteralExpression {
- return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false);
+ return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false);
}
function isSimplePropertyName() {
@@ -1157,7 +1162,7 @@ namespace ts {
}
function parseAnyContextualModifier(): boolean {
- return isModifier(token) && tryParse(nextTokenCanFollowModifier);
+ return isModifierKind(token) && tryParse(nextTokenCanFollowModifier);
}
function canFollowModifier(): boolean {
@@ -1385,7 +1390,7 @@ namespace ts {
function isInSomeParsingContext(): boolean {
for (let kind = 0; kind < ParsingContext.Count; kind++) {
if (parsingContext & (1 << kind)) {
- if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) {
+ if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
return true;
}
}
@@ -1402,7 +1407,7 @@ namespace ts {
result.pos = getNodePos();
while (!isListTerminator(kind)) {
- if (isListElement(kind, /* inErrorRecovery */ false)) {
+ if (isListElement(kind, /*inErrorRecovery*/ false)) {
const element = parseListElement(kind, parseElement);
result.push(element);
@@ -1751,7 +1756,7 @@ namespace ts {
let commaStart = -1; // Meaning the previous token was not a comma
while (true) {
- if (isListElement(kind, /* inErrorRecovery */ false)) {
+ if (isListElement(kind, /*inErrorRecovery*/ false)) {
result.push(parseListElement(kind, parseElement));
commaStart = scanner.getTokenPos();
if (parseOptional(SyntaxKind.CommaToken)) {
@@ -1859,7 +1864,7 @@ namespace ts {
// Report that we need an identifier. However, report it right after the dot,
// and not on the next token. This is because the next token might actually
// be an identifier and the error would be quite confusing.
- return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentToken*/ true, Diagnostics.Identifier_expected);
+ return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected);
}
}
@@ -1869,7 +1874,7 @@ namespace ts {
function parseTemplateExpression(): TemplateExpression {
const template = createNode(SyntaxKind.TemplateExpression);
- template.head = parseLiteralNode();
+ template.head = parseTemplateLiteralFragment();
Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
const templateSpans = >[];
@@ -1890,22 +1895,34 @@ namespace ts {
const span = createNode(SyntaxKind.TemplateSpan);
span.expression = allowInAnd(parseExpression);
- let literal: LiteralExpression;
+ let literal: TemplateLiteralFragment;
if (token === SyntaxKind.CloseBraceToken) {
reScanTemplateToken();
- literal = parseLiteralNode();
+ literal = parseTemplateLiteralFragment();
}
else {
- literal = parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
+ literal = parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
}
span.literal = literal;
return finishNode(span);
}
+ function parseStringLiteralTypeNode(): StringLiteralTypeNode {
+ return parseLiteralLikeNode(SyntaxKind.StringLiteralType, /*internName*/ true);
+ }
+
function parseLiteralNode(internName?: boolean): LiteralExpression {
- const node = createNode(token);
+ return parseLiteralLikeNode(token, internName);
+ }
+
+ function parseTemplateLiteralFragment(): TemplateLiteralFragment {
+ return parseLiteralLikeNode(token, /*internName*/ false);
+ }
+
+ function parseLiteralLikeNode(kind: SyntaxKind, internName: boolean): LiteralLikeNode {
+ const node = createNode(kind);
const text = scanner.getTokenValue();
node.text = internName ? internIdentifier(text) : text;
@@ -1956,6 +1973,12 @@ namespace ts {
return finishNode(node);
}
+ function parseThisTypeNode(): TypeNode {
+ const node = createNode(SyntaxKind.ThisType);
+ nextToken();
+ return finishNode(node);
+ }
+
function parseTypeQuery(): TypeQueryNode {
const node = createNode(SyntaxKind.TypeQuery);
parseExpected(SyntaxKind.TypeOfKeyword);
@@ -2004,7 +2027,7 @@ namespace ts {
}
function isStartOfParameter(): boolean {
- return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifier(token) || token === SyntaxKind.AtToken;
+ return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken;
}
function setModifiers(node: Node, modifiers: ModifiersArray) {
@@ -2025,7 +2048,7 @@ namespace ts {
node.name = parseIdentifierOrPattern();
- if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifier(token)) {
+ if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifierKind(token)) {
// in cases like
// 'use strict'
// function foo(static)
@@ -2132,8 +2155,8 @@ namespace ts {
parseSemicolon();
}
- function parseSignatureMember(kind: SyntaxKind): SignatureDeclaration {
- const node = createNode(kind);
+ function parseSignatureMember(kind: SyntaxKind): CallSignatureDeclaration | ConstructSignatureDeclaration {
+ const node = createNode(kind);
if (kind === SyntaxKind.ConstructSignature) {
parseExpected(SyntaxKind.NewKeyword);
}
@@ -2172,7 +2195,7 @@ namespace ts {
return true;
}
- if (isModifier(token)) {
+ if (isModifierKind(token)) {
nextToken();
if (isIdentifier()) {
return true;
@@ -2215,13 +2238,13 @@ namespace ts {
return finishNode(node);
}
- function parsePropertyOrMethodSignature(): Declaration {
+ function parsePropertyOrMethodSignature(): PropertySignature | MethodSignature {
const fullStart = scanner.getStartPos();
const name = parsePropertyName();
const questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
- const method = createNode(SyntaxKind.MethodSignature, fullStart);
+ const method = createNode(SyntaxKind.MethodSignature, fullStart);
method.name = name;
method.questionToken = questionToken;
@@ -2232,10 +2255,18 @@ namespace ts {
return finishNode(method);
}
else {
- const property = createNode(SyntaxKind.PropertySignature, fullStart);
+ const property = createNode(SyntaxKind.PropertySignature, fullStart);
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
+
+ if (token === SyntaxKind.EqualsToken) {
+ // Although type literal properties cannot not have initializers, we attempt
+ // to parse an initializer so we can report in the checker that an interface
+ // property or type literal property cannot have an initializer.
+ property.initializer = parseNonParameterInitializer();
+ }
+
parseTypeMemberSemicolon();
return finishNode(property);
}
@@ -2248,7 +2279,7 @@ namespace ts {
case SyntaxKind.OpenBracketToken: // Both for indexers and computed properties
return true;
default:
- if (isModifier(token)) {
+ if (isModifierKind(token)) {
const result = lookAhead(isStartOfIndexSignatureDeclaration);
if (result) {
return result;
@@ -2260,7 +2291,7 @@ namespace ts {
}
function isStartOfIndexSignatureDeclaration() {
- while (isModifier(token)) {
+ while (isModifierKind(token)) {
nextToken();
}
@@ -2276,7 +2307,7 @@ namespace ts {
canParseSemicolon();
}
- function parseTypeMember(): Declaration {
+ function parseTypeMember(): TypeElement {
switch (token) {
case SyntaxKind.OpenParenToken:
case SyntaxKind.LessThanToken:
@@ -2301,7 +2332,7 @@ namespace ts {
// 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 (isModifier(token)) {
+ if (isModifierKind(token)) {
const result = tryParse(parseIndexSignatureWithModifiers);
if (result) {
return result;
@@ -2334,14 +2365,14 @@ namespace ts {
return finishNode(node);
}
- function parseObjectTypeMembers(): NodeArray {
- let members: NodeArray;
+ function parseObjectTypeMembers(): NodeArray {
+ let members: NodeArray;
if (parseExpected(SyntaxKind.OpenBraceToken)) {
members = parseList(ParsingContext.TypeMembers, parseTypeMember);
parseExpected(SyntaxKind.CloseBraceToken);
}
else {
- members = createMissingList();
+ members = createMissingList();
}
return members;
@@ -2386,10 +2417,11 @@ namespace ts {
const node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
case SyntaxKind.StringLiteral:
- return parseLiteralNode(/*internName*/ true);
+ return parseStringLiteralTypeNode();
case SyntaxKind.VoidKeyword:
- case SyntaxKind.ThisKeyword:
return parseTokenNode();
+ case SyntaxKind.ThisKeyword:
+ return parseThisTypeNode();
case SyntaxKind.TypeOfKeyword:
return parseTypeQuery();
case SyntaxKind.OpenBraceToken:
@@ -2483,11 +2515,11 @@ namespace ts {
// ( ...
return true;
}
- if (isIdentifier() || isModifier(token)) {
+ if (isIdentifier() || isModifierKind(token)) {
nextToken();
if (token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken ||
token === SyntaxKind.QuestionToken || token === SyntaxKind.EqualsToken ||
- isIdentifier() || isModifier(token)) {
+ isIdentifier() || isModifierKind(token)) {
// ( id :
// ( id ,
// ( id ?
@@ -2609,7 +2641,7 @@ namespace ts {
// clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
const saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
- setDecoratorContext(false);
+ setDecoratorContext(/*val*/ false);
}
let expr = parseAssignmentExpressionOrHigher();
@@ -2619,7 +2651,7 @@ namespace ts {
}
if (saveDecoratorContext) {
- setDecoratorContext(true);
+ setDecoratorContext(/*val*/ true);
}
return expr;
}
@@ -2773,7 +2805,7 @@ namespace ts {
node.parameters.pos = parameter.pos;
node.parameters.end = parameter.end;
- node.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, false, Diagnostics._0_expected, "=>");
+ node.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, "=>");
node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false);
return finishNode(node);
@@ -2894,7 +2926,7 @@ namespace ts {
}
// This *could* be a parenthesized arrow function.
- // Return Unknown to const the caller know.
+ // Return Unknown to let the caller know.
return Tristate.Unknown;
}
else {
@@ -2993,7 +3025,7 @@ namespace ts {
// user meant to supply a block. For example, if the user wrote:
//
// a =>
- // const v = 0;
+ // let v = 0;
// }
//
// they may be missing an open brace. Check to see if that's the case so we can
@@ -3220,7 +3252,7 @@ namespace ts {
/**
* Parse ES7 unary expression and await expression
- *
+ *
* ES7 UnaryExpression:
* 1) SimpleUnaryExpression[?yield]
* 2) IncrementExpression[?yield] ** UnaryExpression[?yield]
@@ -3573,7 +3605,7 @@ namespace ts {
parseExpected(SyntaxKind.GreaterThanToken);
}
else {
- parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*advance*/ false);
+ parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
node = createNode(SyntaxKind.JsxSelfClosingElement, fullStart);
@@ -3609,7 +3641,7 @@ namespace ts {
parseExpected(SyntaxKind.CloseBraceToken);
}
else {
- parseExpected(SyntaxKind.CloseBraceToken, /*message*/ undefined, /*advance*/ false);
+ parseExpected(SyntaxKind.CloseBraceToken, /*message*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
@@ -3654,7 +3686,7 @@ namespace ts {
parseExpected(SyntaxKind.GreaterThanToken);
}
else {
- parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*advance*/ false);
+ parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
return finishNode(node);
@@ -3973,7 +4005,7 @@ namespace ts {
// function BindingIdentifier[opt](FormalParameters){ FunctionBody }
const saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
- setDecoratorContext(false);
+ setDecoratorContext(/*val*/ false);
}
const node = createNode(SyntaxKind.FunctionExpression);
@@ -3993,7 +4025,7 @@ namespace ts {
node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false);
if (saveDecoratorContext) {
- setDecoratorContext(true);
+ setDecoratorContext(/*val*/ true);
}
return finishNode(node);
@@ -4039,13 +4071,13 @@ namespace ts {
// arrow function. The body of the function is not in [Decorator] context.
const saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
- setDecoratorContext(false);
+ setDecoratorContext(/*val*/ false);
}
const block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage);
if (saveDecoratorContext) {
- setDecoratorContext(true);
+ setDecoratorContext(/*val*/ true);
}
setYieldContext(savedYieldContext);
@@ -4720,7 +4752,7 @@ namespace ts {
return finishNode(node);
}
- function parseMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, asteriskToken: Node, name: DeclarationName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
+ function parseMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
const method = createNode(SyntaxKind.MethodDeclaration, fullStart);
method.decorators = decorators;
setModifiers(method, modifiers);
@@ -4734,7 +4766,7 @@ namespace ts {
return finishNode(method);
}
- function parsePropertyDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, name: DeclarationName, questionToken: Node): ClassElement {
+ function parsePropertyDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, name: PropertyName, questionToken: Node): ClassElement {
const property = createNode(SyntaxKind.PropertyDeclaration, fullStart);
property.decorators = decorators;
setModifiers(property, modifiers);
@@ -4808,7 +4840,7 @@ namespace ts {
}
// Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
- while (isModifier(token)) {
+ while (isModifierKind(token)) {
idToken = token;
// If the idToken is a class modifier (protected, private, public, and static), it is
// certain that we are starting to parse class member. This allows better error recovery
@@ -4878,7 +4910,7 @@ namespace ts {
if (!decorators) {
decorators = >[];
- decorators.pos = scanner.getStartPos();
+ decorators.pos = decoratorStart;
}
const decorator = createNode(SyntaxKind.Decorator, decoratorStart);
@@ -5018,8 +5050,8 @@ namespace ts {
// implements is a future reserved word so
// 'class implements' might mean either
// - class expression with omitted name, 'implements' starts heritage clause
- // - class with name 'implements'
- // 'isImplementsClause' helps to disambiguate between these two cases
+ // - class with name 'implements'
+ // 'isImplementsClause' helps to disambiguate between these two cases
return isIdentifier() && !isImplementsClause()
? parseIdentifier()
: undefined;
@@ -5278,16 +5310,17 @@ namespace ts {
}
function parseModuleSpecifier(): Expression {
- // We allow arbitrary expressions here, even though the grammar only allows string
- // literals. We check to ensure that it is only a string literal later in the grammar
- // walker.
- const result = parseExpression();
- // Ensure the string being required is in our 'identifier' table. This will ensure
- // that features like 'find refs' will look inside this file when search for its name.
- if (result.kind === SyntaxKind.StringLiteral) {
+ if (token === SyntaxKind.StringLiteral) {
+ const result = parseLiteralNode();
internIdentifier((result).text);
+ return result;
+ }
+ else {
+ // We allow arbitrary expressions here, even though the grammar only allows string
+ // literals. We check to ensure that it is only a string literal later in the grammar
+ // check pass.
+ return parseExpression();
}
- return result;
}
function parseNamespaceImport(): NamespaceImport {
@@ -5404,11 +5437,13 @@ namespace ts {
// reference comment.
while (true) {
const kind = triviaScanner.scan();
- if (kind === SyntaxKind.WhitespaceTrivia || kind === SyntaxKind.NewLineTrivia || kind === SyntaxKind.MultiLineCommentTrivia) {
- continue;
- }
if (kind !== SyntaxKind.SingleLineCommentTrivia) {
- break;
+ if (isTrivia(kind)) {
+ continue;
+ }
+ else {
+ break;
+ }
}
const range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() };
@@ -6162,7 +6197,7 @@ namespace ts {
if (sourceFile.statements.length === 0) {
// If we don't have any statements in the current source file, then there's no real
// way to incrementally parse. So just do a full parse instead.
- return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true);
+ return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true);
}
// Make sure we're not trying to incrementally update a source file more than once. Once
@@ -6226,7 +6261,7 @@ namespace ts {
// inconsistent tree. Setting the parents on the new tree should be very fast. We
// will immediately bail out of walking any subtrees when we can see that their parents
// are already correct.
- const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true);
+ const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true);
return result;
}
diff --git a/src/compiler/program.ts b/src/compiler/program.ts
index 08321da82e9..ed9f010c56a 100644
--- a/src/compiler/program.ts
+++ b/src/compiler/program.ts
@@ -14,10 +14,10 @@ namespace ts {
export const version = "1.8.0";
- export function findConfigFile(searchPath: string): string {
+ export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
let fileName = "tsconfig.json";
while (true) {
- if (sys.fileExists(fileName)) {
+ if (fileExists(fileName)) {
return fileName;
}
const parentPath = getDirectoryPath(searchPath);
@@ -42,24 +42,24 @@ namespace ts {
: compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
switch (moduleResolution) {
- case ModuleResolutionKind.NodeJs: return nodeModuleNameResolver(moduleName, containingFile, host);
+ case ModuleResolutionKind.NodeJs: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
case ModuleResolutionKind.Classic: return classicNameResolver(moduleName, containingFile, compilerOptions, host);
}
}
- export function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
+ 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(supportedJsExtensions, candidate, failedLookupLocations, host);
+ let resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName }, failedLookupLocations };
}
- resolvedFileName = loadNodeModuleFromDirectory(supportedJsExtensions, candidate, failedLookupLocations, host);
+ resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
@@ -122,12 +122,13 @@ namespace ts {
if (baseName !== "node_modules") {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
- let result = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, host);
+ // Load only typescript files irrespective of allowJs option if loading from node modules
+ let result = loadNodeModuleFromFile(supportedTypeScriptExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
}
- result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, host);
+ result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
}
@@ -162,10 +163,10 @@ namespace ts {
const failedLookupLocations: string[] = [];
let referencedSourceFile: string;
- const extensions = compilerOptions.allowNonTsExtensions ? supportedJsExtensions : supportedExtensions;
+ const supportedExtensions = getSupportedExtensions(compilerOptions);
while (true) {
searchName = normalizePath(combinePaths(searchPath, moduleName));
- referencedSourceFile = forEach(extensions, extension => {
+ 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
@@ -285,13 +286,13 @@ namespace ts {
}
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] {
- const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
+ let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
- diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
+ diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return sortAndDeduplicateDiagnostics(diagnostics);
@@ -335,10 +336,13 @@ namespace ts {
let classifiableNames: Map;
let skipDefaultLib = options.noLib;
+ const supportedExtensions = getSupportedExtensions(options);
const start = new Date().getTime();
host = host || createCompilerHost(options);
+ // Map storing if there is emit blocking diagnostics for given input
+ const hasEmitBlockingDiagnostics = createFileMap(getCanonicalFileName);
const currentDirectory = host.getCurrentDirectory();
const resolveModuleNamesWorker = host.resolveModuleNames
@@ -358,29 +362,26 @@ namespace ts {
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
- (oldOptions.jsx !== options.jsx)) {
+ (oldOptions.jsx !== options.jsx) ||
+ (oldOptions.allowJs !== options.allowJs)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
- forEach(rootNames, name => processRootFile(name, false));
+ forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// Do not process the default library if:
// - The '--noLib' flag is used.
// - A 'no-default-lib' reference comment is encountered in
// processing the root files.
if (!skipDefaultLib) {
- processRootFile(host.getDefaultLibFileName(options), true);
+ processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true);
}
}
- verifyCompilerOptions();
-
// unconditionally set oldProgram to undefined to prevent it from being captured in closure
oldProgram = undefined;
- programTime += new Date().getTime() - start;
-
program = {
getRootFileNames: () => rootNames,
getSourceFile,
@@ -394,7 +395,7 @@ namespace ts {
getTypeChecker,
getClassifiableNames,
getDiagnosticsProducingTypeChecker,
- getCommonSourceDirectory: () => commonSourceDirectory,
+ getCommonSourceDirectory,
emit,
getCurrentDirectory: () => currentDirectory,
getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(),
@@ -403,8 +404,32 @@ namespace ts {
getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(),
getFileProcessingDiagnostics: () => fileProcessingDiagnostics
};
+
+ verifyCompilerOptions();
+
+ programTime += new Date().getTime() - start;
+
return program;
+ function getCommonSourceDirectory() {
+ if (typeof commonSourceDirectory === "undefined") {
+ if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
+ // If a rootDir is specified and is valid use it as the commonSourceDirectory
+ commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
+ }
+ else {
+ commonSourceDirectory = computeCommonSourceDirectory(files);
+ }
+ if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
+ // Make sure directory path ends with directory separator so this string can directly
+ // used to replace with "" to get the relative path of the source file and the relative path doesn't
+ // start with / making it rooted path
+ commonSourceDirectory += directorySeparator;
+ }
+ }
+ return commonSourceDirectory;
+ }
+
function getClassifiableNames() {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
@@ -524,6 +549,7 @@ namespace ts {
getSourceFiles: program.getSourceFiles,
writeFile: writeFileCallback || (
(fileName, data, writeByteOrderMark, onError) => host.writeFile(fileName, data, writeByteOrderMark, onError)),
+ isEmitBlocked,
};
}
@@ -539,6 +565,10 @@ namespace ts {
return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken));
}
+ function isEmitBlocked(emitFileName: string): boolean {
+ return hasEmitBlockingDiagnostics.contains(toPath(emitFileName, currentDirectory, getCanonicalFileName));
+ }
+
function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult {
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
@@ -636,7 +666,12 @@ namespace ts {
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
- const checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken);
+ // For JavaScript files, we don't want to report the normal typescript semantic errors.
+ // Instead, we just report errors for using TypeScript-only constructs from within a
+ // JavaScript file.
+ const checkDiagnostics = isSourceFileJavaScript(sourceFile) ?
+ getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) :
+ typeChecker.getDiagnostics(sourceFile, cancellationToken);
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -644,6 +679,165 @@ namespace ts {
});
}
+ function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
+ return runWithCancellationToken(() => {
+ const diagnostics: Diagnostic[] = [];
+ walk(sourceFile);
+
+ return diagnostics;
+
+ function walk(node: Node): boolean {
+ if (!node) {
+ return false;
+ }
+
+ switch (node.kind) {
+ case SyntaxKind.ImportEqualsDeclaration:
+ 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;
+ case SyntaxKind.ClassDeclaration:
+ let classDeclaration = node;
+ if (checkModifiers(classDeclaration.modifiers) ||
+ checkTypeParameters(classDeclaration.typeParameters)) {
+ return true;
+ }
+ break;
+ case SyntaxKind.HeritageClause:
+ let heritageClause = node;
+ if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+ break;
+ case SyntaxKind.InterfaceDeclaration:
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
+ return true;
+ case SyntaxKind.ModuleDeclaration:
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
+ return true;
+ case SyntaxKind.TypeAliasDeclaration:
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
+ return true;
+ case SyntaxKind.MethodDeclaration:
+ case SyntaxKind.MethodSignature:
+ case SyntaxKind.Constructor:
+ case SyntaxKind.GetAccessor:
+ case SyntaxKind.SetAccessor:
+ case SyntaxKind.FunctionExpression:
+ case SyntaxKind.FunctionDeclaration:
+ case SyntaxKind.ArrowFunction:
+ case SyntaxKind.FunctionDeclaration:
+ const functionDeclaration = node;
+ if (checkModifiers(functionDeclaration.modifiers) ||
+ checkTypeParameters(functionDeclaration.typeParameters) ||
+ checkTypeAnnotation(functionDeclaration.type)) {
+ return true;
+ }
+ break;
+ case SyntaxKind.VariableStatement:
+ const variableStatement = node;
+ if (checkModifiers(variableStatement.modifiers)) {
+ return true;
+ }
+ break;
+ case SyntaxKind.VariableDeclaration:
+ const variableDeclaration = node;
+ if (checkTypeAnnotation(variableDeclaration.type)) {
+ return true;
+ }
+ break;
+ case SyntaxKind.CallExpression:
+ case SyntaxKind.NewExpression:
+ const expression = node;
+ if (expression.typeArguments && expression.typeArguments.length > 0) {
+ const start = expression.typeArguments.pos;
+ diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start,
+ Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+ break;
+ case SyntaxKind.Parameter:
+ const parameter = node;
+ if (parameter.modifiers) {
+ const start = parameter.modifiers.pos;
+ diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start,
+ Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+ if (parameter.questionToken) {
+ diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
+ return true;
+ }
+ if (parameter.type) {
+ diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+ break;
+ case SyntaxKind.PropertyDeclaration:
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.property_declarations_can_only_be_used_in_a_ts_file));
+ return true;
+ case SyntaxKind.EnumDeclaration:
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
+ return true;
+ case SyntaxKind.TypeAssertionExpression:
+ let typeAssertionExpression = node;
+ diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
+ return true;
+ case SyntaxKind.Decorator:
+ diagnostics.push(createDiagnosticForNode(node, Diagnostics.decorators_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+
+ return forEachChild(node, walk);
+ }
+
+ function checkTypeParameters(typeParameters: NodeArray): boolean {
+ if (typeParameters) {
+ const start = typeParameters.pos;
+ diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+ return false;
+ }
+
+ function checkTypeAnnotation(type: TypeNode): boolean {
+ if (type) {
+ diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file));
+ return true;
+ }
+
+ return false;
+ }
+
+ function checkModifiers(modifiers: ModifiersArray): boolean {
+ if (modifiers) {
+ for (const modifier of modifiers) {
+ switch (modifier.kind) {
+ case SyntaxKind.PublicKeyword:
+ case SyntaxKind.PrivateKeyword:
+ case SyntaxKind.ProtectedKeyword:
+ case SyntaxKind.DeclareKeyword:
+ diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
+ return true;
+
+ // These are all legal modifiers.
+ case SyntaxKind.StaticKeyword:
+ case SyntaxKind.ExportKeyword:
+ case SyntaxKind.ConstKeyword:
+ case SyntaxKind.DefaultKeyword:
+ case SyntaxKind.AbstractKeyword:
+ }
+ }
+ }
+
+ return false;
+ }
+ });
+ }
+
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
if (!isDeclarationFile(sourceFile)) {
@@ -693,7 +887,7 @@ namespace ts {
let imports: LiteralExpression[];
for (const node of file.statements) {
- collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false);
+ collect(node, /*allowRelativeModuleNames*/ true, /*collectOnlyRequireCalls*/ false);
}
file.imports = imports || emptyArray;
@@ -729,7 +923,7 @@ namespace ts {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
- collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls);
+ collect(node, /*allowRelativeModuleNames*/ false, collectOnlyRequireCalls);
});
}
break;
@@ -741,7 +935,7 @@ namespace ts {
(imports || (imports = [])).push((node).arguments[0]);
}
else {
- forEachChild(node, node => collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true));
+ forEachChild(node, node => collect(node, allowRelativeModuleNames, /*collectOnlyRequireCalls*/ true));
}
}
}
@@ -800,12 +994,12 @@ namespace ts {
}
// Get source file from normalized fileName
- function findSourceFile(fileName: string, normalizedAbsolutePath: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
- if (filesByName.contains(normalizedAbsolutePath)) {
- const file = filesByName.get(normalizedAbsolutePath);
+ function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
+ if (filesByName.contains(path)) {
+ const file = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
- if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== normalizedAbsolutePath) {
+ if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd);
}
@@ -823,18 +1017,18 @@ namespace ts {
}
});
- filesByName.set(normalizedAbsolutePath, file);
+ filesByName.set(path, file);
if (file) {
- file.path = normalizedAbsolutePath;
+ file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
- const existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath);
+ const existingFile = filesByNameIgnoreCase.get(path);
if (existingFile) {
reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
}
else {
- filesByNameIgnoreCase.set(normalizedAbsolutePath, file);
+ filesByNameIgnoreCase.set(path, file);
}
}
@@ -862,7 +1056,7 @@ namespace ts {
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
- processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end);
+ processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end);
});
}
@@ -880,9 +1074,11 @@ namespace ts {
const resolution = resolutions[i];
setResolvedModule(file, moduleNames[i], resolution);
if (resolution && !options.noResolve) {
- const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
+ const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
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)) {
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));
@@ -904,7 +1100,7 @@ namespace ts {
function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string {
let commonPathComponents: string[];
- forEach(files, sourceFile => {
+ const failed = forEach(files, sourceFile => {
// Each file contributes into common source file path
if (isDeclarationFile(sourceFile)) {
return;
@@ -920,10 +1116,10 @@ namespace ts {
}
for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
- if (commonPathComponents[i] !== sourcePathComponents[i]) {
+ if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
- programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
- return;
+ // Failed to find any common path component
+ return true;
}
// New common path found that is 0 -> i-1
@@ -938,6 +1134,11 @@ namespace ts {
}
});
+ // A common path can not be found when paths span multiple drives on windows, for example
+ if (failed) {
+ return "";
+ }
+
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
@@ -990,16 +1191,15 @@ namespace ts {
if (options.mapRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
- if (options.sourceRoot) {
- programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap"));
- }
}
-
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));
}
+ if (options.sourceRoot) {
+ programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources"));
+ }
}
if (options.out && options.outFile) {
@@ -1011,10 +1211,9 @@ namespace ts {
if (options.mapRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
- if (options.sourceRoot) {
+ if (options.sourceRoot && !options.inlineSourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
- return;
}
const languageVersion = options.target || ScriptTarget.ES3;
@@ -1054,20 +1253,12 @@ namespace ts {
options.sourceRoot || // there is --sourceRoot specified
options.mapRoot) { // there is --mapRoot specified
- if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
- // If a rootDir is specified and is valid use it as the commonSourceDirectory
- commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
- }
- else {
- // Compute the commonSourceDirectory from the input files
- commonSourceDirectory = computeCommonSourceDirectory(files);
- }
+ // Precalculate and cache the common source directory
+ const dir = getCommonSourceDirectory();
- if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
- // Make sure directory path ends with directory separator so this string can directly
- // used to replace with "" to get the relative path of the source file and the relative path doesn't
- // start with / making it rooted path
- commonSourceDirectory += directorySeparator;
+ // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
+ if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) {
+ programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
}
}
@@ -1088,11 +1279,49 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
+ else if (options.allowJs && options.declaration) {
+ programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"));
+ }
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
+
+ // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
+ if (!options.noEmit) {
+ const emitHost = getEmitHost();
+ const emitFilesSeen = createFileMap(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined);
+ forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => {
+ verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen);
+ verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen);
+ });
+ }
+
+ // Verify that all the emit files are unique and don't overwrite input files
+ function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap) {
+ if (emitFileName) {
+ const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName);
+ // Report error if the output overwrites input file
+ if (filesByName.contains(emitFilePath)) {
+ createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file);
+ }
+
+ // Report error if multiple files write into same file
+ if (emitFilesSeen.contains(emitFilePath)) {
+ // Already seen the same emit file - report error
+ createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files);
+ }
+ else {
+ emitFilesSeen.set(emitFilePath, true);
+ }
+ }
+ }
+ }
+
+ function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) {
+ hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true);
+ programDiagnostics.add(createCompilerDiagnostic(message, emitFileName));
}
}
}
diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts
index 9703ef8517b..022d63fbe9d 100644
--- a/src/compiler/scanner.ts
+++ b/src/compiler/scanner.ts
@@ -425,6 +425,12 @@ namespace ts {
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
+ // Using ! with a greater than test is a fast way of testing the following conditions:
+ // pos === undefined || pos === null || isNaN(pos) || pos < 0;
+ if (!(pos >= 0)) {
+ return pos;
+ }
+
// Keep in sync with couldStartTrivia
while (true) {
const ch = text.charCodeAt(pos);
@@ -567,12 +573,12 @@ namespace ts {
}
/**
- * Extract comments from text prefixing the token closest following `pos`.
+ * Extract comments from text prefixing the token closest following `pos`.
* The return value is an array containing a TextRange for each comment.
* Single-line comment ranges include the beginning '//' characters but not the ending line break.
* Multi - line comment ranges include the beginning '/* and ending '/' characters.
* The return value is undefined if no comments were found.
- * @param trailing
+ * @param trailing
* If false, whitespace is skipped until the first line break and comments between that location
* and the next token are returned.
* If true, comments occurring between the given position and the next line break are returned.
@@ -1634,11 +1640,11 @@ namespace ts {
}
function lookAhead(callback: () => T): T {
- return speculationHelper(callback, /*isLookahead:*/ true);
+ return speculationHelper(callback, /*isLookahead*/ true);
}
function tryScan(callback: () => T): T {
- return speculationHelper(callback, /*isLookahead:*/ false);
+ return speculationHelper(callback, /*isLookahead*/ false);
}
function setText(newText: string, start: number, length: number) {
diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts
new file mode 100644
index 00000000000..d98dc233c16
--- /dev/null
+++ b/src/compiler/sourcemap.ts
@@ -0,0 +1,332 @@
+///
+
+/* @internal */
+namespace ts {
+ export interface SourceMapWriter {
+ getSourceMapData(): SourceMapData;
+ setSourceFile(sourceFile: SourceFile): void;
+ emitPos(pos: number): void;
+ emitStart(range: TextRange): void;
+ emitEnd(range: TextRange): void;
+ getText(): string;
+ getSourceMappingURL(): string;
+ initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void;
+ reset(): void;
+ }
+
+ const nop = <(...args: any[]) => any>Function.prototype;
+ let nullSourceMapWriter: SourceMapWriter;
+
+ export function getNullSourceMapWriter(): SourceMapWriter {
+ if (nullSourceMapWriter === undefined) {
+ nullSourceMapWriter = {
+ getSourceMapData(): SourceMapData { return undefined; },
+ setSourceFile(sourceFile: SourceFile): void { },
+ emitStart(range: TextRange): void { },
+ emitEnd(range: TextRange): void { },
+ emitPos(pos: number): void { },
+ getText(): string { return undefined; },
+ getSourceMappingURL(): string { return undefined; },
+ initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void { },
+ reset(): void { },
+ };
+ }
+
+ return nullSourceMapWriter;
+ }
+
+ export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
+ const compilerOptions = host.getCompilerOptions();
+ let currentSourceFile: SourceFile;
+ let sourceMapDir: string; // The directory in which sourcemap will be
+
+ // Current source map file and its index in the sources list
+ let sourceMapSourceIndex: number;
+
+ // Last recorded and encoded spans
+ let lastRecordedSourceMapSpan: SourceMapSpan;
+ let lastEncodedSourceMapSpan: SourceMapSpan;
+ let lastEncodedNameIndex: number;
+
+ // Source map data
+ let sourceMapData: SourceMapData;
+
+ return {
+ getSourceMapData: () => sourceMapData,
+ setSourceFile,
+ emitPos,
+ emitStart,
+ emitEnd,
+ getText,
+ getSourceMappingURL,
+ initialize,
+ reset,
+ };
+
+ function initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
+ if (sourceMapData) {
+ reset();
+ }
+
+ currentSourceFile = undefined;
+
+ // Current source map file and its index in the sources list
+ sourceMapSourceIndex = -1;
+
+ // Last recorded and encoded spans
+ lastRecordedSourceMapSpan = undefined;
+ lastEncodedSourceMapSpan = {
+ emittedLine: 1,
+ emittedColumn: 1,
+ sourceLine: 1,
+ sourceColumn: 1,
+ sourceIndex: 0
+ };
+ lastEncodedNameIndex = 0;
+
+ // Initialize source map data
+ sourceMapData = {
+ sourceMapFilePath: sourceMapFilePath,
+ jsSourceMappingURL: !compilerOptions.inlineSourceMap ? getBaseFileName(normalizeSlashes(sourceMapFilePath)) : undefined,
+ sourceMapFile: getBaseFileName(normalizeSlashes(filePath)),
+ sourceMapSourceRoot: compilerOptions.sourceRoot || "",
+ sourceMapSources: [],
+ inputSourceFileNames: [],
+ sourceMapNames: [],
+ sourceMapMappings: "",
+ sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined,
+ sourceMapDecodedMappings: []
+ };
+
+ // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
+ // relative paths of the sources list in the sourcemap
+ sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);
+ if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== CharacterCodes.slash) {
+ sourceMapData.sourceMapSourceRoot += directorySeparator;
+ }
+
+ if (compilerOptions.mapRoot) {
+ sourceMapDir = normalizeSlashes(compilerOptions.mapRoot);
+ if (!isBundledEmit) { // emitting single module file
+ Debug.assert(sourceFiles.length === 1);
+ // For modules or multiple emit files the mapRoot will have directory structure like the sources
+ // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
+ sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir));
+ }
+
+ if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) {
+ // The relative paths are relative to the common directory
+ sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
+ sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl(
+ getDirectoryPath(normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
+ combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
+ host.getCurrentDirectory(),
+ host.getCanonicalFileName,
+ /*isAbsolutePathAnUrl*/ true);
+ }
+ else {
+ sourceMapData.jsSourceMappingURL = combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);
+ }
+ }
+ else {
+ sourceMapDir = getDirectoryPath(normalizePath(filePath));
+ }
+ }
+
+ function reset() {
+ currentSourceFile = undefined;
+ sourceMapDir = undefined;
+ sourceMapSourceIndex = undefined;
+ lastRecordedSourceMapSpan = undefined;
+ lastEncodedSourceMapSpan = undefined;
+ lastEncodedNameIndex = undefined;
+ sourceMapData = undefined;
+ }
+
+ // Encoding for sourcemap span
+ function encodeLastRecordedSourceMapSpan() {
+ if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {
+ return;
+ }
+
+ let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
+ // Line/Comma delimiters
+ if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
+ // Emit comma to separate the entry
+ if (sourceMapData.sourceMapMappings) {
+ sourceMapData.sourceMapMappings += ",";
+ }
+ }
+ else {
+ // Emit line delimiters
+ for (let encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
+ sourceMapData.sourceMapMappings += ";";
+ }
+ prevEncodedEmittedColumn = 1;
+ }
+
+ // 1. Relative Column 0 based
+ sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);
+
+ // 2. Relative sourceIndex
+ sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);
+
+ // 3. Relative sourceLine 0 based
+ sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);
+
+ // 4. Relative sourceColumn 0 based
+ sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);
+
+ // 5. Relative namePosition 0 based
+ if (lastRecordedSourceMapSpan.nameIndex >= 0) {
+ sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);
+ lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;
+ }
+
+ lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;
+ sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);
+ }
+
+ function emitPos(pos: number) {
+ if (pos === -1) {
+ return;
+ }
+
+ const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
+
+ // Convert the location to be one-based.
+ sourceLinePos.line++;
+ sourceLinePos.character++;
+
+ const emittedLine = writer.getLine();
+ const emittedColumn = writer.getColumn();
+
+ // If this location wasn't recorded or the location in source is going backwards, record the span
+ if (!lastRecordedSourceMapSpan ||
+ lastRecordedSourceMapSpan.emittedLine !== emittedLine ||
+ lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||
+ (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&
+ (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||
+ (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {
+
+ // Encode the last recordedSpan before assigning new
+ encodeLastRecordedSourceMapSpan();
+
+ // New span
+ lastRecordedSourceMapSpan = {
+ emittedLine: emittedLine,
+ emittedColumn: emittedColumn,
+ sourceLine: sourceLinePos.line,
+ sourceColumn: sourceLinePos.character,
+ sourceIndex: sourceMapSourceIndex
+ };
+ }
+ else {
+ // Take the new pos instead since there is no change in emittedLine and column since last location
+ lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;
+ lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;
+ lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;
+ }
+ }
+
+ function emitStart(range: TextRange) {
+ const rangeHasDecorators = !!(range as Node).decorators;
+ emitPos(range.pos !== -1 ? skipTrivia(currentSourceFile.text, rangeHasDecorators ? (range as Node).decorators.end : range.pos) : -1);
+ }
+
+ function emitEnd(range: TextRange) {
+ emitPos(range.end);
+ }
+
+ function setSourceFile(sourceFile: SourceFile) {
+ currentSourceFile = sourceFile;
+
+ // Add the file to tsFilePaths
+ // If sourceroot option: Use the relative path corresponding to the common directory path
+ // otherwise source locations relative to map file location
+ const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
+
+ const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath,
+ currentSourceFile.fileName,
+ host.getCurrentDirectory(),
+ host.getCanonicalFileName,
+ /*isAbsolutePathAnUrl*/ true);
+
+ sourceMapSourceIndex = indexOf(sourceMapData.sourceMapSources, source);
+ if (sourceMapSourceIndex === -1) {
+ sourceMapSourceIndex = sourceMapData.sourceMapSources.length;
+ sourceMapData.sourceMapSources.push(source);
+
+ // The one that can be used from program to get the actual source file
+ sourceMapData.inputSourceFileNames.push(sourceFile.fileName);
+
+ if (compilerOptions.inlineSources) {
+ sourceMapData.sourceMapSourcesContent.push(sourceFile.text);
+ }
+ }
+ }
+
+ function getText() {
+ encodeLastRecordedSourceMapSpan();
+
+ return stringify({
+ version: 3,
+ file: sourceMapData.sourceMapFile,
+ sourceRoot: sourceMapData.sourceMapSourceRoot,
+ sources: sourceMapData.sourceMapSources,
+ names: sourceMapData.sourceMapNames,
+ mappings: sourceMapData.sourceMapMappings,
+ sourcesContent: sourceMapData.sourceMapSourcesContent,
+ });
+ }
+
+ function getSourceMappingURL() {
+ if (compilerOptions.inlineSourceMap) {
+ // Encode the sourceMap into the sourceMap url
+ const base64SourceMapText = convertToBase64(getText());
+ return sourceMapData.jsSourceMappingURL = `data:application/json;base64,${base64SourceMapText}`;
+ }
+ else {
+ return sourceMapData.jsSourceMappingURL;
+ }
+ }
+ }
+
+ const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ function base64FormatEncode(inValue: number) {
+ if (inValue < 64) {
+ return base64Chars.charAt(inValue);
+ }
+
+ throw TypeError(inValue + ": not a 64 based value");
+ }
+
+ function base64VLQFormatEncode(inValue: number) {
+ // Add a new least significant bit that has the sign of the value.
+ // if negative number the least significant bit that gets added to the number has value 1
+ // else least significant bit value that gets added is 0
+ // eg. -1 changes to binary : 01 [1] => 3
+ // +1 changes to binary : 01 [0] => 2
+ if (inValue < 0) {
+ inValue = ((-inValue) << 1) + 1;
+ }
+ else {
+ inValue = inValue << 1;
+ }
+
+ // Encode 5 bits at a time starting from least significant bits
+ let encodedStr = "";
+ do {
+ let currentDigit = inValue & 31; // 11111
+ inValue = inValue >> 5;
+ if (inValue > 0) {
+ // There are still more digits to decode, set the msb (6th bit)
+ currentDigit = currentDigit | 32;
+ }
+ encodedStr = encodedStr + base64FormatEncode(currentDigit);
+ } while (inValue > 0);
+
+ return encodedStr;
+ }
+}
\ No newline at end of file
diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts
index 3a90ca42fa1..cd7580119b5 100644
--- a/src/compiler/sys.ts
+++ b/src/compiler/sys.ts
@@ -47,6 +47,21 @@ namespace ts {
constructor(o: any);
}
+ declare var ChakraHost: {
+ args: string[];
+ currentDirectory: string;
+ executingFile: string;
+ echo(s: string): void;
+ quit(exitCode?: number): void;
+ fileExists(path: string): boolean;
+ directoryExists(path: string): boolean;
+ createDirectory(path: string): void;
+ resolvePath(path: string): string;
+ readFile(path: string): string;
+ writeFile(path: string, contents: string): void;
+ readDirectory(path: string, extension?: string, exclude?: string[]): string[];
+ };
+
export var sys: System = (function () {
function getWScriptSystem(): System {
@@ -194,6 +209,7 @@ namespace ts {
}
};
}
+
function getNodeSystem(): System {
const _fs = require("fs");
const _path = require("path");
@@ -281,7 +297,7 @@ namespace ts {
// REVIEW: for now this implementation uses polling.
// The advantage of polling is that it works reliably
// on all os and with network mounted files.
- // For 90 referenced files, the average time to detect
+ // For 90 referenced files, the average time to detect
// changes is 2*msInterval (by default 5 seconds).
// The overhead of this is .04 percent (1/2500) with
// average pause of < 1 millisecond (and max
@@ -406,7 +422,7 @@ namespace ts {
};
},
watchDirectory: (path, callback, recursive) => {
- // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
+ // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
return _fs.watch(
path,
@@ -454,6 +470,37 @@ namespace ts {
}
};
}
+
+ function getChakraSystem(): System {
+
+ return {
+ newLine: "\r\n",
+ args: ChakraHost.args,
+ useCaseSensitiveFileNames: false,
+ write: ChakraHost.echo,
+ readFile(path: string, encoding?: string) {
+ // encoding is automatically handled by the implementation in ChakraHost
+ return ChakraHost.readFile(path);
+ },
+ writeFile(path: string, data: string, writeByteOrderMark?: boolean) {
+ // If a BOM is required, emit one
+ if (writeByteOrderMark) {
+ data = "\uFEFF" + data;
+ }
+
+ ChakraHost.writeFile(path, data);
+ },
+ resolvePath: ChakraHost.resolvePath,
+ fileExists: ChakraHost.fileExists,
+ directoryExists: ChakraHost.directoryExists,
+ createDirectory: ChakraHost.createDirectory,
+ getExecutingFilePath: () => ChakraHost.executingFile,
+ getCurrentDirectory: () => ChakraHost.currentDirectory,
+ readDirectory: ChakraHost.readDirectory,
+ exit: ChakraHost.quit,
+ };
+ }
+
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
@@ -462,8 +509,13 @@ namespace ts {
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
+ else if (typeof ChakraHost !== "undefined") {
+ return getChakraSystem();
+ }
else {
return undefined; // Unsupported host
}
})();
}
+
+
diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts
index f560a15dfb9..d064ec54c9c 100644
--- a/src/compiler/tsc.ts
+++ b/src/compiler/tsc.ts
@@ -280,7 +280,7 @@ namespace ts {
}
if (commandLine.options.version) {
- reportDiagnostic(createCompilerDiagnostic(Diagnostics.Version_0, ts.version), /* compilerHost */ undefined);
+ printVersion();
return sys.exit(ExitStatus.Success);
}
@@ -295,15 +295,30 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
- configFileName = normalizePath(combinePaths(commandLine.options.project, "tsconfig.json"));
if (commandLine.fileNames.length !== 0) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
+
+ const fileOrDirectory = normalizePath(commandLine.options.project);
+ if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) {
+ configFileName = combinePaths(fileOrDirectory, "tsconfig.json");
+ if (!sys.fileExists(configFileName)) {
+ reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
+ return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
+ }
+ }
+ else {
+ configFileName = fileOrDirectory;
+ if (!sys.fileExists(configFileName)) {
+ reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
+ return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
+ }
+ }
}
else if (commandLine.fileNames.length === 0 && isJSONSupported()) {
const searchPath = normalizePath(sys.getCurrentDirectory());
- configFileName = findConfigFile(searchPath);
+ configFileName = findConfigFile(searchPath, sys.fileExists);
}
if (commandLine.fileNames.length === 0 && !configFileName) {
@@ -360,7 +375,7 @@ namespace ts {
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
- const configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName));
+ const configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName), commandLine.options);
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -376,7 +391,7 @@ namespace ts {
if (configFileName) {
const configParseResult = parseConfigFile();
rootFileNames = configParseResult.fileNames;
- compilerOptions = extend(commandLine.options, configParseResult.options);
+ compilerOptions = configParseResult.options;
}
else {
rootFileNames = commandLine.fileNames;
@@ -469,7 +484,7 @@ namespace ts {
}
function watchedDirectoryChanged(fileName: string) {
- if (fileName && !ts.isSupportedSourceFileName(fileName)) {
+ if (fileName && !ts.isSupportedSourceFileName(fileName, commandLine.options)) {
return;
}
diff --git a/src/compiler/types.ts b/src/compiler/types.ts
index 8b0027c1377..9411437c981 100644
--- a/src/compiler/types.ts
+++ b/src/compiler/types.ts
@@ -204,6 +204,8 @@ namespace ts {
UnionType,
IntersectionType,
ParenthesizedType,
+ ThisType,
+ StringLiteralType,
// Binding patterns
ObjectBindingPattern,
ArrayBindingPattern,
@@ -348,8 +350,8 @@ namespace ts {
LastKeyword = OfKeyword,
FirstFutureReservedWord = ImplementsKeyword,
LastFutureReservedWord = YieldKeyword,
- FirstTypeNode = TypeReference,
- LastTypeNode = ParenthesizedType,
+ FirstTypeNode = TypePredicate,
+ LastTypeNode = StringLiteralType,
FirstPunctuation = OpenBraceToken,
LastPunctuation = CaretEqualsToken,
FirstToken = Unknown,
@@ -437,12 +439,16 @@ namespace ts {
export const enum JsxFlags {
None = 0,
+ /** An element from a named property of the JSX.IntrinsicElements interface */
IntrinsicNamedElement = 1 << 0,
+ /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 1 << 1,
- ClassElement = 1 << 2,
- UnknownElement = 1 << 3,
+ /** An element backed by a class, class-like, or function value */
+ ValueElement = 1 << 2,
+ /** Element resolution failed */
+ UnknownElement = 1 << 4,
- IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement
+ IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement,
}
@@ -474,15 +480,29 @@ namespace ts {
hasTrailingComma?: boolean;
}
- export interface ModifiersArray extends NodeArray {
+ export interface ModifiersArray extends NodeArray {
flags: number;
}
+ // @kind(SyntaxKind.AbstractKeyword)
+ // @kind(SyntaxKind.AsyncKeyword)
+ // @kind(SyntaxKind.ConstKeyword)
+ // @kind(SyntaxKind.DeclareKeyword)
+ // @kind(SyntaxKind.DefaultKeyword)
+ // @kind(SyntaxKind.ExportKeyword)
+ // @kind(SyntaxKind.PublicKeyword)
+ // @kind(SyntaxKind.PrivateKeyword)
+ // @kind(SyntaxKind.ProtectedKeyword)
+ // @kind(SyntaxKind.StaticKeyword)
+ export interface Modifier extends Node { }
+
+ // @kind(SyntaxKind.Identifier)
export interface Identifier extends PrimaryExpression {
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
}
+ // @kind(SyntaxKind.QualifiedName)
export interface QualifiedName extends Node {
// Must have same layout as PropertyAccess
left: EntityName;
@@ -492,6 +512,7 @@ namespace ts {
export type EntityName = Identifier | QualifiedName;
export type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
+
export type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
export interface Declaration extends Node {
@@ -499,14 +520,21 @@ namespace ts {
name?: DeclarationName;
}
+ export interface DeclarationStatement extends Declaration, Statement {
+ name?: Identifier;
+ }
+
+ // @kind(SyntaxKind.ComputedPropertyName)
export interface ComputedPropertyName extends Node {
expression: Expression;
}
+ // @kind(SyntaxKind.Decorator)
export interface Decorator extends Node {
expression: LeftHandSideExpression;
}
+ // @kind(SyntaxKind.TypeParameter)
export interface TypeParameterDeclaration extends Declaration {
name: Identifier;
constraint?: TypeNode;
@@ -516,12 +544,19 @@ namespace ts {
}
export interface SignatureDeclaration extends Declaration {
+ name?: PropertyName;
typeParameters?: NodeArray;
parameters: NodeArray;
type?: TypeNode;
}
- // SyntaxKind.VariableDeclaration
+ // @kind(SyntaxKind.CallSignature)
+ export interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { }
+
+ // @kind(SyntaxKind.ConstructSignature)
+ export interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { }
+
+ // @kind(SyntaxKind.VariableDeclaration)
export interface VariableDeclaration extends Declaration {
parent?: VariableDeclarationList;
name: Identifier | BindingPattern; // Declared variable name
@@ -529,11 +564,12 @@ namespace ts {
initializer?: Expression; // Optional initializer
}
+ // @kind(SyntaxKind.VariableDeclarationList)
export interface VariableDeclarationList extends Node {
declarations: NodeArray;
}
- // SyntaxKind.Parameter
+ // @kind(SyntaxKind.Parameter)
export interface ParameterDeclaration extends Declaration {
dotDotDotToken?: Node; // Present on rest parameter
name: Identifier | BindingPattern; // Declared parameter name
@@ -542,7 +578,7 @@ namespace ts {
initializer?: Expression; // Optional initializer
}
- // SyntaxKind.BindingElement
+ // @kind(SyntaxKind.BindingElement)
export interface BindingElement extends Declaration {
propertyName?: PropertyName; // Binding property name (in object binding pattern)
dotDotDotToken?: Node; // Present on rest binding element
@@ -550,27 +586,36 @@ namespace ts {
initializer?: Expression; // Optional initializer
}
- // SyntaxKind.Property
- export interface PropertyDeclaration extends Declaration, ClassElement {
- name: DeclarationName; // Declared property name
+ // @kind(SyntaxKind.PropertySignature)
+ export interface PropertySignature extends TypeElement {
+ name: PropertyName; // Declared property name
questionToken?: Node; // Present on optional property
type?: TypeNode; // Optional type annotation
initializer?: Expression; // Optional initializer
}
- export interface ObjectLiteralElement extends Declaration {
- _objectLiteralBrandBrand: any;
+ // @kind(SyntaxKind.PropertyDeclaration)
+ export interface PropertyDeclaration extends ClassElement {
+ questionToken?: Node; // Present for use with reporting a grammar error
+ name: PropertyName;
+ type?: TypeNode;
+ initializer?: Expression; // Optional initializer
}
- // SyntaxKind.PropertyAssignment
+ export interface ObjectLiteralElement extends Declaration {
+ _objectLiteralBrandBrand: any;
+ name?: PropertyName;
+ }
+
+ // @kind(SyntaxKind.PropertyAssignment)
export interface PropertyAssignment extends ObjectLiteralElement {
_propertyAssignmentBrand: any;
- name: DeclarationName;
+ name: PropertyName;
questionToken?: Node;
initializer: Expression;
}
- // SyntaxKind.ShorthandPropertyAssignment
+ // @kind(SyntaxKind.ShorthandPropertyAssignment)
export interface ShorthandPropertyAssignment extends ObjectLiteralElement {
name: Identifier;
questionToken?: Node;
@@ -596,10 +641,20 @@ namespace ts {
initializer?: Expression;
}
+ export interface PropertyLikeDeclaration extends Declaration {
+ name: PropertyName;
+ }
+
export interface BindingPattern extends Node {
elements: NodeArray;
}
+ // @kind(SyntaxKind.ObjectBindingPattern)
+ export interface ObjectBindingPattern extends BindingPattern { }
+
+ // @kind(SyntaxKind.ArrayBindingPattern)
+ export interface ArrayBindingPattern extends BindingPattern { }
+
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
@@ -616,9 +671,15 @@ namespace ts {
body?: Block | Expression;
}
- export interface FunctionDeclaration extends FunctionLikeDeclaration, Statement {
+ // @kind(SyntaxKind.FunctionDeclaration)
+ export interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement {
name?: Identifier;
- body?: Block;
+ body?: FunctionBody;
+ }
+
+ // @kind(SyntaxKind.MethodSignature)
+ export interface MethodSignature extends SignatureDeclaration, TypeElement {
+ name: PropertyName;
}
// Note that a MethodDeclaration is considered both a ClassElement and an ObjectLiteralElement.
@@ -630,15 +691,19 @@ namespace ts {
// Because of this, it may be necessary to determine what sort of MethodDeclaration you have
// at later stages of the compiler pipeline. In that case, you can either check the parent kind
// of the method, or use helpers like isObjectLiteralMethodDeclaration
+ // @kind(SyntaxKind.MethodDeclaration)
export interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
- body?: Block;
+ name: PropertyName;
+ body?: FunctionBody;
}
+ // @kind(SyntaxKind.Constructor)
export interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement {
- body?: Block;
+ body?: FunctionBody;
}
// For when we encounter a semicolon in a class declaration. ES6 allows these as class elements.
+ // @kind(SyntaxKind.SemicolonClassElement)
export interface SemicolonClassElement extends ClassElement {
_semicolonClassElementBrand: any;
}
@@ -647,13 +712,28 @@ namespace ts {
// ClassElement and an ObjectLiteralElement.
export interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
_accessorDeclarationBrand: any;
- body: Block;
+ name: PropertyName;
+ body: FunctionBody;
}
- export interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement {
+ // @kind(SyntaxKind.GetAccessor)
+ export interface GetAccessorDeclaration extends AccessorDeclaration { }
+
+ // @kind(SyntaxKind.SetAccessor)
+ export interface SetAccessorDeclaration extends AccessorDeclaration { }
+
+ // @kind(SyntaxKind.IndexSignature)
+ export interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement {
_indexSignatureDeclarationBrand: any;
}
+ // @kind(SyntaxKind.AnyKeyword)
+ // @kind(SyntaxKind.NumberKeyword)
+ // @kind(SyntaxKind.BooleanKeyword)
+ // @kind(SyntaxKind.StringKeyword)
+ // @kind(SyntaxKind.SymbolKeyword)
+ // @kind(SyntaxKind.VoidKeyword)
+ // @kind(SyntaxKind.ThisType)
export interface TypeNode extends Node {
_typeNodeBrand: any;
}
@@ -662,29 +742,41 @@ namespace ts {
_functionOrConstructorTypeNodeBrand: any;
}
+ // @kind(SyntaxKind.FunctionType)
+ export interface FunctionTypeNode extends FunctionOrConstructorTypeNode { }
+
+ // @kind(SyntaxKind.ConstructorType)
+ export interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { }
+
+ // @kind(SyntaxKind.TypeReference)
export interface TypeReferenceNode extends TypeNode {
typeName: EntityName;
typeArguments?: NodeArray;
}
+ // @kind(SyntaxKind.TypePredicate)
export interface TypePredicateNode extends TypeNode {
parameterName: Identifier;
type: TypeNode;
}
+ // @kind(SyntaxKind.TypeQuery)
export interface TypeQueryNode extends TypeNode {
exprName: EntityName;
}
// A TypeLiteral is the declaration node for an anonymous symbol.
+ // @kind(SyntaxKind.TypeLiteral)
export interface TypeLiteralNode extends TypeNode, Declaration {
- members: NodeArray;
+ members: NodeArray;
}
+ // @kind(SyntaxKind.ArrayType)
export interface ArrayTypeNode extends TypeNode {
elementType: TypeNode;
}
+ // @kind(SyntaxKind.TupleType)
export interface TupleTypeNode extends TypeNode {
elementTypes: NodeArray;
}
@@ -693,17 +785,24 @@ namespace ts {
types: NodeArray;
}
+ // @kind(SyntaxKind.UnionType)
export interface UnionTypeNode extends UnionOrIntersectionTypeNode { }
+ // @kind(SyntaxKind.IntersectionType)
export interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { }
+ // @kind(SyntaxKind.ParenthesizedType)
export interface ParenthesizedTypeNode extends TypeNode {
type: TypeNode;
}
- // Note that a StringLiteral AST node is both an Expression and a TypeNode. The latter is
- // because string literals can appear in type annotations as well.
- export interface StringLiteral extends LiteralExpression, TypeNode {
+ // @kind(SyntaxKind.StringLiteralType)
+ export interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode {
+ _stringLiteralTypeBrand: any;
+ }
+
+ // @kind(SyntaxKind.StringLiteral)
+ export interface StringLiteral extends LiteralExpression {
_stringLiteralBrand: any;
}
@@ -719,6 +818,9 @@ namespace ts {
contextualType?: Type; // Used to temporarily assign a contextual type during overload resolution
}
+ // @kind(SyntaxKind.OmittedExpression)
+ export interface OmittedExpression extends Expression { }
+
export interface UnaryExpression extends Expression {
_unaryExpressionBrand: any;
}
@@ -727,11 +829,13 @@ namespace ts {
_incrementExpressionBrand: any;
}
+ // @kind(SyntaxKind.PrefixUnaryExpression)
export interface PrefixUnaryExpression extends IncrementExpression {
operator: SyntaxKind;
operand: UnaryExpression;
}
+ // @kind(SyntaxKind.PostfixUnaryExpression)
export interface PostfixUnaryExpression extends IncrementExpression {
operand: LeftHandSideExpression;
operator: SyntaxKind;
@@ -749,31 +853,42 @@ namespace ts {
_memberExpressionBrand: any;
}
+ // @kind(SyntaxKind.TrueKeyword)
+ // @kind(SyntaxKind.FalseKeyword)
+ // @kind(SyntaxKind.NullKeyword)
+ // @kind(SyntaxKind.ThisKeyword)
+ // @kind(SyntaxKind.SuperKeyword)
export interface PrimaryExpression extends MemberExpression {
_primaryExpressionBrand: any;
}
+ // @kind(SyntaxKind.DeleteExpression)
export interface DeleteExpression extends UnaryExpression {
expression: UnaryExpression;
}
+ // @kind(SyntaxKind.TypeOfExpression)
export interface TypeOfExpression extends UnaryExpression {
expression: UnaryExpression;
}
+ // @kind(SyntaxKind.VoidExpression)
export interface VoidExpression extends UnaryExpression {
expression: UnaryExpression;
}
+ // @kind(SyntaxKind.AwaitExpression)
export interface AwaitExpression extends UnaryExpression {
expression: UnaryExpression;
}
+ // @kind(SyntaxKind.YieldExpression)
export interface YieldExpression extends Expression {
asteriskToken?: Node;
expression?: Expression;
}
+ // @kind(SyntaxKind.BinaryExpression)
// Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files
export interface BinaryExpression extends Expression, Declaration {
left: Expression;
@@ -781,6 +896,7 @@ namespace ts {
right: Expression;
}
+ // @kind(SyntaxKind.ConditionalExpression)
export interface ConditionalExpression extends Expression {
condition: Expression;
questionToken: Node;
@@ -789,77 +905,109 @@ namespace ts {
whenFalse: Expression;
}
+ export type FunctionBody = Block;
+ export type ConciseBody = FunctionBody | Expression;
+
+ // @kind(SyntaxKind.FunctionExpression)
export interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration {
name?: Identifier;
- body: Block | Expression; // Required, whereas the member inherited from FunctionDeclaration is optional
+ body: FunctionBody; // Required, whereas the member inherited from FunctionDeclaration is optional
}
+ // @kind(SyntaxKind.ArrowFunction)
export interface ArrowFunction extends Expression, FunctionLikeDeclaration {
equalsGreaterThanToken: Node;
+ body: ConciseBody;
}
- // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
- // or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
- // For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
- export interface LiteralExpression extends PrimaryExpression {
+ export interface LiteralLikeNode extends Node {
text: string;
isUnterminated?: boolean;
hasExtendedUnicodeEscape?: boolean;
}
+ // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
+ // or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
+ // For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
+ // @kind(SyntaxKind.NumericLiteral)
+ // @kind(SyntaxKind.RegularExpressionLiteral)
+ // @kind(SyntaxKind.NoSubstitutionTemplateLiteral)
+ export interface LiteralExpression extends LiteralLikeNode, PrimaryExpression {
+ _literalExpressionBrand: any;
+ }
+
+ // @kind(SyntaxKind.TemplateHead)
+ // @kind(SyntaxKind.TemplateMiddle)
+ // @kind(SyntaxKind.TemplateTail)
+ export interface TemplateLiteralFragment extends LiteralLikeNode {
+ _templateLiteralFragmentBrand: any;
+ }
+
+ // @kind(SyntaxKind.TemplateExpression)
export interface TemplateExpression extends PrimaryExpression {
- head: LiteralExpression;
+ head: TemplateLiteralFragment;
templateSpans: NodeArray;
}
// Each of these corresponds to a substitution expression and a template literal, in that order.
// The template literal must have kind TemplateMiddleLiteral or TemplateTailLiteral.
+ // @kind(SyntaxKind.TemplateSpan)
export interface TemplateSpan extends Node {
expression: Expression;
- literal: LiteralExpression;
+ literal: TemplateLiteralFragment;
}
+ // @kind(SyntaxKind.ParenthesizedExpression)
export interface ParenthesizedExpression extends PrimaryExpression {
expression: Expression;
}
+ // @kind(SyntaxKind.ArrayLiteralExpression)
export interface ArrayLiteralExpression extends PrimaryExpression {
elements: NodeArray;
}
+ // @kind(SyntaxKind.SpreadElementExpression)
export interface SpreadElementExpression extends Expression {
expression: Expression;
}
// An ObjectLiteralExpression is the declaration node for an anonymous symbol.
+ // @kind(SyntaxKind.ObjectLiteralExpression)
export interface ObjectLiteralExpression extends PrimaryExpression, Declaration {
properties: NodeArray;
}
+ // @kind(SyntaxKind.PropertyAccessExpression)
export interface PropertyAccessExpression extends MemberExpression, Declaration {
expression: LeftHandSideExpression;
dotToken: Node;
name: Identifier;
}
+ // @kind(SyntaxKind.ElementAccessExpression)
export interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
}
+ // @kind(SyntaxKind.CallExpression)
export interface CallExpression extends LeftHandSideExpression {
expression: LeftHandSideExpression;
typeArguments?: NodeArray;
arguments: NodeArray;
}
+ // @kind(SyntaxKind.ExpressionWithTypeArguments)
export interface ExpressionWithTypeArguments extends TypeNode {
expression: LeftHandSideExpression;
typeArguments?: NodeArray;
}
+ // @kind(SyntaxKind.NewExpression)
export interface NewExpression extends CallExpression, PrimaryExpression { }
+ // @kind(SyntaxKind.TaggedTemplateExpression)
export interface TaggedTemplateExpression extends MemberExpression {
tag: LeftHandSideExpression;
template: LiteralExpression | TemplateExpression;
@@ -867,11 +1015,13 @@ namespace ts {
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
+ // @kind(SyntaxKind.AsExpression)
export interface AsExpression extends Expression {
expression: Expression;
type: TypeNode;
}
+ // @kind(SyntaxKind.TypeAssertionExpression)
export interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
@@ -880,6 +1030,7 @@ namespace ts {
export type AssertionExpression = TypeAssertion | AsExpression;
/// A JSX expression of the form ...
+ // @kind(SyntaxKind.JsxElement)
export interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray;
@@ -887,6 +1038,7 @@ namespace ts {
}
/// The opening element of a ... JsxElement
+ // @kind(SyntaxKind.JsxOpeningElement)
export interface JsxOpeningElement extends Expression {
_openingElementBrand?: any;
tagName: EntityName;
@@ -894,6 +1046,7 @@ namespace ts {
}
/// A JSX expression of the form
+ // @kind(SyntaxKind.JsxSelfClosingElement)
export interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement {
_selfClosingElementBrand?: any;
}
@@ -901,24 +1054,29 @@ namespace ts {
/// Either the opening tag in a ... pair, or the lone in a self-closing form
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
+ // @kind(SyntaxKind.JsxAttribute)
export interface JsxAttribute extends Node {
name: Identifier;
/// JSX attribute initializers are optional; is sugar for
initializer?: Expression;
}
+ // @kind(SyntaxKind.JsxSpreadAttribute)
export interface JsxSpreadAttribute extends Node {
expression: Expression;
}
+ // @kind(SyntaxKind.JsxClosingElement)
export interface JsxClosingElement extends Node {
tagName: EntityName;
}
+ // @kind(SyntaxKind.JsxExpression)
export interface JsxExpression extends Expression {
expression?: Expression;
}
+ // @kind(SyntaxKind.JsxText)
export interface JsxText extends Node {
_jsxTextExpressionBrand: any;
}
@@ -929,18 +1087,35 @@ namespace ts {
_statementBrand: any;
}
+ // @kind(SyntaxKind.EmptyStatement)
+ export interface EmptyStatement extends Statement { }
+
+ // @kind(SyntaxKind.DebuggerStatement)
+ export interface DebuggerStatement extends Statement { }
+
+ // @kind(SyntaxKind.MissingDeclaration)
+ export interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement {
+ name?: Identifier;
+ }
+
+ export type BlockLike = SourceFile | Block | ModuleBlock | CaseClause;
+
+ // @kind(SyntaxKind.Block)
export interface Block extends Statement {
statements: NodeArray;
}
+ // @kind(SyntaxKind.VariableStatement)
export interface VariableStatement extends Statement {
declarationList: VariableDeclarationList;
}
+ // @kind(SyntaxKind.ExpressionStatement)
export interface ExpressionStatement extends Statement {
expression: Expression;
}
+ // @kind(SyntaxKind.IfStatement)
export interface IfStatement extends Statement {
expression: Expression;
thenStatement: Statement;
@@ -951,78 +1126,101 @@ namespace ts {
statement: Statement;
}
+ // @kind(SyntaxKind.DoStatement)
export interface DoStatement extends IterationStatement {
expression: Expression;
}
+ // @kind(SyntaxKind.WhileStatement)
export interface WhileStatement extends IterationStatement {
expression: Expression;
}
+ // @kind(SyntaxKind.ForStatement)
export interface ForStatement extends IterationStatement {
initializer?: VariableDeclarationList | Expression;
condition?: Expression;
incrementor?: Expression;
}
+ // @kind(SyntaxKind.ForInStatement)
export interface ForInStatement extends IterationStatement {
initializer: VariableDeclarationList | Expression;
expression: Expression;
}
+ // @kind(SyntaxKind.ForOfStatement)
export interface ForOfStatement extends IterationStatement {
initializer: VariableDeclarationList | Expression;
expression: Expression;
}
- export interface BreakOrContinueStatement extends Statement {
+ // @kind(SyntaxKind.BreakStatement)
+ export interface BreakStatement extends Statement {
label?: Identifier;
}
+ // @kind(SyntaxKind.ContinueStatement)
+ export interface ContinueStatement extends Statement {
+ label?: Identifier;
+ }
+
+ export type BreakOrContinueStatement = BreakStatement | ContinueStatement;
+
+ // @kind(SyntaxKind.ReturnStatement)
export interface ReturnStatement extends Statement {
expression?: Expression;
}
+ // @kind(SyntaxKind.WithStatement)
export interface WithStatement extends Statement {
expression: Expression;
statement: Statement;
}
+ // @kind(SyntaxKind.SwitchStatement)
export interface SwitchStatement extends Statement {
expression: Expression;
caseBlock: CaseBlock;
}
+ // @kind(SyntaxKind.CaseBlock)
export interface CaseBlock extends Node {
clauses: NodeArray;
}
+ // @kind(SyntaxKind.CaseClause)
export interface CaseClause extends Node {
expression?: Expression;
statements: NodeArray;
}
+ // @kind(SyntaxKind.DefaultClause)
export interface DefaultClause extends Node {
statements: NodeArray;
}
export type CaseOrDefaultClause = CaseClause | DefaultClause;
+ // @kind(SyntaxKind.LabeledStatement)
export interface LabeledStatement extends Statement {
label: Identifier;
statement: Statement;
}
+ // @kind(SyntaxKind.ThrowStatement)
export interface ThrowStatement extends Statement {
expression: Expression;
}
+ // @kind(SyntaxKind.TryStatement)
export interface TryStatement extends Statement {
tryBlock: Block;
catchClause?: CatchClause;
finallyBlock?: Block;
}
+ // @kind(SyntaxKind.CatchClause)
export interface CatchClause extends Node {
variableDeclaration: VariableDeclaration;
block: Block;
@@ -1035,34 +1233,48 @@ namespace ts {
members: NodeArray;
}
- export interface ClassDeclaration extends ClassLikeDeclaration, Statement {
+ // @kind(SyntaxKind.ClassDeclaration)
+ export interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement {
+ name?: Identifier;
}
+ // @kind(SyntaxKind.ClassExpression)
export interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
}
export interface ClassElement extends Declaration {
_classElementBrand: any;
+ name?: PropertyName;
}
- export interface InterfaceDeclaration extends Declaration, Statement {
+ export interface TypeElement extends Declaration {
+ _typeElementBrand: any;
+ name?: PropertyName;
+ questionToken?: Node;
+ }
+
+ // @kind(SyntaxKind.InterfaceDeclaration)
+ export interface InterfaceDeclaration extends DeclarationStatement {
name: Identifier;
typeParameters?: NodeArray;
heritageClauses?: NodeArray;
- members: NodeArray;
+ members: NodeArray;
}
+ // @kind(SyntaxKind.HeritageClause)
export interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray;
}
- export interface TypeAliasDeclaration extends Declaration, Statement {
+ // @kind(SyntaxKind.TypeAliasDeclaration)
+ export interface TypeAliasDeclaration extends DeclarationStatement {
name: Identifier;
typeParameters?: NodeArray;
type: TypeNode;
}
+ // @kind(SyntaxKind.EnumMember)
export interface EnumMember extends Declaration {
// This does include ComputedPropertyName, but the parser will give an error
// if it parses a ComputedPropertyName in an EnumMember
@@ -1070,21 +1282,27 @@ namespace ts {
initializer?: Expression;
}
- export interface EnumDeclaration extends Declaration, Statement {
+ // @kind(SyntaxKind.EnumDeclaration)
+ export interface EnumDeclaration extends DeclarationStatement {
name: Identifier;
members: NodeArray;
}
- export interface ModuleDeclaration extends Declaration, Statement {
+ export type ModuleBody = ModuleBlock | ModuleDeclaration;
+
+ // @kind(SyntaxKind.ModuleDeclaration)
+ export interface ModuleDeclaration extends DeclarationStatement {
name: Identifier | LiteralExpression;
body: ModuleBlock | ModuleDeclaration;
}
+ // @kind(SyntaxKind.ModuleBlock)
export interface ModuleBlock extends Node, Statement {
statements: NodeArray;
}
- export interface ImportEqualsDeclaration extends Declaration, Statement {
+ // @kind(SyntaxKind.ImportEqualsDeclaration)
+ export interface ImportEqualsDeclaration extends DeclarationStatement {
name: Identifier;
// 'EntityName' for an internal module reference, 'ExternalModuleReference' for an external
@@ -1092,6 +1310,7 @@ namespace ts {
moduleReference: EntityName | ExternalModuleReference;
}
+ // @kind(SyntaxKind.ExternalModuleReference)
export interface ExternalModuleReference extends Node {
expression?: Expression;
}
@@ -1100,6 +1319,7 @@ namespace ts {
// import "mod" => importClause = undefined, moduleSpecifier = "mod"
// In rest of the cases, module specifier is string literal corresponding to module
// ImportClause information is shown at its declaration below.
+ // @kind(SyntaxKind.ImportDeclaration)
export interface ImportDeclaration extends Statement {
importClause?: ImportClause;
moduleSpecifier: Expression;
@@ -1111,36 +1331,51 @@ namespace ts {
// import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns }
// import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]}
// import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]}
+ // @kind(SyntaxKind.ImportClause)
export interface ImportClause extends Declaration {
name?: Identifier; // Default binding
namedBindings?: NamespaceImport | NamedImports;
}
+ // @kind(SyntaxKind.NamespaceImport)
export interface NamespaceImport extends Declaration {
name: Identifier;
}
- export interface ExportDeclaration extends Declaration, Statement {
+ // @kind(SyntaxKind.ExportDeclaration)
+ export interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
}
- export interface NamedImportsOrExports extends Node {
- elements: NodeArray;
+ // @kind(SyntaxKind.NamedImports)
+ export interface NamedImports extends Node {
+ elements: NodeArray;
}
- export type NamedImports = NamedImportsOrExports;
- export type NamedExports = NamedImportsOrExports;
+ // @kind(SyntaxKind.NamedExports)
+ export interface NamedExports extends Node {
+ elements: NodeArray;
+ }
- export interface ImportOrExportSpecifier extends Declaration {
+ export type NamedImportsOrExports = NamedImports | NamedExports;
+
+ // @kind(SyntaxKind.ImportSpecifier)
+ export interface ImportSpecifier extends Declaration {
propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
name: Identifier; // Declared name
}
- export type ImportSpecifier = ImportOrExportSpecifier;
- export type ExportSpecifier = ImportOrExportSpecifier;
+ // @kind(SyntaxKind.ExportSpecifier)
+ export interface ExportSpecifier extends Declaration {
+ propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
+ name: Identifier; // Declared name
+ }
- export interface ExportAssignment extends Declaration, Statement {
+ export type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier;
+
+ // @kind(SyntaxKind.ExportAssignment)
+ export interface ExportAssignment extends DeclarationStatement {
isExportEquals?: boolean;
expression: Expression;
}
@@ -1155,6 +1390,7 @@ namespace ts {
}
// represents a top level: { type } expression in a JSDoc comment.
+ // @kind(SyntaxKind.JSDocTypeExpression)
export interface JSDocTypeExpression extends Node {
type: JSDocType;
}
@@ -1163,90 +1399,111 @@ namespace ts {
_jsDocTypeBrand: any;
}
+ // @kind(SyntaxKind.JSDocAllType)
export interface JSDocAllType extends JSDocType {
_JSDocAllTypeBrand: any;
}
+ // @kind(SyntaxKind.JSDocUnknownType)
export interface JSDocUnknownType extends JSDocType {
_JSDocUnknownTypeBrand: any;
}
+ // @kind(SyntaxKind.JSDocArrayType)
export interface JSDocArrayType extends JSDocType {
elementType: JSDocType;
}
+ // @kind(SyntaxKind.JSDocUnionType)
export interface JSDocUnionType extends JSDocType {
types: NodeArray;
}
+ // @kind(SyntaxKind.JSDocTupleType)
export interface JSDocTupleType extends JSDocType {
types: NodeArray;
}
+ // @kind(SyntaxKind.JSDocNonNullableType)
export interface JSDocNonNullableType extends JSDocType {
type: JSDocType;
}
+ // @kind(SyntaxKind.JSDocNullableType)
export interface JSDocNullableType extends JSDocType {
type: JSDocType;
}
+ // @kind(SyntaxKind.JSDocRecordType)
export interface JSDocRecordType extends JSDocType, TypeLiteralNode {
members: NodeArray;
}
+ // @kind(SyntaxKind.JSDocTypeReference)
export interface JSDocTypeReference extends JSDocType {
name: EntityName;
typeArguments: NodeArray;
}
+ // @kind(SyntaxKind.JSDocOptionalType)
export interface JSDocOptionalType extends JSDocType {
type: JSDocType;
}
+ // @kind(SyntaxKind.JSDocFunctionType)
export interface JSDocFunctionType extends JSDocType, SignatureDeclaration {
parameters: NodeArray;
type: JSDocType;
}
+ // @kind(SyntaxKind.JSDocVariadicType)
export interface JSDocVariadicType extends JSDocType {
type: JSDocType;
}
+ // @kind(SyntaxKind.JSDocConstructorType)
export interface JSDocConstructorType extends JSDocType {
type: JSDocType;
}
+ // @kind(SyntaxKind.JSDocThisType)
export interface JSDocThisType extends JSDocType {
type: JSDocType;
}
- export interface JSDocRecordMember extends PropertyDeclaration {
+ // @kind(SyntaxKind.JSDocRecordMember)
+ export interface JSDocRecordMember extends PropertySignature {
name: Identifier | LiteralExpression;
type?: JSDocType;
}
+ // @kind(SyntaxKind.JSDocComment)
export interface JSDocComment extends Node {
tags: NodeArray;
}
+ // @kind(SyntaxKind.JSDocTag)
export interface JSDocTag extends Node {
atToken: Node;
tagName: Identifier;
}
+ // @kind(SyntaxKind.JSDocTemplateTag)
export interface JSDocTemplateTag extends JSDocTag {
typeParameters: NodeArray;
}
+ // @kind(SyntaxKind.JSDocReturnTag)
export interface JSDocReturnTag extends JSDocTag {
typeExpression: JSDocTypeExpression;
}
+ // @kind(SyntaxKind.JSDocTypeTag)
export interface JSDocTypeTag extends JSDocTag {
typeExpression: JSDocTypeExpression;
}
+ // @kind(SyntaxKind.JSDocParameterTag)
export interface JSDocParameterTag extends JSDocTag {
preParameterName?: Identifier;
typeExpression?: JSDocTypeExpression;
@@ -1254,7 +1511,13 @@ namespace ts {
isBracketed: boolean;
}
+ export interface AmdDependency {
+ path: string;
+ name: string;
+ }
+
// Source files are declarations when they are external modules.
+ // @kind(SyntaxKind.SourceFile)
export interface SourceFile extends Declaration {
statements: NodeArray;
endOfFileToken: Node;
@@ -1263,7 +1526,7 @@ namespace ts {
/* internal */ path: Path;
text: string;
- amdDependencies: {path: string; name: string}[];
+ amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
@@ -1494,7 +1757,7 @@ namespace ts {
export interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
- buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
@@ -2114,6 +2377,8 @@ namespace ts {
noImplicitReturns?: boolean;
noFallthroughCasesInSwitch?: boolean;
forceConsistentCasingInFileNames?: boolean;
+ allowSyntheticDefaultImports?: boolean;
+ allowJs?: boolean;
/* @internal */ stripInternal?: boolean;
// Skip checking lib.d.ts to help speed up tests.
@@ -2179,17 +2444,17 @@ namespace ts {
/* @internal */
export interface CommandLineOptionBase {
name: string;
- type: string | Map; // "string", "number", "boolean", 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
+ type: "string" | "number" | "boolean" | Map; // 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;
}
/* @internal */
export interface CommandLineOptionOfPrimitiveType extends CommandLineOptionBase {
- type: string; // "string" | "number" | "boolean"
+ type: "string" | "number" | "boolean";
}
/* @internal */
@@ -2341,7 +2606,7 @@ namespace ts {
export interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
// 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
+ // to determine location of bundled typings for node module
readFile(fileName: string): string;
}
@@ -2349,7 +2614,7 @@ namespace ts {
resolvedFileName: string;
/*
* Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be proper external module:
- * - be a .d.ts file
+ * - be a .d.ts file
* - use top level imports\exports
* - don't use tripleslash references
*/
@@ -2372,11 +2637,11 @@ namespace ts {
getNewLine(): string;
/*
- * CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
- * module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
+ * CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
+ * module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
* will appply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
- * If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
- * 'throw new Error("NotImplemented")'
+ * If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
+ * 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
}
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts
index ed7242a785e..95bf4ff7fa3 100644
--- a/src/compiler/utilities.ts
+++ b/src/compiler/utilities.ts
@@ -38,6 +38,8 @@ namespace ts {
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
+ isEmitBlocked(emitFileName: string): boolean;
+
writeFile: WriteFileCallback;
}
@@ -464,9 +466,6 @@ namespace ts {
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.VoidExpression;
- case SyntaxKind.StringLiteral:
- // Specialized signatures can have string literals as their parameters' type names
- return node.parent.kind === SyntaxKind.Parameter;
case SyntaxKind.ExpressionWithTypeArguments:
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
@@ -907,23 +906,6 @@ namespace ts {
return false;
}
- export function childIsDecorated(node: Node): boolean {
- switch (node.kind) {
- case SyntaxKind.ClassDeclaration:
- return forEach((node).members, nodeOrChildIsDecorated);
-
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.SetAccessor:
- return forEach((node).parameters, nodeIsDecorated);
- }
-
- return false;
- }
-
- export function nodeOrChildIsDecorated(node: Node): boolean {
- return nodeIsDecorated(node) || childIsDecorated(node);
- }
-
export function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression {
return node.kind === SyntaxKind.PropertyAccessExpression;
}
@@ -1327,7 +1309,7 @@ namespace ts {
}
// True if the given identifier, string literal, or number literal is the name of a declaration node
- export function isDeclarationName(name: Node): boolean {
+ export function isDeclarationName(name: Node): name is Identifier | StringLiteral | LiteralExpression {
if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) {
return false;
}
@@ -1545,7 +1527,7 @@ namespace ts {
return node.kind === SyntaxKind.Identifier && (node).text === "Symbol";
}
- export function isModifier(token: SyntaxKind): boolean {
+ export function isModifierKind(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AsyncKeyword:
@@ -1578,20 +1560,60 @@ namespace ts {
return isFunctionLike(n) || n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.SourceFile;
}
- export function cloneEntityName(node: EntityName): EntityName {
- if (node.kind === SyntaxKind.Identifier) {
- const clone = createSynthesizedNode(SyntaxKind.Identifier);
- clone.text = (node).text;
- return clone;
+ /**
+ * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent"
+ * properties are excluded by default, and can be provided via the "location", "flags", and
+ * "parent" parameters.
+ * @param node The node to clone.
+ * @param location An optional TextRange to use to supply the new position.
+ * @param flags The NodeFlags to use for the cloned node.
+ * @param parent The parent for the new node.
+ */
+ export function cloneNode(node: T, location?: TextRange, flags?: NodeFlags, parent?: Node): T {
+ // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
+ // the original node. We also need to exclude specific properties and only include own-
+ // properties (to skip members already defined on the shared prototype).
+ const clone = location !== undefined
+ ? createNode(node.kind, location.pos, location.end)
+ : createSynthesizedNode(node.kind);
+
+ for (const key in node) {
+ if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
+ continue;
+ }
+
+ (clone)[key] = (node)[key];
}
- else {
- const clone = createSynthesizedNode(SyntaxKind.QualifiedName);
- clone.left = cloneEntityName((node).left);
- clone.left.parent = clone;
- clone.right = cloneEntityName((node).right);
- clone.right.parent = clone;
- return clone;
+
+ if (flags !== undefined) {
+ clone.flags = flags;
}
+
+ if (parent !== undefined) {
+ clone.parent = parent;
+ }
+
+ return clone;
+ }
+
+ /**
+ * Creates a deep clone of an EntityName, with new parent pointers.
+ * @param node The EntityName to clone.
+ * @param parent The parent for the cloned node.
+ */
+ export function cloneEntityName(node: EntityName, parent?: Node): EntityName {
+ const clone = cloneNode(node, node, node.flags, parent);
+ if (isQualifiedName(clone)) {
+ const { left, right } = clone;
+ clone.left = cloneEntityName(left, clone);
+ clone.right = cloneNode(right, right, right.flags, parent);
+ }
+
+ return clone;
+ }
+
+ export function isQualifiedName(node: Node): node is QualifiedName {
+ return node.kind === SyntaxKind.QualifiedName;
}
export function nodeIsSynthesized(node: Node): boolean {
@@ -1867,8 +1889,10 @@ namespace ts {
* Resolves a local path to a path which is absolute to the base of the emit
*/
export function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string {
- const dir = host.getCurrentDirectory();
- const relativePath = getRelativePathToDirectoryOrUrl(dir, fileName, dir, f => host.getCanonicalFileName(f), /*isAbsolutePathAnUrl*/ false);
+ const getCanonicalFileName = (f: string) => host.getCanonicalFileName(f);
+ const dir = toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
+ const filePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
+ const relativePath = getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return removeFileExtension(relativePath);
}
@@ -1885,15 +1909,85 @@ namespace ts {
return emitOutputFilePathWithoutExtension + extension;
}
+ export function getEmitScriptTarget(compilerOptions: CompilerOptions) {
+ return compilerOptions.target || ScriptTarget.ES3;
+ }
+
+ export function getEmitModuleKind(compilerOptions: CompilerOptions) {
+ return compilerOptions.module ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None;
+ }
+
+ export interface EmitFileNames {
+ jsFilePath: string;
+ sourceMapFilePath: string;
+ declarationFilePath: string;
+ }
+
+ export function forEachExpectedEmitFile(host: EmitHost,
+ action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void,
+ targetSourceFile?: SourceFile) {
+ const options = host.getCompilerOptions();
+ // Emit on each source file
+ if (options.outFile || options.out) {
+ onBundledEmit(host);
+ }
+ else {
+ const sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
+ for (const sourceFile of sourceFiles) {
+ if (!isDeclarationFile(sourceFile)) {
+ onSingleFileEmit(host, sourceFile);
+ }
+ }
+ }
+
+ function onSingleFileEmit(host: EmitHost, sourceFile: SourceFile) {
+ const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host,
+ sourceFile.languageVariant === LanguageVariant.JSX && options.jsx === JsxEmit.Preserve ? ".jsx" : ".js");
+ const emitFileNames: EmitFileNames = {
+ jsFilePath,
+ sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
+ declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined
+ };
+ action(emitFileNames, [sourceFile], /*isBundledEmit*/false);
+ }
+
+ function onBundledEmit(host: EmitHost) {
+ // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
+ const bundledSources = filter(host.getSourceFiles(),
+ sourceFile => !isDeclarationFile(sourceFile) && // Not a declaration file
+ (!isExternalModule(sourceFile) || // non module file
+ (getEmitModuleKind(options) && isExternalModule(sourceFile)))); // module that can emit - note falsy value from getEmitModuleKind means the module kind that shouldn't be emitted
+ if (bundledSources.length) {
+ const jsFilePath = options.outFile || options.out;
+ const emitFileNames: EmitFileNames = {
+ jsFilePath,
+ sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
+ declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options)
+ };
+ action(emitFileNames, bundledSources, /*isBundledEmit*/true);
+ }
+ }
+
+ function getSourceMapFilePath(jsFilePath: string, options: CompilerOptions) {
+ return options.sourceMap ? jsFilePath + ".map" : undefined;
+ }
+
+ function getDeclarationEmitFilePath(jsFilePath: string, options: CompilerOptions) {
+ return options.declaration ? removeFileExtension(jsFilePath) + ".d.ts" : undefined;
+ }
+ }
+
export function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string) {
let sourceFilePath = getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory());
sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), "");
return combinePaths(newDirPath, sourceFilePath);
}
- export function writeFile(host: EmitHost, diagnostics: Diagnostic[], fileName: string, data: string, writeByteOrderMark: boolean) {
+ export function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean) {
host.writeFile(fileName, data, writeByteOrderMark, hostErrorMessage => {
- diagnostics.push(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
+ diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
});
}
@@ -1917,18 +2011,6 @@ namespace ts {
return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type;
}
- export function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
- if (!isDeclarationFile(sourceFile)) {
- if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) {
- // 1. in-browser single file compilation scenario
- // 2. non .js file
- return compilerOptions.isolatedModules || !fileExtensionIs(sourceFile.fileName, ".js");
- }
- return false;
- }
- return false;
- }
-
export function getAllAccessorDeclarations(declarations: NodeArray, accessor: AccessorDeclaration) {
let firstAccessor: AccessorDeclaration;
let secondAccessor: AccessorDeclaration;
@@ -2273,11 +2355,7 @@ namespace ts {
}
export function hasJavaScriptFileExtension(fileName: string) {
- return fileExtensionIs(fileName, ".js") || fileExtensionIs(fileName, ".jsx");
- }
-
- export function allowsJsxExpressions(fileName: string) {
- return fileExtensionIs(fileName, ".tsx") || fileExtensionIs(fileName, ".jsx");
+ return forEach(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension));
}
/**
@@ -2318,6 +2396,55 @@ namespace ts {
return output;
}
+ /**
+ * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph
+ * as the fallback implementation does not check for circular references by default.
+ */
+ export const stringify: (value: any) => string = typeof JSON !== "undefined" && JSON.stringify
+ ? JSON.stringify
+ : stringifyFallback;
+
+ /**
+ * Serialize an object graph into a JSON string.
+ */
+ function stringifyFallback(value: any): string {
+ // JSON.stringify returns `undefined` here, instead of the string "undefined".
+ return value === undefined ? undefined : stringifyValue(value);
+ }
+
+ function stringifyValue(value: any): string {
+ return typeof value === "string" ? `"${escapeString(value)}"`
+ : typeof value === "number" ? isFinite(value) ? String(value) : "null"
+ : typeof value === "boolean" ? value ? "true" : "false"
+ : typeof value === "object" && value ? isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value)
+ : /*fallback*/ "null";
+ }
+
+ function cycleCheck(cb: (value: any) => string, value: any) {
+ Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON");
+ value.__cycle = true;
+ const result = cb(value);
+ delete value.__cycle;
+ return result;
+ }
+
+ function stringifyArray(value: any) {
+ return `[${reduceLeft(value, stringifyElement, "")}]`;
+ }
+
+ function stringifyElement(memo: string, value: any) {
+ return (memo ? memo + "," : memo) + stringifyValue(value);
+ }
+
+ function stringifyObject(value: any) {
+ return `{${reduceProperties(value, stringifyProperty, "")}}`;
+ }
+
+ function stringifyProperty(memo: string, value: any, key: string) {
+ return value === undefined || typeof value === "function" || key === "__cycle" ? memo
+ : (memo ? memo + "," : memo) + `"${escapeString(key)}":${stringifyValue(value)}`;
+ }
+
const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts
index 848f229f109..8ee287b2637 100644
--- a/src/harness/compilerRunner.ts
+++ b/src/harness/compilerRunner.ts
@@ -40,89 +40,79 @@ class CompilerBaselineRunner extends RunnerBase {
this.basePath += "/" + this.testSuiteName;
}
+ private makeUnitName(name: string, root: string) {
+ return ts.isRootedDiskPath(name) ? name : ts.combinePaths(root, name);
+ };
+
public checkTestCodeOutput(fileName: string) {
describe("compiler tests for " + fileName, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let justName: string;
- let content: string;
- let testCaseContent: { settings: Harness.TestCaseParser.CompilerSettings; testUnitData: Harness.TestCaseParser.TestUnitData[]; };
-
- let units: Harness.TestCaseParser.TestUnitData[];
- let tcSettings: Harness.TestCaseParser.CompilerSettings;
let lastUnit: Harness.TestCaseParser.TestUnitData;
- let rootDir: string;
+ let harnessSettings: Harness.TestCaseParser.CompilerSettings;
+ let hasNonDtsFiles: boolean;
let result: Harness.Compiler.CompilerResult;
- let program: ts.Program;
let options: ts.CompilerOptions;
// equivalent to the files that will be passed on the command line
- let toBeCompiled: { unitName: string; content: string }[];
+ let toBeCompiled: Harness.Compiler.TestFile[];
// equivalent to other files on the file system not directly passed to the compiler (ie things that are referenced by other files)
- let otherFiles: { unitName: string; content: string }[];
- let harnessCompiler: Harness.Compiler.HarnessCompiler;
+ let otherFiles: Harness.Compiler.TestFile[];
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ""); // strips the fileName from the path.
- content = Harness.IO.readFile(fileName);
- testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
- units = testCaseContent.testUnitData;
- tcSettings = testCaseContent.settings;
+ const content = Harness.IO.readFile(fileName);
+ const testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
+ const units = testCaseContent.testUnitData;
+ harnessSettings = testCaseContent.settings;
lastUnit = units[units.length - 1];
- rootDir = lastUnit.originalFilePath.indexOf("conformance") === -1 ? "tests/cases/compiler/" : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf("/")) + "/";
- harnessCompiler = Harness.Compiler.getCompiler();
+ 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: rootDir + lastUnit.name, content: lastUnit.content });
+ toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content });
units.forEach(unit => {
if (unit.name !== lastUnit.name) {
- otherFiles.push({ unitName: rootDir + unit.name, content: unit.content });
+ otherFiles.push({ unitName: this.makeUnitName(unit.name, rootDir), content: unit.content });
}
});
}
else {
toBeCompiled = units.map(unit => {
- return { unitName: rootDir + unit.name, content: unit.content };
+ return { unitName: this.makeUnitName(unit.name, rootDir), content: unit.content };
});
}
- options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _program) {
- result = compileResult;
- // The program will be used by typeWriter
- program = _program;
- }, function (settings) {
- harnessCompiler.setCompilerSettings(tcSettings);
- });
+ const output = Harness.Compiler.compileFiles(
+ toBeCompiled, otherFiles, harnessSettings, /* options */ undefined, /* currentDirectory */ undefined);
+
+ options = output.options;
+ result = output.result;
});
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
justName = undefined;
- content = undefined;
- testCaseContent = undefined;
- units = undefined;
- tcSettings = undefined;
lastUnit = undefined;
- rootDir = undefined;
+ hasNonDtsFiles = undefined;
result = undefined;
- program = undefined;
options = undefined;
toBeCompiled = undefined;
otherFiles = undefined;
- harnessCompiler = undefined;
});
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : "";
}
- function getErrorBaseline(toBeCompiled: { unitName: string; content: string }[], otherFiles: { unitName: string; content: string }[], result: Harness.Compiler.CompilerResult) {
+ function getErrorBaseline(toBeCompiled: Harness.Compiler.TestFile[], otherFiles: Harness.Compiler.TestFile[], result: Harness.Compiler.CompilerResult) {
return Harness.Compiler.getErrorBaseline(toBeCompiled.concat(otherFiles), result.errors);
}
@@ -151,8 +141,8 @@ class CompilerBaselineRunner extends RunnerBase {
});
it("Correct JS output for " + fileName, () => {
- if (!ts.fileExtensionIs(lastUnit.name, ".d.ts") && this.emit) {
- if (result.files.length === 0 && result.errors.length === 0) {
+ if (hasNonDtsFiles && this.emit) {
+ if (!options.noEmit && result.files.length === 0 && result.errors.length === 0) {
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
}
@@ -184,9 +174,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
}
- const declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
- harnessCompiler.setCompilerSettings(tcSettings);
- }, options);
+ const declFileCompilationResult =
+ Harness.Compiler.compileDeclarationFiles(
+ toBeCompiled, otherFiles, result, harnessSettings, options, /*currentDirectory*/ undefined);
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
@@ -257,10 +247,11 @@ class CompilerBaselineRunner extends RunnerBase {
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
+ const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
- const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ true);
- const pullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ false);
+ const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
+ const pullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ false);
const fullResults: ts.Map = {};
const pullResults: ts.Map = {};
@@ -274,14 +265,14 @@ class CompilerBaselineRunner extends RunnerBase {
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
- checkBaseLines(/*isSymbolBaseLine:*/ false);
+ checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
- checkBaseLines(/*isSymbolBaseLine:*/ true);
+ checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
@@ -367,7 +358,6 @@ class CompilerBaselineRunner extends RunnerBase {
public initializeTests() {
describe(this.testSuiteName + " tests", () => {
describe("Setup compiler for compiler baselines", () => {
- const harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
});
diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts
index 1c8593a9e12..9d729345781 100644
--- a/src/harness/fourslash.ts
+++ b/src/harness/fourslash.ts
@@ -48,12 +48,6 @@ namespace FourSlash {
ranges: Range[];
}
- export interface TestXmlData {
- invalidReason: string;
- originalName: string;
- actions: string[];
- }
-
interface MemberListData {
result: {
maybeInaccurate: boolean;
@@ -84,14 +78,14 @@ namespace FourSlash {
marker?: Marker;
}
- interface ILocationInformation {
+ interface LocationInformation {
position: number;
sourcePosition: number;
sourceLine: number;
sourceColumn: number;
}
- interface IRangeLocationInformation extends ILocationInformation {
+ interface RangeLocationInformation extends LocationInformation {
marker?: Marker;
}
@@ -134,11 +128,6 @@ namespace FourSlash {
return settings;
}
- export let currentTestState: TestState = null;
- function assertionMessage(msg: string) {
- return "\nMarker: " + currentTestState.lastKnownMarker + "\nChecking: " + msg + "\n\n";
- }
-
export class TestCancellationToken implements ts.HostCancellationToken {
// 0 - cancelled
// >0 - not cancelled
@@ -216,9 +205,6 @@ namespace FourSlash {
public formatCodeOptions: ts.FormatCodeOptions;
- private scenarioActions: string[] = [];
- private taoInvalidReason: string = null;
-
private inputFiles: ts.Map = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references
// Add input file which has matched file name with the given reference-file path.
@@ -300,7 +286,7 @@ namespace FourSlash {
// Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts"
// so convert them before making appropriate comparison
const importedFilePath = this.basePath + "/" + importedFile.fileName;
- this.addMatchedInputFile(importedFilePath, compilationOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions);
+ this.addMatchedInputFile(importedFilePath, ts.getSupportedExtensions(compilationOptions));
});
// Check if no-default-lib flag is false and if so add default library
@@ -338,7 +324,6 @@ namespace FourSlash {
this.testData.files.forEach(file => {
const fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), "").substr(1);
const fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf("."));
- this.scenarioActions.push("");
});
// Open the first file by default
@@ -367,35 +352,22 @@ namespace FourSlash {
public goToPosition(pos: number) {
this.currentCaretPosition = pos;
-
- const lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName));
- const lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos);
- this.scenarioActions.push(``);
}
public moveCaretRight(count = 1) {
this.currentCaretPosition += count;
this.currentCaretPosition = Math.min(this.currentCaretPosition, this.getFileContent(this.activeFile.fileName).length);
- if (count > 0) {
- this.scenarioActions.push(``);
- }
- else {
- this.scenarioActions.push(``);
- }
}
// Opens a file given its 0-based index or fileName
- public openFile(index: number): void;
- public openFile(name: string): void;
- public openFile(indexOrName: any) {
+ public openFile(index: number, content?: string): void;
+ public openFile(name: string, content?: string): void;
+ public openFile(indexOrName: any, content?: string) {
const fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
- const fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), "").substr(1);
- this.scenarioActions.push(``);
-
// Let the host know that this file is now open
- this.languageServiceAdapterHost.openFile(fileToOpen.fileName);
+ this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content);
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
@@ -407,8 +379,6 @@ namespace FourSlash {
const exists = this.anyErrorInRange(predicate, startMarker, endMarker);
- this.taoInvalidReason = "verifyErrorExistsBetweenMarkers NYI";
-
if (exists !== negative) {
this.printErrorLog(negative, this.getAllDiagnostics());
throw new Error("Failure between markers: " + startMarkerName + ", " + endMarkerName);
@@ -421,7 +391,11 @@ namespace FourSlash {
}
private messageAtLastKnownMarker(message: string) {
- return "Marker: " + currentTestState.lastKnownMarker + "\n" + message;
+ return "Marker: " + this.lastKnownMarker + "\n" + message;
+ }
+
+ private assertionMessageAtLastKnownMarker(msg: string) {
+ return "\nMarker: " + this.lastKnownMarker + "\nChecking: " + msg + "\n\n";
}
private getDiagnostics(fileName: string): ts.Diagnostic[] {
@@ -461,8 +435,6 @@ namespace FourSlash {
};
}
- this.taoInvalidReason = "verifyErrorExistsAfterMarker NYI";
-
const exists = this.anyErrorInRange(predicate, marker);
const diagnostics = this.getAllDiagnostics();
@@ -511,10 +483,8 @@ namespace FourSlash {
const errors = this.getDiagnostics(this.activeFile.fileName);
const actual = errors.length;
- this.scenarioActions.push(``);
-
if (actual !== expected) {
- this.printErrorLog(false, errors);
+ this.printErrorLog(/*expectErrors*/ false, errors);
const errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")";
Harness.IO.log(errorMsg);
this.raiseError(errorMsg);
@@ -527,8 +497,6 @@ namespace FourSlash {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
}
- this.taoInvalidReason = "verifyEval impossible";
-
const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)();
if (evaluation !== value) {
this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`);
@@ -540,21 +508,22 @@ namespace FourSlash {
if (emit.outputFiles.length !== 1) {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
}
- this.taoInvalidReason = "verifyGetEmitOutputForCurrentFile impossible";
const actual = emit.outputFiles[0].text;
if (actual !== expected) {
this.raiseError(`Expected emit output to be "${expected}", but got "${actual}"`);
}
}
- public verifyMemberListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
-
- if (text || documentation || kind) {
- this.taoInvalidReason = "verifyMemberListContains only supports the \"symbol\" parameter";
+ public verifyGetEmitOutputContentsForCurrentFile(expected: ts.OutputFile[]): void {
+ const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
+ assert.equal(emit.outputFiles.length, expected.length, "Number of emit output files");
+ for (let i = 0; i < emit.outputFiles.length; i++) {
+ assert.equal(emit.outputFiles[i].name, expected[i].name, "FileName");
+ assert.equal(emit.outputFiles[i].text, expected[i].text, "Content");
}
+ }
+ public verifyMemberListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
const members = this.getMemberListAtCaret();
if (members) {
this.assertItemInCompletionList(members.entries, symbol, text, documentation, kind);
@@ -565,18 +534,9 @@ namespace FourSlash {
}
public verifyMemberListCount(expectedCount: number, negative: boolean) {
- if (expectedCount === 0) {
- if (negative) {
- this.verifyMemberListIsEmpty(false);
- return;
- }
- else {
- this.scenarioActions.push("");
- }
- }
- else {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
+ if (expectedCount === 0 && negative) {
+ this.verifyMemberListIsEmpty(/*negative*/ false);
+ return;
}
const members = this.getMemberListAtCaret();
@@ -594,9 +554,6 @@ namespace FourSlash {
}
public verifyMemberListDoesNotContain(symbol: string) {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
-
const members = this.getMemberListAtCaret();
if (members && members.entries.filter(e => e.name === symbol).length !== 0) {
this.raiseError(`Member list did contain ${symbol}`);
@@ -604,8 +561,6 @@ namespace FourSlash {
}
public verifyCompletionListItemsCountIsGreaterThan(count: number, negative: boolean) {
- this.taoInvalidReason = "verifyCompletionListItemsCountIsGreaterThan NYI";
-
const completions = this.getCompletionListAtCaret();
const itemsCount = completions.entries.length;
@@ -622,13 +577,6 @@ namespace FourSlash {
}
public verifyMemberListIsEmpty(negative: boolean) {
- if (negative) {
- this.scenarioActions.push("");
- }
- else {
- this.scenarioActions.push("");
- }
-
const members = this.getMemberListAtCaret();
if ((!members || members.entries.length === 0) && negative) {
this.raiseError("Member list is empty at Caret");
@@ -647,8 +595,6 @@ namespace FourSlash {
}
public verifyCompletionListIsEmpty(negative: boolean) {
- this.scenarioActions.push("");
-
const completions = this.getCompletionListAtCaret();
if ((!completions || completions.entries.length === 0) && negative) {
this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition);
@@ -716,8 +662,6 @@ namespace FourSlash {
// and keep it in the list of filtered entry.
return true;
}
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
const completions = this.getCompletionListAtCaret();
if (completions) {
@@ -745,24 +689,20 @@ namespace FourSlash {
}
public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) {
- this.taoInvalidReason = "verifyCompletionEntryDetails NYI";
-
const details = this.getCompletionEntryDetails(entryName);
- assert.equal(ts.displayPartsToString(details.displayParts), expectedText, assertionMessage("completion entry details text"));
+ assert.equal(ts.displayPartsToString(details.displayParts), expectedText, this.assertionMessageAtLastKnownMarker("completion entry details text"));
if (expectedDocumentation !== undefined) {
- assert.equal(ts.displayPartsToString(details.documentation), expectedDocumentation, assertionMessage("completion entry documentation"));
+ assert.equal(ts.displayPartsToString(details.documentation), expectedDocumentation, this.assertionMessageAtLastKnownMarker("completion entry documentation"));
}
if (kind !== undefined) {
- assert.equal(details.kind, kind, assertionMessage("completion entry kind"));
+ assert.equal(details.kind, kind, this.assertionMessageAtLastKnownMarker("completion entry kind"));
}
}
public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) {
- this.taoInvalidReason = "verifyReferencesAtPositionListContains NYI";
-
const references = this.getReferencesAtCaret();
if (!references || references.length === 0) {
@@ -784,8 +724,6 @@ namespace FourSlash {
}
public verifyReferencesCountIs(count: number, localFilesOnly = true) {
- this.taoInvalidReason = "verifyReferences NYI";
-
const references = this.getReferencesAtCaret();
let referencesCount = 0;
@@ -845,13 +783,6 @@ namespace FourSlash {
}
public verifyQuickInfoString(negative: boolean, expectedText?: string, expectedDocumentation?: string) {
- [expectedText, expectedDocumentation].forEach(str => {
- if (str) {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
- }
- });
-
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
const actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : "";
const actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : "";
@@ -871,7 +802,7 @@ namespace FourSlash {
}
// TODO: should be '==='?
if (expectedDocumentation != undefined) {
- assert.equal(actualQuickInfoDocumentation, expectedDocumentation, assertionMessage("quick info doc"));
+ assert.equal(actualQuickInfoDocumentation, expectedDocumentation, this.assertionMessageAtLastKnownMarker("quick info doc"));
}
}
}
@@ -879,8 +810,6 @@ namespace FourSlash {
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; },
displayParts: ts.SymbolDisplayPart[],
documentation: ts.SymbolDisplayPart[]) {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
function getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
let result = "";
@@ -947,8 +876,6 @@ namespace FourSlash {
}
public verifyQuickInfoExists(negative: boolean) {
- this.taoInvalidReason = "verifyQuickInfoExists NYI";
-
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (negative) {
if (actualQuickInfo) {
@@ -963,8 +890,6 @@ namespace FourSlash {
}
public verifyCurrentSignatureHelpIs(expected: string) {
- this.taoInvalidReason = "verifyCurrentSignatureHelpIs NYI";
-
const help = this.getActiveSignatureHelpItem();
assert.equal(
ts.displayPartsToString(help.prefixDisplayParts) +
@@ -973,75 +898,51 @@ namespace FourSlash {
}
public verifyCurrentParameterIsletiable(isVariable: boolean) {
- this.taoInvalidReason = "verifyCurrentParameterIsletiable NYI";
-
const signature = this.getActiveSignatureHelpItem();
assert.isNotNull(signature);
assert.equal(isVariable, signature.isVariadic);
}
public verifyCurrentParameterHelpName(name: string) {
- this.taoInvalidReason = "verifyCurrentParameterHelpName NYI";
-
const activeParameter = this.getActiveParameter();
const activeParameterName = activeParameter.name;
assert.equal(activeParameterName, name);
}
public verifyCurrentParameterSpanIs(parameter: string) {
- this.taoInvalidReason = "verifyCurrentParameterSpanIs NYI";
-
const activeSignature = this.getActiveSignatureHelpItem();
const activeParameter = this.getActiveParameter();
assert.equal(ts.displayPartsToString(activeParameter.displayParts), parameter);
}
public verifyCurrentParameterHelpDocComment(docComment: string) {
- this.taoInvalidReason = "verifyCurrentParameterHelpDocComment NYI";
-
const activeParameter = this.getActiveParameter();
const activeParameterDocComment = activeParameter.documentation;
- assert.equal(ts.displayPartsToString(activeParameterDocComment), docComment, assertionMessage("current parameter Help DocComment"));
+ assert.equal(ts.displayPartsToString(activeParameterDocComment), docComment, this.assertionMessageAtLastKnownMarker("current parameter Help DocComment"));
}
public verifyCurrentSignatureHelpParameterCount(expectedCount: number) {
- this.taoInvalidReason = "verifyCurrentSignatureHelpParameterCount NYI";
-
assert.equal(this.getActiveSignatureHelpItem().parameters.length, expectedCount);
}
- public verifyCurrentSignatureHelpTypeParameterCount(expectedCount: number) {
- this.taoInvalidReason = "verifyCurrentSignatureHelpTypeParameterCount NYI";
-
- // assert.equal(this.getActiveSignatureHelpItem().typeParameters.length, expectedCount);
- }
-
public verifyCurrentSignatureHelpDocComment(docComment: string) {
- this.taoInvalidReason = "verifyCurrentSignatureHelpDocComment NYI";
-
const actualDocComment = this.getActiveSignatureHelpItem().documentation;
- assert.equal(ts.displayPartsToString(actualDocComment), docComment, assertionMessage("current signature help doc comment"));
+ assert.equal(ts.displayPartsToString(actualDocComment), docComment, this.assertionMessageAtLastKnownMarker("current signature help doc comment"));
}
public verifySignatureHelpCount(expected: number) {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
-
const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
const actual = help && help.items ? help.items.length : 0;
assert.equal(actual, expected);
}
public verifySignatureHelpArgumentCount(expected: number) {
- this.taoInvalidReason = "verifySignatureHelpArgumentCount NYI";
const signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
const actual = signatureHelpItems.argumentCount;
assert.equal(actual, expected);
}
public verifySignatureHelpPresent(shouldBePresent = true) {
- this.taoInvalidReason = "verifySignatureHelpPresent NYI";
-
const actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
if (shouldBePresent) {
if (!actual) {
@@ -1184,13 +1085,10 @@ namespace FourSlash {
}
public getBreakpointStatementLocation(pos: number) {
- this.taoInvalidReason = "getBreakpointStatementLocation NYI";
return this.languageService.getBreakpointStatementAtPosition(this.activeFile.fileName, pos);
}
public baselineCurrentFileBreakpointLocations() {
- this.taoInvalidReason = "baselineCurrentFileBreakpointLocations impossible";
-
Harness.Baseline.runBaseline(
"Breakpoint Locations for " + this.activeFile.fileName,
this.testData.globalOptions[metadataOptionNames.baselineFile],
@@ -1201,7 +1099,6 @@ namespace FourSlash {
}
public baselineGetEmitOutput() {
- this.taoInvalidReason = "baselineGetEmitOutput impossible";
// Find file to be emitted
const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on
@@ -1327,8 +1224,6 @@ namespace FourSlash {
}
public deleteChar(count = 1) {
- this.scenarioActions.push(``);
-
let offset = this.currentCaretPosition;
const ch = "";
@@ -1340,14 +1235,14 @@ namespace FourSlash {
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch);
if (i % checkCadence === 0) {
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
// Handle post-keystroke formatting
if (this.enableFormatting) {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
- offset += this.applyEdits(this.activeFile.fileName, edits, true);
+ offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
// this.checkPostEditInletiants();
}
}
@@ -1357,20 +1252,16 @@ namespace FourSlash {
this.currentCaretPosition = offset;
this.fixCaretPosition();
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
public replace(start: number, length: number, text: string) {
- this.taoInvalidReason = "replace NYI";
-
this.languageServiceAdapterHost.editScript(this.activeFile.fileName, start, start + length, text);
this.updateMarkersForEdit(this.activeFile.fileName, start, start + length, text);
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
public deleteCharBehindMarker(count = 1) {
- this.scenarioActions.push(``);
-
let offset = this.currentCaretPosition;
const ch = "";
const checkCadence = (count >> 2) + 1;
@@ -1382,14 +1273,14 @@ namespace FourSlash {
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch);
if (i % checkCadence === 0) {
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
// Handle post-keystroke formatting
if (this.enableFormatting) {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
- offset += this.applyEdits(this.activeFile.fileName, edits, true);
+ offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
}
}
}
@@ -1398,18 +1289,11 @@ namespace FourSlash {
this.currentCaretPosition = offset;
this.fixCaretPosition();
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
// Enters lines of text at the current caret position
public type(text: string) {
- if (text === "") {
- this.taoInvalidReason = "Test used empty-insert workaround.";
- }
- else {
- this.scenarioActions.push(``);
- }
-
return this.typeHighFidelity(text);
}
@@ -1440,7 +1324,7 @@ namespace FourSlash {
}
if (i % checkCadence === 0) {
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
// this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
// this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
}
@@ -1449,7 +1333,7 @@ namespace FourSlash {
if (this.enableFormatting) {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
- offset += this.applyEdits(this.activeFile.fileName, edits, true);
+ offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
// this.checkPostEditInletiants();
}
}
@@ -1459,26 +1343,24 @@ namespace FourSlash {
this.currentCaretPosition = offset;
this.fixCaretPosition();
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
// Enters text as if the user had pasted it
public paste(text: string) {
- this.scenarioActions.push(``);
-
const start = this.currentCaretPosition;
let offset = this.currentCaretPosition;
this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, text);
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, text);
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
offset += text.length;
// Handle formatting
if (this.enableFormatting) {
const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions);
if (edits.length) {
- offset += this.applyEdits(this.activeFile.fileName, edits, true);
- this.checkPostEditInletiants();
+ offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
+ this.checkPostEditInvariants();
}
}
@@ -1486,10 +1368,10 @@ namespace FourSlash {
this.currentCaretPosition = offset;
this.fixCaretPosition();
- this.checkPostEditInletiants();
+ this.checkPostEditInvariants();
}
- private checkPostEditInletiants() {
+ private checkPostEditInvariants() {
if (this.testType !== FourSlashTestType.Native) {
// getSourcefile() results can not be serialized. Only perform these verifications
// if running against a native LS object.
@@ -1560,18 +1442,14 @@ namespace FourSlash {
}
public formatDocument() {
- this.scenarioActions.push("");
-
const edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions);
- this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true);
+ this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
this.fixCaretPosition();
}
public formatSelection(start: number, end: number) {
- this.taoInvalidReason = "formatSelection NYI";
-
const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions);
- this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true);
+ this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
this.fixCaretPosition();
}
@@ -1603,13 +1481,6 @@ namespace FourSlash {
}
public goToDefinition(definitionIndex: number) {
- if (definitionIndex === 0) {
- this.scenarioActions.push("");
- }
- else {
- this.taoInvalidReason = "GoToDefinition not supported for non-zero definition indices";
- }
-
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
this.raiseError("goToDefinition failed - expected to at least one definition location but got 0");
@@ -1625,13 +1496,6 @@ namespace FourSlash {
}
public goToTypeDefinition(definitionIndex: number) {
- if (definitionIndex === 0) {
- this.scenarioActions.push("");
- }
- else {
- this.taoInvalidReason = "GoToTypeDefinition not supported for non-zero definition indices";
- }
-
const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
this.raiseError("goToTypeDefinition failed - expected to at least one definition location but got 0");
@@ -1647,8 +1511,6 @@ namespace FourSlash {
}
public verifyDefinitionLocationExists(negative: boolean) {
- this.taoInvalidReason = "verifyDefinitionLocationExists NYI";
-
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
const foundDefinitions = definitions && definitions.length;
@@ -1680,8 +1542,6 @@ namespace FourSlash {
}
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
- this.taoInvalidReason = "verifyDefinititionsInfo NYI";
-
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
const actualDefinitionName = definitions && definitions.length ? definitions[0].name : "";
const actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : "";
@@ -1706,8 +1566,6 @@ namespace FourSlash {
}
public verifyCaretAtMarker(markerName = "") {
- this.taoInvalidReason = "verifyCaretAtMarker NYI";
-
const pos = this.getMarkerByName(markerName);
if (pos.fileName !== this.activeFile.fileName) {
throw new Error(`verifyCaretAtMarker failed - expected to be in file "${pos.fileName}", but was in file "${this.activeFile.fileName}"`);
@@ -1726,8 +1584,6 @@ namespace FourSlash {
}
public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) {
- this.taoInvalidReason = "verifyIndentationAtCurrentPosition NYI";
-
const actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle);
const lineCol = this.getLineColStringAtPosition(this.currentCaretPosition);
if (actual !== numberOfSpaces) {
@@ -1736,8 +1592,6 @@ namespace FourSlash {
}
public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) {
- this.taoInvalidReason = "verifyIndentationAtPosition NYI";
-
const actual = this.getIndentation(fileName, position, indentStyle);
const lineCol = this.getLineColStringAtPosition(position);
if (actual !== numberOfSpaces) {
@@ -1746,8 +1600,6 @@ namespace FourSlash {
}
public verifyCurrentLineContent(text: string) {
- this.taoInvalidReason = "verifyCurrentLineContent NYI";
-
const actual = this.getCurrentLineContent();
if (actual !== text) {
throw new Error("verifyCurrentLineContent\n" +
@@ -1757,8 +1609,6 @@ namespace FourSlash {
}
public verifyCurrentFileContent(text: string) {
- this.taoInvalidReason = "verifyCurrentFileContent NYI";
-
const actual = this.getFileContent(this.activeFile.fileName);
const replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n");
if (replaceNewlines(actual) !== replaceNewlines(text)) {
@@ -1769,8 +1619,6 @@ namespace FourSlash {
}
public verifyTextAtCaretIs(text: string) {
- this.taoInvalidReason = "verifyCurrentFileContent NYI";
-
const actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length);
if (actual !== text) {
throw new Error("verifyTextAtCaretIs\n" +
@@ -1780,8 +1628,6 @@ namespace FourSlash {
}
public verifyCurrentNameOrDottedNameSpanText(text: string) {
- this.taoInvalidReason = "verifyCurrentNameOrDottedNameSpanText NYI";
-
const span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition);
if (!span) {
this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" +
@@ -1798,13 +1644,10 @@ namespace FourSlash {
}
private getNameOrDottedNameSpan(pos: number) {
- this.taoInvalidReason = "getNameOrDottedNameSpan NYI";
return this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, pos, pos);
}
public baselineCurrentFileNameOrDottedNameSpans() {
- this.taoInvalidReason = "baselineCurrentFileNameOrDottedNameSpans impossible";
-
Harness.Baseline.runBaseline(
"Name OrDottedNameSpans for " + this.activeFile.fileName,
this.testData.globalOptions[metadataOptionNames.baselineFile],
@@ -1898,8 +1741,6 @@ namespace FourSlash {
}
public verifyOutliningSpans(spans: TextSpan[]) {
- this.taoInvalidReason = "verifyOutliningSpans NYI";
-
const actual = this.languageService.getOutliningSpans(this.activeFile.fileName);
if (actual.length !== spans.length) {
@@ -1968,8 +1809,6 @@ namespace FourSlash {
}
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) {
- this.taoInvalidReason = "verifyMatchingBracePosition NYI";
-
const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
if (actual.length !== 2) {
@@ -1993,8 +1832,6 @@ namespace FourSlash {
}
public verifyNoMatchingBracePosition(bracePosition: number) {
- this.taoInvalidReason = "verifyNoMatchingBracePosition NYI";
-
const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
if (actual.length !== 0) {
@@ -2007,8 +1844,6 @@ namespace FourSlash {
Report an error if expected value and actual value do not match.
*/
public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string) {
- this.taoInvalidReason = "verifyNavigationItemsCount NYI";
-
const items = this.languageService.getNavigateToItems(searchValue);
let actual = 0;
let item: ts.NavigateToItem = null;
@@ -2037,8 +1872,6 @@ namespace FourSlash {
matchKind: string,
fileName?: string,
parentName?: string) {
- this.taoInvalidReason = "verifyNavigationItemsListContains NYI";
-
const items = this.languageService.getNavigateToItems(searchValue);
if (!items || items.length === 0) {
@@ -2063,8 +1896,6 @@ namespace FourSlash {
}
public verifyGetScriptLexicalStructureListCount(expected: number) {
- this.taoInvalidReason = "verifyNavigationItemsListContains impossible";
-
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
const actual = this.getNavigationBarItemsCount(items);
@@ -2086,8 +1917,6 @@ namespace FourSlash {
}
public verifyGetScriptLexicalStructureListContains(name: string, kind: string) {
- this.taoInvalidReason = "verifyGetScriptLexicalStructureListContains impossible";
-
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
if (!items || items.length === 0) {
@@ -2148,8 +1977,6 @@ namespace FourSlash {
}
public verifyOccurrencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) {
- this.taoInvalidReason = "verifyOccurrencesAtPositionListContains NYI";
-
const occurrences = this.getOccurrencesAtCurrentPosition();
if (!occurrences || occurrences.length === 0) {
@@ -2170,8 +1997,6 @@ namespace FourSlash {
}
public verifyOccurrencesAtPositionListCount(expectedCount: number) {
- this.taoInvalidReason = "verifyOccurrencesAtPositionListCount NYI";
-
const occurrences = this.getOccurrencesAtCurrentPosition();
const actualCount = occurrences ? occurrences.length : 0;
if (expectedCount !== actualCount) {
@@ -2185,8 +2010,6 @@ namespace FourSlash {
}
public verifyDocumentHighlightsAtPositionListContains(fileName: string, start: number, end: number, fileNamesToSearch: string[], kind?: string) {
- this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListContains NYI";
-
const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch);
if (!documentHighlights || documentHighlights.length === 0) {
@@ -2213,8 +2036,6 @@ namespace FourSlash {
}
public verifyDocumentHighlightsAtPositionListCount(expectedCount: number, fileNamesToSearch: string[]) {
- this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListCount NYI";
-
const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch);
const actualCount = documentHighlights
? documentHighlights.reduce((currentCount, { highlightSpans }) => currentCount + highlightSpans.length, 0)
@@ -2255,13 +2076,6 @@ namespace FourSlash {
}
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string) {
- this.scenarioActions.push("");
- this.scenarioActions.push(``);
-
- if (text || documentation || kind) {
- this.taoInvalidReason = "assertItemInCompletionList only supports the \"name\" parameter";
- }
-
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.name === name) {
@@ -2269,15 +2083,15 @@ namespace FourSlash {
const details = this.getCompletionEntryDetails(item.name);
if (documentation !== undefined) {
- assert.equal(ts.displayPartsToString(details.documentation), documentation, assertionMessage("completion item documentation for " + name));
+ assert.equal(ts.displayPartsToString(details.documentation), documentation, this.assertionMessageAtLastKnownMarker("completion item documentation for " + name));
}
if (text !== undefined) {
- assert.equal(ts.displayPartsToString(details.displayParts), text, assertionMessage("completion item detail text for " + name));
+ assert.equal(ts.displayPartsToString(details.displayParts), text, this.assertionMessageAtLastKnownMarker("completion item detail text for " + name));
}
}
if (kind !== undefined) {
- assert.equal(item.kind, kind, assertionMessage("completion item kind for " + name));
+ assert.equal(item.kind, kind, this.assertionMessageAtLastKnownMarker("completion item kind for " + name));
}
return;
@@ -2352,14 +2166,6 @@ namespace FourSlash {
return text.replace(/ /g, "\u00B7").replace(/\r/g, "\u00B6").replace(/\n/g, "\u2193\n").replace(/\t/g, "\u2192\ ");
}
- public getTestXmlData(): TestXmlData {
- return {
- actions: this.scenarioActions,
- invalidReason: this.taoInvalidReason,
- originalName: ""
- };
- }
-
public setCancelled(numberOfCalls: number): void {
this.cancellationToken.setCancelled(numberOfCalls);
}
@@ -2372,43 +2178,33 @@ namespace FourSlash {
// TOOD: should these just use the Harness's stdout/stderr?
const fsOutput = new Harness.Compiler.WriterAggregator();
const fsErrors = new Harness.Compiler.WriterAggregator();
- export let xmlData: TestXmlData[] = [];
export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) {
const content = Harness.IO.readFile(fileName);
- const xml = runFourSlashTestContent(basePath, testType, content, fileName);
- xmlData.push(xml);
+ runFourSlashTestContent(basePath, testType, content, fileName);
}
- // We don't want to recompile 'fourslash.ts' for every test, so
- // here we cache the JS output and reuse it for every test.
- let fourslashJsOutput: string;
- {
- const host = Harness.Compiler.createCompilerHost([{ unitName: Harness.Compiler.fourslashFileName, content: undefined }],
- (fn, contents) => fourslashJsOutput = contents,
- ts.ScriptTarget.Latest,
- Harness.IO.useCaseSensitiveFileNames());
-
- const program = ts.createProgram([Harness.Compiler.fourslashFileName], { noResolve: true, target: ts.ScriptTarget.ES3 }, host);
-
- program.emit(host.getSourceFile(Harness.Compiler.fourslashFileName, ts.ScriptTarget.ES3));
- }
-
-
- export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): TestXmlData {
+ export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): void {
// Parse out the files and their metadata
const testData = parseTestData(basePath, content, fileName);
- currentTestState = new TestState(basePath, testType, testData);
+ const state = new TestState(basePath, testType, testData);
let result = "";
+ const fourslashFile: Harness.Compiler.TestFile = {
+ unitName: Harness.Compiler.fourslashFileName,
+ content: undefined,
+ };
+ const testFile: Harness.Compiler.TestFile = {
+ unitName: fileName,
+ content: content
+ };
+
const host = Harness.Compiler.createCompilerHost(
- [
- { unitName: Harness.Compiler.fourslashFileName, content: undefined },
- { unitName: fileName, content: content }
- ],
+ [ fourslashFile, testFile ],
(fn, contents) => result = contents,
ts.ScriptTarget.Latest,
- Harness.IO.useCaseSensitiveFileNames());
+ Harness.IO.useCaseSensitiveFileNames(),
+ Harness.IO.getCurrentDirectory());
const program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host);
@@ -2421,22 +2217,32 @@ namespace FourSlash {
}
program.emit(sourceFile);
- result = result || ""; // Might have an empty fourslash file
- result = fourslashJsOutput + "\r\n" + result;
+ ts.Debug.assert(!!result);
+ runCode(result, state);
+ }
+ function runCode(code: string, state: TestState): void {
// Compile and execute the test
+ const wrappedCode =
+`(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) {
+${code}
+})`;
try {
- eval(result);
+ const test = new FourSlashInterface.Test(state);
+ const goTo = new FourSlashInterface.GoTo(state);
+ const verify = new FourSlashInterface.Verify(state);
+ const edit = new FourSlashInterface.Edit(state);
+ const debug = new FourSlashInterface.Debug(state);
+ const format = new FourSlashInterface.Format(state);
+ const cancellation = new FourSlashInterface.Cancellation(state);
+ const f = eval(wrappedCode);
+ f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlash.verifyOperationIsCancelled);
}
catch (err) {
// Debugging: FourSlash.currentTestState.printCurrentFileState();
throw err;
}
-
- const xmlData = currentTestState.getTestXmlData();
- xmlData.originalName = fileName;
- return xmlData;
}
function chompLeadingSpace(content: string) {
@@ -2604,7 +2410,7 @@ namespace FourSlash {
throw new Error(errorMessage);
}
- function recordObjectMarker(fileName: string, location: ILocationInformation, text: string, markerMap: MarkerMap, markers: Marker[]): Marker {
+ function recordObjectMarker(fileName: string, location: LocationInformation, text: string, markerMap: MarkerMap, markers: Marker[]): Marker {
let markerValue: any = undefined;
try {
// Attempt to parse the marker value as JSON
@@ -2635,7 +2441,7 @@ namespace FourSlash {
return marker;
}
- function recordMarker(fileName: string, location: ILocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker {
+ function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker {
const marker: Marker = {
fileName: fileName,
position: location.position
@@ -2664,10 +2470,10 @@ namespace FourSlash {
let output = "";
/// The current marker (or maybe multi-line comment?) we're parsing, possibly
- let openMarker: ILocationInformation = null;
+ let openMarker: LocationInformation = null;
/// A stack of the open range markers that are still unclosed
- const openRanges: IRangeLocationInformation[] = [];
+ const openRanges: RangeLocationInformation[] = [];
/// A list of ranges we've collected so far */
let localRanges: Range[] = [];
@@ -2853,3 +2659,632 @@ namespace FourSlash {
};
}
}
+
+namespace FourSlashInterface {
+ export class Test {
+ constructor(private state: FourSlash.TestState) {
+ }
+
+ public markers(): FourSlash.Marker[] {
+ return this.state.getMarkers();
+ }
+
+ public marker(name?: string): FourSlash.Marker {
+ return this.state.getMarkerByName(name);
+ }
+
+ public ranges(): FourSlash.Range[] {
+ return this.state.getRanges();
+ }
+
+ public markerByName(s: string): FourSlash.Marker {
+ return this.state.getMarkerByName(s);
+ }
+ }
+
+ export class GoTo {
+ constructor(private state: FourSlash.TestState) {
+ }
+ // Moves the caret to the specified marker,
+ // or the anonymous marker ('/**/') if no name
+ // is given
+ public marker(name?: string) {
+ this.state.goToMarker(name);
+ }
+
+ public bof() {
+ this.state.goToBOF();
+ }
+
+ public eof() {
+ this.state.goToEOF();
+ }
+
+ public definition(definitionIndex = 0) {
+ this.state.goToDefinition(definitionIndex);
+ }
+
+ public type(definitionIndex = 0) {
+ this.state.goToTypeDefinition(definitionIndex);
+ }
+
+ public position(position: number, fileIndex?: number): void;
+ public position(position: number, fileName?: string): void;
+ public position(position: number, fileNameOrIndex?: any): void {
+ if (fileNameOrIndex !== undefined) {
+ this.file(fileNameOrIndex);
+ }
+ this.state.goToPosition(position);
+ }
+
+ // Opens a file, given either its index as it
+ // appears in the test source, or its filename
+ // as specified in the test metadata
+ public file(index: number, content?: string): void;
+ public file(name: string, content?: string): void;
+ public file(indexOrName: any, content?: string): void {
+ this.state.openFile(indexOrName, content);
+ }
+ }
+
+ export class VerifyNegatable {
+ public not: VerifyNegatable;
+
+ constructor(protected state: FourSlash.TestState, private negative = false) {
+ if (!negative) {
+ this.not = new VerifyNegatable(state, true);
+ }
+ }
+
+ // Verifies the member list contains the specified symbol. The
+ // member list is brought up if necessary
+ public memberListContains(symbol: string, text?: string, documenation?: string, kind?: string) {
+ if (this.negative) {
+ this.state.verifyMemberListDoesNotContain(symbol);
+ }
+ else {
+ this.state.verifyMemberListContains(symbol, text, documenation, kind);
+ }
+ }
+
+ public memberListCount(expectedCount: number) {
+ this.state.verifyMemberListCount(expectedCount, this.negative);
+ }
+
+ // Verifies the completion list contains the specified symbol. The
+ // completion list is brought up if necessary
+ public completionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
+ if (this.negative) {
+ this.state.verifyCompletionListDoesNotContain(symbol, text, documentation, kind);
+ }
+ else {
+ this.state.verifyCompletionListContains(symbol, text, documentation, kind);
+ }
+ }
+
+ // Verifies the completion list items count to be greater than the specified amount. The
+ // completion list is brought up if necessary
+ public completionListItemsCountIsGreaterThan(count: number) {
+ this.state.verifyCompletionListItemsCountIsGreaterThan(count, this.negative);
+ }
+
+ public completionListIsEmpty() {
+ this.state.verifyCompletionListIsEmpty(this.negative);
+ }
+
+ public completionListAllowsNewIdentifier() {
+ this.state.verifyCompletionListAllowsNewIdentifier(this.negative);
+ }
+
+ public memberListIsEmpty() {
+ this.state.verifyMemberListIsEmpty(this.negative);
+ }
+
+ public referencesCountIs(count: number) {
+ this.state.verifyReferencesCountIs(count, /*localFilesOnly*/ false);
+ }
+
+ public referencesAtPositionContains(range: FourSlash.Range, isWriteAccess?: boolean) {
+ this.state.verifyReferencesAtPositionListContains(range.fileName, range.start, range.end, isWriteAccess);
+ }
+
+ public signatureHelpPresent() {
+ this.state.verifySignatureHelpPresent(!this.negative);
+ }
+
+ public errorExistsBetweenMarkers(startMarker: string, endMarker: string) {
+ this.state.verifyErrorExistsBetweenMarkers(startMarker, endMarker, !this.negative);
+ }
+
+ public errorExistsAfterMarker(markerName = "") {
+ this.state.verifyErrorExistsAfterMarker(markerName, !this.negative, /*after*/ true);
+ }
+
+ public errorExistsBeforeMarker(markerName = "") {
+ this.state.verifyErrorExistsAfterMarker(markerName, !this.negative, /*after*/ false);
+ }
+
+ public quickInfoIs(expectedText?: string, expectedDocumentation?: string) {
+ this.state.verifyQuickInfoString(this.negative, expectedText, expectedDocumentation);
+ }
+
+ public quickInfoExists() {
+ this.state.verifyQuickInfoExists(this.negative);
+ }
+
+ public definitionCountIs(expectedCount: number) {
+ this.state.verifyDefinitionsCount(this.negative, expectedCount);
+ }
+
+ public typeDefinitionCountIs(expectedCount: number) {
+ this.state.verifyTypeDefinitionsCount(this.negative, expectedCount);
+ }
+
+ public definitionLocationExists() {
+ this.state.verifyDefinitionLocationExists(this.negative);
+ }
+
+ public verifyDefinitionsName(name: string, containerName: string) {
+ this.state.verifyDefinitionsName(this.negative, name, containerName);
+ }
+ }
+
+ export class Verify extends VerifyNegatable {
+ constructor(state: FourSlash.TestState) {
+ super(state);
+ }
+
+ public caretAtMarker(markerName?: string) {
+ this.state.verifyCaretAtMarker(markerName);
+ }
+
+ public indentationIs(numberOfSpaces: number) {
+ this.state.verifyIndentationAtCurrentPosition(numberOfSpaces);
+ }
+
+ public indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle = ts.IndentStyle.Smart) {
+ this.state.verifyIndentationAtPosition(fileName, position, numberOfSpaces, indentStyle);
+ }
+
+ public textAtCaretIs(text: string) {
+ this.state.verifyTextAtCaretIs(text);
+ }
+
+ /**
+ * Compiles the current file and evaluates 'expr' in a context containing
+ * the emitted output, then compares (using ===) the result of that expression
+ * to 'value'. Do not use this function with external modules as it is not supported.
+ */
+ public eval(expr: string, value: any) {
+ this.state.verifyEval(expr, value);
+ }
+
+ public currentLineContentIs(text: string) {
+ this.state.verifyCurrentLineContent(text);
+ }
+
+ public currentFileContentIs(text: string) {
+ this.state.verifyCurrentFileContent(text);
+ }
+
+ public verifyGetEmitOutputForCurrentFile(expected: string): void {
+ this.state.verifyGetEmitOutputForCurrentFile(expected);
+ }
+
+ public verifyGetEmitOutputContentsForCurrentFile(expected: ts.OutputFile[]): void {
+ this.state.verifyGetEmitOutputContentsForCurrentFile(expected);
+ }
+
+ public currentParameterHelpArgumentNameIs(name: string) {
+ this.state.verifyCurrentParameterHelpName(name);
+ }
+
+ public currentParameterSpanIs(parameter: string) {
+ this.state.verifyCurrentParameterSpanIs(parameter);
+ }
+
+ public currentParameterHelpArgumentDocCommentIs(docComment: string) {
+ this.state.verifyCurrentParameterHelpDocComment(docComment);
+ }
+
+ public currentSignatureHelpDocCommentIs(docComment: string) {
+ this.state.verifyCurrentSignatureHelpDocComment(docComment);
+ }
+
+ public signatureHelpCountIs(expected: number) {
+ this.state.verifySignatureHelpCount(expected);
+ }
+
+ public signatureHelpArgumentCountIs(expected: number) {
+ this.state.verifySignatureHelpArgumentCount(expected);
+ }
+
+ public currentSignatureParameterCountIs(expected: number) {
+ this.state.verifyCurrentSignatureHelpParameterCount(expected);
+ }
+
+ public currentSignatureHelpIs(expected: string) {
+ this.state.verifyCurrentSignatureHelpIs(expected);
+ }
+
+ public numberOfErrorsInCurrentFile(expected: number) {
+ this.state.verifyNumberOfErrorsInCurrentFile(expected);
+ }
+
+ public baselineCurrentFileBreakpointLocations() {
+ this.state.baselineCurrentFileBreakpointLocations();
+ }
+
+ public baselineCurrentFileNameOrDottedNameSpans() {
+ this.state.baselineCurrentFileNameOrDottedNameSpans();
+ }
+
+ public baselineGetEmitOutput() {
+ this.state.baselineGetEmitOutput();
+ }
+
+ public nameOrDottedNameSpanTextIs(text: string) {
+ this.state.verifyCurrentNameOrDottedNameSpanText(text);
+ }
+
+ public outliningSpansInCurrentFile(spans: FourSlash.TextSpan[]) {
+ this.state.verifyOutliningSpans(spans);
+ }
+
+ public todoCommentsInCurrentFile(descriptors: string[]) {
+ this.state.verifyTodoComments(descriptors, this.state.getRanges());
+ }
+
+ public matchingBracePositionInCurrentFile(bracePosition: number, expectedMatchPosition: number) {
+ this.state.verifyMatchingBracePosition(bracePosition, expectedMatchPosition);
+ }
+
+ public noMatchingBracePositionInCurrentFile(bracePosition: number) {
+ this.state.verifyNoMatchingBracePosition(bracePosition);
+ }
+
+ public DocCommentTemplate(expectedText: string, expectedOffset: number, empty?: boolean) {
+ this.state.verifyDocCommentTemplate(empty ? undefined : { newText: expectedText, caretOffset: expectedOffset });
+ }
+
+ public noDocCommentTemplate() {
+ this.DocCommentTemplate(/*expectedText*/ undefined, /*expectedOffset*/ undefined, /*empty*/ true);
+ }
+
+ public getScriptLexicalStructureListCount(count: number) {
+ this.state.verifyGetScriptLexicalStructureListCount(count);
+ }
+
+ // TODO: figure out what to do with the unused arguments.
+ public getScriptLexicalStructureListContains(
+ name: string,
+ kind: string,
+ fileName?: string,
+ parentName?: string,
+ isAdditionalSpan?: boolean,
+ markerPosition?: number) {
+ this.state.verifyGetScriptLexicalStructureListContains(name, kind);
+ }
+
+ public navigationItemsListCount(count: number, searchValue: string, matchKind?: string) {
+ this.state.verifyNavigationItemsCount(count, searchValue, matchKind);
+ }
+
+ public navigationItemsListContains(
+ name: string,
+ kind: string,
+ searchValue: string,
+ matchKind: string,
+ fileName?: string,
+ parentName?: string) {
+ this.state.verifyNavigationItemsListContains(
+ name,
+ kind,
+ searchValue,
+ matchKind,
+ fileName,
+ parentName);
+ }
+
+ public occurrencesAtPositionContains(range: FourSlash.Range, isWriteAccess?: boolean) {
+ this.state.verifyOccurrencesAtPositionListContains(range.fileName, range.start, range.end, isWriteAccess);
+ }
+
+ public occurrencesAtPositionCount(expectedCount: number) {
+ this.state.verifyOccurrencesAtPositionListCount(expectedCount);
+ }
+
+ public documentHighlightsAtPositionContains(range: FourSlash.Range, fileNamesToSearch: string[], kind?: string) {
+ this.state.verifyDocumentHighlightsAtPositionListContains(range.fileName, range.start, range.end, fileNamesToSearch, kind);
+ }
+
+ public documentHighlightsAtPositionCount(expectedCount: number, fileNamesToSearch: string[]) {
+ this.state.verifyDocumentHighlightsAtPositionListCount(expectedCount, fileNamesToSearch);
+ }
+
+ public completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string) {
+ this.state.verifyCompletionEntryDetails(entryName, text, documentation, kind);
+ }
+
+ /**
+ * This method *requires* a contiguous, complete, and ordered stream of classifications for a file.
+ */
+ public syntacticClassificationsAre(...classifications: { classificationType: string; text: string }[]) {
+ this.state.verifySyntacticClassifications(classifications);
+ }
+
+ /**
+ * This method *requires* an ordered stream of classifications for a file, and spans are highly recommended.
+ */
+ public semanticClassificationsAre(...classifications: { classificationType: string; text: string; textSpan?: FourSlash.TextSpan }[]) {
+ this.state.verifySemanticClassifications(classifications);
+ }
+
+ public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) {
+ this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers);
+ }
+
+ public renameInfoFailed(message?: string) {
+ this.state.verifyRenameInfoFailed(message);
+ }
+
+ public renameLocations(findInStrings: boolean, findInComments: boolean) {
+ this.state.verifyRenameLocations(findInStrings, findInComments);
+ }
+
+ public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; },
+ displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[]) {
+ this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation);
+ }
+
+ public getSyntacticDiagnostics(expected: string) {
+ this.state.getSyntacticDiagnostics(expected);
+ }
+
+ public getSemanticDiagnostics(expected: string) {
+ this.state.getSemanticDiagnostics(expected);
+ }
+
+ public ProjectInfo(expected: string []) {
+ this.state.verifyProjectInfo(expected);
+ }
+ }
+
+ export class Edit {
+ constructor(private state: FourSlash.TestState) {
+ }
+ public backspace(count?: number) {
+ this.state.deleteCharBehindMarker(count);
+ }
+
+ public deleteAtCaret(times?: number) {
+ this.state.deleteChar(times);
+ }
+
+ public replace(start: number, length: number, text: string) {
+ this.state.replace(start, length, text);
+ }
+
+ public paste(text: string) {
+ this.state.paste(text);
+ }
+
+ public insert(text: string) {
+ this.insertLines(text);
+ }
+
+ public insertLine(text: string) {
+ this.insertLines(text + "\n");
+ }
+
+ public insertLines(...lines: string[]) {
+ this.state.type(lines.join("\n"));
+ }
+
+ public moveRight(count?: number) {
+ this.state.moveCaretRight(count);
+ }
+
+ public moveLeft(count?: number) {
+ if (typeof count === "undefined") {
+ count = 1;
+ }
+ this.state.moveCaretRight(count * -1);
+ }
+
+ public enableFormatting() {
+ this.state.enableFormatting = true;
+ }
+
+ public disableFormatting() {
+ this.state.enableFormatting = false;
+ }
+ }
+
+ export class Debug {
+ constructor(private state: FourSlash.TestState) {
+ }
+
+ public printCurrentParameterHelp() {
+ this.state.printCurrentParameterHelp();
+ }
+
+ public printCurrentFileState() {
+ this.state.printCurrentFileState();
+ }
+
+ public printCurrentFileStateWithWhitespace() {
+ this.state.printCurrentFileState(/*makeWhitespaceVisible*/true);
+ }
+
+ public printCurrentFileStateWithoutCaret() {
+ this.state.printCurrentFileState(/*makeWhitespaceVisible*/false, /*makeCaretVisible*/false);
+ }
+
+ public printCurrentQuickInfo() {
+ this.state.printCurrentQuickInfo();
+ }
+
+ public printCurrentSignatureHelp() {
+ this.state.printCurrentSignatureHelp();
+ }
+
+ public printMemberListMembers() {
+ this.state.printMemberListMembers();
+ }
+
+ public printCompletionListMembers() {
+ this.state.printCompletionListMembers();
+ }
+
+ public printBreakpointLocation(pos: number) {
+ this.state.printBreakpointLocation(pos);
+ }
+ public printBreakpointAtCurrentLocation() {
+ this.state.printBreakpointAtCurrentLocation();
+ }
+
+ public printNameOrDottedNameSpans(pos: number) {
+ this.state.printNameOrDottedNameSpans(pos);
+ }
+
+ public printErrorList() {
+ this.state.printErrorList();
+ }
+
+ public printNavigationItems(searchValue = ".*") {
+ this.state.printNavigationItems(searchValue);
+ }
+
+ public printScriptLexicalStructureItems() {
+ this.state.printScriptLexicalStructureItems();
+ }
+
+ public printReferences() {
+ this.state.printReferences();
+ }
+
+ public printContext() {
+ this.state.printContext();
+ }
+ }
+
+ export class Format {
+ constructor(private state: FourSlash.TestState) {
+ }
+
+ public document() {
+ this.state.formatDocument();
+ }
+
+ public copyFormatOptions(): ts.FormatCodeOptions {
+ return this.state.copyFormatOptions();
+ }
+
+ public setFormatOptions(options: ts.FormatCodeOptions) {
+ return this.state.setFormatOptions(options);
+ }
+
+ public selection(startMarker: string, endMarker: string) {
+ this.state.formatSelection(this.state.getMarkerByName(startMarker).position, this.state.getMarkerByName(endMarker).position);
+ }
+
+ public setOption(name: string, value: number): void;
+ public setOption(name: string, value: string): void;
+ public setOption(name: string, value: boolean): void;
+ public setOption(name: string, value: any): void {
+ this.state.formatCodeOptions[name] = value;
+ }
+ }
+
+ export class Cancellation {
+ constructor(private state: FourSlash.TestState) {
+ }
+
+ public resetCancelled() {
+ this.state.resetCancelled();
+ }
+
+ public setCancelled(numberOfCalls = 0) {
+ this.state.setCancelled(numberOfCalls);
+ }
+ }
+
+ export namespace Classification {
+ export function comment(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("comment", text, position);
+ }
+
+ export function identifier(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("identifier", text, position);
+ }
+
+ export function keyword(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("keyword", text, position);
+ }
+
+ export function numericLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("numericLiteral", text, position);
+ }
+
+ export function operator(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("operator", text, position);
+ }
+
+ export function stringLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("stringLiteral", text, position);
+ }
+
+ export function whiteSpace(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("whiteSpace", text, position);
+ }
+
+ export function text(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("text", text, position);
+ }
+
+ export function punctuation(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("punctuation", text, position);
+ }
+
+ export function docCommentTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("docCommentTagName", text, position);
+ }
+
+ export function className(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("className", text, position);
+ }
+
+ export function enumName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("enumName", text, position);
+ }
+
+ export function interfaceName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("interfaceName", text, position);
+ }
+
+ export function moduleName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("moduleName", text, position);
+ }
+
+ export function typeParameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("typeParameterName", text, position);
+ }
+
+ export function parameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("parameterName", text, position);
+ }
+
+ export function typeAliasName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
+ return getClassification("typeAliasName", text, position);
+ }
+
+ function getClassification(type: string, text: string, position?: number) {
+ return {
+ classificationType: type,
+ text: text,
+ textSpan: position === undefined ? undefined : { start: position, end: position + text.length }
+ };
+ }
+ }
+}
diff --git a/src/harness/fourslashRunner.ts b/src/harness/fourslashRunner.ts
index 7228f06c20f..84e352359c4 100644
--- a/src/harness/fourslashRunner.ts
+++ b/src/harness/fourslashRunner.ts
@@ -58,56 +58,6 @@ class FourSlashRunner extends RunnerBase {
}
});
});
-
- describe("Generate Tao XML", () => {
- const invalidReasons: any = {};
- FourSlash.xmlData.forEach(xml => {
- if (xml.invalidReason !== null) {
- invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1;
- }
- });
- const invalidReport: { reason: string; count: number }[] = [];
- for (const reason in invalidReasons) {
- if (invalidReasons.hasOwnProperty(reason)) {
- invalidReport.push({ reason: reason, count: invalidReasons[reason] });
- }
- }
- invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
-
- const lines: string[] = [];
- lines.push("");
- lines.push("");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- FourSlash.xmlData.forEach(xml => {
- if (xml.invalidReason !== null) {
- lines.push("");
- }
- else {
- lines.push(" ");
- xml.actions.forEach(action => {
- lines.push(" " + action);
- });
- lines.push(" ");
- }
- });
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push(" ");
- lines.push("");
- Harness.IO.writeFile("built/local/fourslash.xml", lines.join("\r\n"));
- });
});
}
}
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 16c3b2d3488..15f3813e54d 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -176,7 +176,9 @@ namespace Utils {
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
for (const childName in node) {
- if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator") {
+ if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" ||
+ // for now ignore jsdoc comments
+ childName === "jsDocComment") {
continue;
}
const child = (node)[childName];
@@ -628,7 +630,7 @@ namespace Harness {
function getResolvedPathFromServer(path: string) {
const xhr = new XMLHttpRequest();
try {
- xhr.open("GET", path + "?resolve", false);
+ xhr.open("GET", path + "?resolve", /*async*/ false);
xhr.send();
}
catch (e) {
@@ -647,7 +649,7 @@ namespace Harness {
export function getFileFromServerSync(url: string): XHRResponse {
const xhr = new XMLHttpRequest();
try {
- xhr.open("GET", url, false);
+ xhr.open("GET", url, /*async*/ false);
xhr.send();
}
catch (e) {
@@ -662,7 +664,7 @@ namespace Harness {
const xhr = new XMLHttpRequest();
try {
const actionMsg = "?action=" + action;
- xhr.open("POST", url + actionMsg, false);
+ xhr.open("POST", url + actionMsg, /*async*/ false);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send(contents);
}
@@ -767,26 +769,9 @@ namespace Harness {
}
namespace Harness {
- let tcServicesFileName = "typescriptServices.js";
-
- export let libFolder: string;
- switch (Utils.getExecutionEnvironment()) {
- case Utils.ExecutionEnvironment.CScript:
- libFolder = "built/local/";
- tcServicesFileName = "built/local/typescriptServices.js";
- break;
- case Utils.ExecutionEnvironment.Node:
- libFolder = "built/local/";
- tcServicesFileName = "built/local/typescriptServices.js";
- break;
- case Utils.ExecutionEnvironment.Browser:
- libFolder = "built/local/";
- tcServicesFileName = "built/local/typescriptServices.js";
- break;
- default:
- throw new Error("Unknown context");
- }
- export let tcServicesFile = IO.readFile(tcServicesFileName);
+ export const libFolder = "built/local/";
+ const tcServicesFileName = ts.combinePaths(libFolder, "typescriptServices.js");
+ export const tcServicesFile = IO.readFile(tcServicesFileName);
export interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
@@ -827,57 +812,14 @@ namespace Harness {
}
}
- export interface IEmitterIOHost {
- writeFile(path: string, contents: string, writeByteOrderMark: boolean): void;
- resolvePath(path: string): string;
- }
-
- /** Mimics having multiple files, later concatenated to a single file. */
- export class EmitterIOHost implements IEmitterIOHost {
- private fileCollection: any = {};
-
- /** create file gets the whole path to create, so this works as expected with the --out parameter */
- public writeFile(s: string, contents: string, writeByteOrderMark: boolean): void {
- let writer: ITextWriter;
- if (this.fileCollection[s]) {
- writer = this.fileCollection[s];
- }
- else {
- writer = new Harness.Compiler.WriterAggregator();
- this.fileCollection[s] = writer;
- }
-
- writer.Write(contents);
- writer.Close();
- }
-
- public resolvePath(s: string) { return s; }
-
- public reset() { this.fileCollection = {}; }
-
- public toArray(): { fileName: string; file: WriterAggregator; }[] {
- const result: { fileName: string; file: WriterAggregator; }[] = [];
- for (const p in this.fileCollection) {
- if (this.fileCollection.hasOwnProperty(p)) {
- const current = this.fileCollection[p];
- if (current.lines.length > 0) {
- if (p.indexOf(".d.ts") !== -1) { current.lines.unshift(["////[", Path.getFileName(p), "]"].join("")); }
- result.push({ fileName: p, file: this.fileCollection[p] });
- }
- }
- }
- return result;
- }
- }
-
export function createSourceFileAndAssertInvariants(
fileName: string,
sourceText: string,
languageVersion: ts.ScriptTarget) {
- // We'll only assert inletiants outside of light mode.
+ // We'll only assert invariants outside of light mode.
const shouldAssertInvariants = !Harness.lightMode;
- // Only set the parent nodes if we're asserting inletiants. We don't need them otherwise.
+ // Only set the parent nodes if we're asserting invariants. We don't need them otherwise.
const result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
if (shouldAssertInvariants) {
@@ -890,12 +832,12 @@ namespace Harness {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
- export let defaultLibFileName = "lib.d.ts";
- export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
- export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
+ export const defaultLibFileName = "lib.d.ts";
+ export const defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
+ export const defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
// Cache these between executions so we don't have to re-parse them for every test
- export let fourslashFileName = "fourslash.ts";
+ export const fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
@@ -903,41 +845,32 @@ namespace Harness {
}
export function createCompilerHost(
- inputFiles: { unitName: string; content: string; }[],
+ inputFiles: TestFile[],
writeFile: (fn: string, contents: string, writeByteOrderMark: boolean) => void,
scriptTarget: ts.ScriptTarget,
useCaseSensitiveFileNames: boolean,
// the currentDirectory is needed for rwcRunner to passed in specified current directory to compiler host
- currentDirectory?: string,
+ currentDirectory: string,
newLineKind?: ts.NewLineKind): ts.CompilerHost {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
- function getCanonicalFileName(fileName: string): string {
- return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ const getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
- const filemap: { [fileName: string]: ts.SourceFile; } = {};
- const getCurrentDirectory = currentDirectory === undefined ? Harness.IO.getCurrentDirectory : () => currentDirectory;
-
- // Register input files
- function register(file: { unitName: string; content: string; }) {
+ const fileMap: ts.FileMap = ts.createFileMap();
+ for (const file of inputFiles) {
if (file.content !== undefined) {
const fileName = ts.normalizePath(file.unitName);
const sourceFile = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget);
- filemap[getCanonicalFileName(fileName)] = sourceFile;
- filemap[getCanonicalFileName(ts.getNormalizedAbsolutePath(fileName, getCurrentDirectory()))] = sourceFile;
+ const path = ts.toPath(file.unitName, currentDirectory, getCanonicalFileName);
+ fileMap.set(path, sourceFile);
}
- };
- inputFiles.forEach(register);
+ }
function getSourceFile(fn: string, languageVersion: ts.ScriptTarget) {
fn = ts.normalizePath(fn);
- if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
- return filemap[getCanonicalFileName(fn)];
- }
- else if (currentDirectory) {
- const canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
- return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
+ const path = ts.toPath(fn, currentDirectory, getCanonicalFileName);
+ if (fileMap.contains(path)) {
+ return fileMap.get(path);
}
else if (fn === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
@@ -959,7 +892,7 @@ namespace Harness {
Harness.IO.newLine();
return {
- getCurrentDirectory,
+ getCurrentDirectory: () => currentDirectory,
getSourceFile,
getDefaultLibFileName: options => defaultLibFileName,
writeFile,
@@ -975,6 +908,7 @@ namespace Harness {
useCaseSensitiveFileNames?: boolean;
includeBuiltFile?: string;
baselineFile?: string;
+ libFiles?: string;
}
// Additional options not already in ts.optionDeclarations
@@ -984,6 +918,7 @@ namespace Harness {
{ name: "baselineFile", type: "string" },
{ name: "includeBuiltFile", type: "string" },
{ name: "fileName", type: "string" },
+ { name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" }
];
@@ -1034,177 +969,144 @@ namespace Harness {
}
}
- export class HarnessCompiler {
- private inputFiles: { unitName: string; content: string }[] = [];
- private compileOptions: ts.CompilerOptions;
- private settings: Harness.TestCaseParser.CompilerSettings = {};
+ export interface TestFile {
+ unitName: string;
+ content: string;
+ }
- private lastErrors: ts.Diagnostic[];
+ export interface CompilationOutput {
+ result: CompilerResult;
+ options: ts.CompilerOptions & HarnessOptions;
+ }
- public reset() {
- this.inputFiles = [];
- this.settings = {};
- this.lastErrors = [];
+ export function compileFiles(
+ inputFiles: TestFile[],
+ otherFiles: TestFile[],
+ harnessSettings: TestCaseParser.CompilerSettings,
+ compilerOptions: ts.CompilerOptions,
+ // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
+ currentDirectory: string): CompilationOutput {
+
+ const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.clone(compilerOptions) : { noResolve: false };
+ options.target = options.target || ts.ScriptTarget.ES3;
+ options.module = options.module || ts.ModuleKind.None;
+ options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
+ options.noErrorTruncation = true;
+ options.skipDefaultLibCheck = true;
+
+ currentDirectory = currentDirectory || Harness.IO.getCurrentDirectory();
+
+ // Parse settings
+ if (harnessSettings) {
+ setCompilerOptionsFromHarnessSetting(harnessSettings, options);
}
- public reportCompilationErrors() {
- return this.lastErrors;
+ const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
+ const programFiles: TestFile[] = inputFiles.slice();
+ // Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
+ // Treat them as library files, so include them in build, but not in baselines.
+ if (options.includeBuiltFile) {
+ const builtFileName = ts.combinePaths(libFolder, options.includeBuiltFile);
+ const builtFile: TestFile = {
+ unitName: builtFileName,
+ content: normalizeLineEndings(IO.readFile(builtFileName), Harness.IO.newLine()),
+ };
+ programFiles.push(builtFile);
}
- public setCompilerSettings(tcSettings: Harness.TestCaseParser.CompilerSettings) {
- this.settings = tcSettings;
- }
+ const fileOutputs: GeneratedFile[] = [];
- public addInputFiles(files: { unitName: string; content: string }[]) {
- files.forEach(file => this.addInputFile(file));
- }
-
- public addInputFile(file: { unitName: string; content: string }) {
- this.inputFiles.push(file);
- }
-
- public setCompilerOptions(options?: ts.CompilerOptions) {
- this.compileOptions = options || { noResolve: false };
- }
-
- public emitAll(ioHost?: IEmitterIOHost) {
- this.compileFiles(this.inputFiles,
- /*otherFiles*/ [],
- /*onComplete*/ result => {
- result.files.forEach(writeFile);
- result.declFilesCode.forEach(writeFile);
- result.sourceMaps.forEach(writeFile);
- },
- /*settingsCallback*/ () => { },
- this.compileOptions);
-
- function writeFile(file: GeneratedFile) {
- ioHost.writeFile(file.fileName, file.code, false);
+ // Files from tests\lib that are requested by "@libFiles"
+ if (options.libFiles) {
+ for (const fileName of options.libFiles.split(",")) {
+ const libFileName = "tests/lib/" + fileName;
+ programFiles.push({ unitName: libFileName, content: normalizeLineEndings(IO.readFile(libFileName), Harness.IO.newLine()) });
}
}
- public compileFiles(inputFiles: { unitName: string; content: string }[],
- otherFiles: { unitName: string; content: string }[],
- onComplete: (result: CompilerResult, program: ts.Program) => void,
- settingsCallback?: (settings: ts.CompilerOptions) => void,
- options?: ts.CompilerOptions & HarnessOptions,
- // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
- currentDirectory?: string) {
- options = options || { noResolve: false };
- options.target = options.target || ts.ScriptTarget.ES3;
- options.module = options.module || ts.ModuleKind.None;
- options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
- options.noErrorTruncation = true;
- options.skipDefaultLibCheck = true;
+ const programFileNames = programFiles.map(file => file.unitName);
- if (settingsCallback) {
- settingsCallback(null);
- }
+ const compilerHost = createCompilerHost(
+ programFiles.concat(otherFiles),
+ (fileName, code, writeByteOrderMark) => fileOutputs.push({ fileName, code, writeByteOrderMark }),
+ options.target,
+ useCaseSensitiveFileNames,
+ currentDirectory,
+ options.newLine);
+ const program = ts.createProgram(programFileNames, options, compilerHost);
- const newLine = "\r\n";
+ const emitResult = program.emit();
- // Parse settings
- setCompilerOptionsFromHarnessSetting(this.settings, options);
+ const errors = ts.getPreEmitDiagnostics(program);
- // Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
- // Treat them as library files, so include them in build, but not in baselines.
- const includeBuiltFiles: { unitName: string; content: string }[] = [];
- if (options.includeBuiltFile) {
- const builtFileName = libFolder + options.includeBuiltFile;
- includeBuiltFiles.push({ unitName: builtFileName, content: normalizeLineEndings(IO.readFile(builtFileName), newLine) });
- }
+ const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps);
+ return { result, options };
+ }
- const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
-
- const fileOutputs: GeneratedFile[] = [];
-
- const programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
-
- const compilerHost = createCompilerHost(
- inputFiles.concat(includeBuiltFiles).concat(otherFiles),
- (fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
- options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine);
- const program = ts.createProgram(programFiles, options, compilerHost);
-
- const emitResult = program.emit();
-
- const errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
- this.lastErrors = errors;
-
- const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps);
- onComplete(result, program);
-
- return options;
+ export function compileDeclarationFiles(inputFiles: TestFile[],
+ otherFiles: TestFile[],
+ result: CompilerResult,
+ harnessSettings: TestCaseParser.CompilerSettings & HarnessOptions,
+ options: ts.CompilerOptions,
+ // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
+ currentDirectory: string) {
+ if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
+ throw new Error("There were no errors and declFiles generated did not match number of js files generated");
}
- public compileDeclarationFiles(inputFiles: { unitName: string; content: string; }[],
- otherFiles: { unitName: string; content: string; }[],
- result: CompilerResult,
- settingsCallback?: (settings: ts.CompilerOptions) => void,
- options?: ts.CompilerOptions,
- // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
- currentDirectory?: string) {
- if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
- throw new Error("There were no errors and declFiles generated did not match number of js files generated");
+ const declInputFiles: TestFile[] = [];
+ const declOtherFiles: TestFile[] = [];
+
+ // if the .d.ts is non-empty, confirm it compiles correctly as well
+ if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
+ ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
+ ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
+ const output = compileFiles(declInputFiles, declOtherFiles, harnessSettings, options, currentDirectory);
+ return { declInputFiles, declOtherFiles, declResult: output.result };
+ }
+
+ function addDtsFile(file: TestFile, dtsFiles: TestFile[]) {
+ if (isDTS(file.unitName)) {
+ dtsFiles.push(file);
}
-
- const declInputFiles: { unitName: string; content: string }[] = [];
- const declOtherFiles: { unitName: string; content: string }[] = [];
- let declResult: Harness.Compiler.CompilerResult;
-
- // if the .d.ts is non-empty, confirm it compiles correctly as well
- if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
- ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
- ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
- this.compileFiles(declInputFiles, declOtherFiles, function (compileResult) { declResult = compileResult; },
- settingsCallback, options, currentDirectory);
-
- return { declInputFiles, declOtherFiles, declResult };
- }
-
- function addDtsFile(file: { unitName: string; content: string }, dtsFiles: { unitName: string; content: string }[]) {
- if (isDTS(file.unitName)) {
- dtsFiles.push(file);
- }
- else if (isTS(file.unitName)) {
- const declFile = findResultCodeFile(file.unitName);
- if (declFile && !findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
- dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
- }
- }
-
- function findResultCodeFile(fileName: string) {
- const sourceFile = result.program.getSourceFile(fileName);
- assert(sourceFile, "Program has no source file with name '" + fileName + "'");
- // Is this file going to be emitted separately
- let sourceFileName: string;
- const outFile = options.outFile || options.out;
- if (ts.isExternalModule(sourceFile) || !outFile) {
- if (options.outDir) {
- let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
- sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
- sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
- }
- else {
- sourceFileName = sourceFile.fileName;
- }
- }
- else {
- // Goes to single --out file
- sourceFileName = outFile;
- }
-
- const dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
-
- return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
- }
-
- function findUnit(fileName: string, units: { unitName: string; content: string; }[]) {
- return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
+ else if (isTS(file.unitName)) {
+ const declFile = findResultCodeFile(file.unitName);
+ if (declFile && !findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
+ dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
}
}
}
+
+ function findResultCodeFile(fileName: string) {
+ const sourceFile = result.program.getSourceFile(fileName);
+ assert(sourceFile, "Program has no source file with name '" + fileName + "'");
+ // Is this file going to be emitted separately
+ let sourceFileName: string;
+ const outFile = options.outFile || options.out;
+ if (!outFile) {
+ if (options.outDir) {
+ let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
+ sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
+ sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
+ }
+ else {
+ sourceFileName = sourceFile.fileName;
+ }
+ }
+ else {
+ // Goes to single --out file
+ sourceFileName = outFile;
+ }
+
+ const dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
+
+ return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
+ }
+
+ function findUnit(fileName: string, units: TestFile[]) {
+ return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
+ }
}
function normalizeLineEndings(text: string, lineEnding: string): string {
@@ -1230,7 +1132,7 @@ namespace Harness {
return errorOutput;
}
- export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: ts.Diagnostic[]) {
+ export function getErrorBaseline(inputFiles: TestFile[], diagnostics: ts.Diagnostic[]) {
diagnostics.sort(ts.compareDiagnostics);
const outputLines: string[] = [];
// Count up all errors that were found in files other than lib.d.ts so we don't miss any
@@ -1371,16 +1273,6 @@ namespace Harness {
}
}
- /** The harness' compiler instance used when tests are actually run. Reseting or changing settings of this compiler instance must be done within a test case (i.e., describe/it) */
- let harnessCompiler: HarnessCompiler;
-
- /** Returns the singleton harness compiler instance for generating and running tests.
- If required a fresh compiler instance will be created, otherwise the existing singleton will be re-used.
- */
- export function getCompiler() {
- return harnessCompiler = harnessCompiler || new HarnessCompiler();
- }
-
// This does not need to exist strictly speaking, but many tests will need to be updated if it's removed
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
@@ -1431,7 +1323,7 @@ namespace Harness {
constructor(fileResults: GeneratedFile[], errors: ts.Diagnostic[], public program: ts.Program,
public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[]) {
- fileResults.forEach(emittedFile => {
+ for (const emittedFile of fileResults) {
if (isDTS(emittedFile.fileName)) {
// .d.ts file, add to declFiles emit
this.declFilesCode.push(emittedFile);
@@ -1446,7 +1338,7 @@ namespace Harness {
else {
throw new Error("Unrecognized file extension for file " + emittedFile.fileName);
}
- });
+ }
this.errors = errors;
}
@@ -1555,7 +1447,7 @@ namespace Harness {
}
// normalize the fileName for the single file case
- currentFileName = testUnitData.length > 0 ? currentFileName : Path.getFileName(fileName);
+ currentFileName = testUnitData.length > 0 || currentFileName ? currentFileName : Path.getFileName(fileName);
// EOF, push whatever remains
const newTestFile2 = {
@@ -1674,7 +1566,7 @@ namespace Harness {
const encoded_actual = Utils.encodeString(actual);
if (expected != encoded_actual) {
// Overwrite & issue error
- const errMsg = "The baseline file " + relativeFileName + " has changed";
+ const errMsg = "The baseline file " + relativeFileName + " has changed.";
throw new Error(errMsg);
}
}
@@ -1711,12 +1603,9 @@ namespace Harness {
return filePath.indexOf(Harness.libFolder) === 0;
}
- export function getDefaultLibraryFile(io: Harness.IO): { unitName: string, content: string } {
+ export function getDefaultLibraryFile(io: Harness.IO): Harness.Compiler.TestFile {
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + "lib.d.ts";
- return {
- unitName: libFile,
- content: io.readFile(libFile)
- };
+ return { unitName: libFile, content: io.readFile(libFile) };
}
if (Error) (Error).stackTraceLimit = 1;
diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts
index faf0ad28eb5..3c7814df562 100644
--- a/src/harness/harnessLanguageService.ts
+++ b/src/harness/harnessLanguageService.ts
@@ -7,7 +7,7 @@ namespace Harness.LanguageService {
export class ScriptInfo {
public version: number = 1;
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
- public lineMap: number[] = undefined;
+ private lineMap: number[] = undefined;
constructor(public fileName: string, public content: string) {
this.setContent(content);
@@ -15,7 +15,11 @@ namespace Harness.LanguageService {
private setContent(content: string): void {
this.content = content;
- this.lineMap = ts.computeLineStarts(content);
+ this.lineMap = undefined;
+ }
+
+ public getLineMap(): number[] {
+ return this.lineMap || (this.lineMap = ts.computeLineStarts(this.content));
}
public updateContent(content: string): void {
@@ -153,7 +157,7 @@ namespace Harness.LanguageService {
throw new Error("No script with name '" + fileName + "'");
}
- public openFile(fileName: string): void {
+ public openFile(fileName: string, content?: string): void {
}
/**
@@ -164,7 +168,7 @@ namespace Harness.LanguageService {
const script: ScriptInfo = this.fileNameToScript[fileName];
assert.isNotNull(script);
- return ts.computeLineAndCharacterOfPosition(script.lineMap, position);
+ return ts.computeLineAndCharacterOfPosition(script.getLineMap(), position);
}
}
@@ -493,9 +497,9 @@ namespace Harness.LanguageService {
this.client = client;
}
- openFile(fileName: string): void {
- super.openFile(fileName);
- this.client.openFile(fileName);
+ openFile(fileName: string, content?: string): void {
+ super.openFile(fileName, content);
+ this.client.openFile(fileName, content);
}
editScript(fileName: string, start: number, end: number, newText: string) {
diff --git a/src/harness/loggedIO.ts b/src/harness/loggedIO.ts
index bf56f1aa3ea..0bae91f7976 100644
--- a/src/harness/loggedIO.ts
+++ b/src/harness/loggedIO.ts
@@ -174,7 +174,7 @@ namespace Playback {
return true;
}
else {
- return findResultByFields(replayLog.fileExists, { path }, false);
+ return findResultByFields(replayLog.fileExists, { path }, /*defaultValue*/ false);
}
})
);
diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts
index f48822f1220..52102663457 100644
--- a/src/harness/projectsRunner.ts
+++ b/src/harness/projectsRunner.ts
@@ -7,19 +7,11 @@ interface ProjectRunnerTestCase {
scenario: string;
projectRoot: string; // project where it lives - this also is the current directory when compiling
inputFiles: string[]; // list of input files to be given to program
- out?: string; // --out
- outDir?: string; // --outDir
- sourceMap?: boolean; // --map
- mapRoot?: string; // --mapRoot
resolveMapRoot?: boolean; // should we resolve this map root and give compiler the absolute disk path as map root?
- sourceRoot?: string; // --sourceRoot
resolveSourceRoot?: boolean; // should we resolve this source root and give compiler the absolute disk path as map root?
- declaration?: boolean; // --d
baselineCheck?: boolean; // Verify the baselines of output files, if this is false, we will write to output to the disk but there is no verification of baselines
runTest?: boolean; // Run the resulting test
bug?: string; // If there is any bug associated with this test case
- noResolve?: boolean;
- rootDir?: string; // --rootDir
}
interface ProjectRunnerTestCaseResolutionInfo extends ProjectRunnerTestCase {
@@ -34,14 +26,14 @@ interface BatchCompileProjectTestCaseEmittedFile extends Harness.Compiler.Genera
interface CompileProjectFilesResult {
moduleKind: ts.ModuleKind;
- program: ts.Program;
+ program?: ts.Program;
+ compilerOptions?: ts.CompilerOptions;
errors: ts.Diagnostic[];
- sourceMapData: ts.SourceMapData[];
+ sourceMapData?: ts.SourceMapData[];
}
interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult {
- outputFiles: BatchCompileProjectTestCaseEmittedFile[];
- nonSubfolderDiskFiles: number;
+ outputFiles?: BatchCompileProjectTestCaseEmittedFile[];
}
class ProjectRunner extends RunnerBase {
@@ -59,7 +51,7 @@ class ProjectRunner extends RunnerBase {
}
private runProjectTestCase(testCaseFileName: string) {
- let testCase: ProjectRunnerTestCase;
+ let testCase: ProjectRunnerTestCase & ts.CompilerOptions;
let testFileText: string = null;
try {
@@ -70,7 +62,7 @@ class ProjectRunner extends RunnerBase {
}
try {
- testCase = JSON.parse(testFileText);
+ testCase = JSON.parse(testFileText);
}
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
@@ -128,9 +120,10 @@ class ProjectRunner extends RunnerBase {
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: () => string[],
getSourceFileTextImpl: (fileName: string) => string,
- writeFile: (fileName: string, data: string, writeByteOrderMark: boolean) => void): CompileProjectFilesResult {
+ writeFile: (fileName: string, data: string, writeByteOrderMark: boolean) => void,
+ compilerOptions: ts.CompilerOptions): CompileProjectFilesResult {
- const program = ts.createProgram(getInputFiles(), createCompilerOptions(), createCompilerHost());
+ const program = ts.createProgram(getInputFiles(), compilerOptions, createCompilerHost());
let errors = ts.getPreEmitDiagnostics(program);
const emitResult = program.emit();
@@ -155,21 +148,6 @@ class ProjectRunner extends RunnerBase {
sourceMapData
};
- function createCompilerOptions(): ts.CompilerOptions {
- return {
- declaration: !!testCase.declaration,
- sourceMap: !!testCase.sourceMap,
- outFile: testCase.out,
- outDir: testCase.outDir,
- mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? Harness.IO.resolvePath(testCase.mapRoot) : testCase.mapRoot,
- sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? Harness.IO.resolvePath(testCase.sourceRoot) : testCase.sourceRoot,
- module: moduleKind,
- moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
- noResolve: testCase.noResolve,
- rootDir: testCase.rootDir
- };
- }
-
function getSourceFileText(fileName: string): string {
const text = getSourceFileTextImpl(fileName);
return text !== undefined ? text : getSourceFileTextImpl(ts.getNormalizedAbsolutePath(fileName, getCurrentDirectory()));
@@ -209,23 +187,105 @@ class ProjectRunner extends RunnerBase {
let nonSubfolderDiskFiles = 0;
const outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
+ let inputFiles = testCase.inputFiles;
+ let compilerOptions = createCompilerOptions();
- const projectCompilerResult = compileProjectFiles(moduleKind, () => testCase.inputFiles, getSourceFileText, writeFile);
+ let configFileName: string;
+ if (compilerOptions.project) {
+ // Parse project
+ configFileName = ts.normalizePath(ts.combinePaths(compilerOptions.project, "tsconfig.json"));
+ assert(!inputFiles || inputFiles.length === 0, "cannot specify input files and project option together");
+ }
+ else if (!inputFiles || inputFiles.length === 0) {
+ configFileName = ts.findConfigFile("", fileExists);
+ }
+
+ if (configFileName) {
+ const result = ts.readConfigFile(configFileName, getSourceFileText);
+ if (result.error) {
+ return {
+ moduleKind,
+ errors: [result.error]
+ };
+ }
+
+ const configObject = result.config;
+ const configParseResult = ts.parseJsonConfigFileContent(configObject, { readDirectory }, ts.getDirectoryPath(configFileName), compilerOptions);
+ if (configParseResult.errors.length > 0) {
+ return {
+ moduleKind,
+ errors: configParseResult.errors
+ };
+ }
+ inputFiles = configParseResult.fileNames;
+ compilerOptions = configParseResult.options;
+ }
+
+ const projectCompilerResult = compileProjectFiles(moduleKind, () => inputFiles, getSourceFileText, writeFile, compilerOptions);
return {
moduleKind,
program: projectCompilerResult.program,
+ compilerOptions,
sourceMapData: projectCompilerResult.sourceMapData,
outputFiles,
errors: projectCompilerResult.errors,
- nonSubfolderDiskFiles,
};
+ function createCompilerOptions() {
+ // Set the special options that depend on other testcase options
+ const compilerOptions: ts.CompilerOptions = {
+ mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? Harness.IO.resolvePath(testCase.mapRoot) : testCase.mapRoot,
+ sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? Harness.IO.resolvePath(testCase.sourceRoot) : testCase.sourceRoot,
+ module: moduleKind,
+ moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
+ };
+ // Set the values specified using json
+ const optionNameMap: ts.Map = {};
+ ts.forEach(ts.optionDeclarations, option => {
+ optionNameMap[option.name] = option;
+ });
+ for (const name in testCase) {
+ if (name !== "mapRoot" && name !== "sourceRoot" && ts.hasProperty(optionNameMap, name)) {
+ const option = optionNameMap[name];
+ const optType = option.type;
+ let value = testCase[name];
+ if (typeof optType !== "string") {
+ const key = value.toLowerCase();
+ if (ts.hasProperty(optType, key)) {
+ value = optType[key];
+ }
+ }
+ compilerOptions[option.name] = value;
+ }
+ }
+
+ return compilerOptions;
+ }
+
+ function getFileNameInTheProjectTest(fileName: string): string {
+ return ts.isRootedDiskPath(fileName)
+ ? fileName
+ : ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName);
+ }
+
+ function readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
+ const harnessReadDirectoryResult = Harness.IO.readDirectory(getFileNameInTheProjectTest(rootDir), extension, exclude);
+ const result: string[] = [];
+ for (let i = 0; i < harnessReadDirectoryResult.length; i++) {
+ result[i] = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, harnessReadDirectoryResult[i],
+ getCurrentDirectory(), Harness.Compiler.getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
+ }
+ return result;
+ }
+
+ function fileExists(fileName: string): boolean {
+ return Harness.IO.fileExists(getFileNameInTheProjectTest(fileName));
+ }
+
function getSourceFileText(fileName: string): string {
let text: string = undefined;
try {
- text = Harness.IO.readFile(ts.isRootedDiskPath(fileName)
- ? fileName
- : ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName));
+ text = Harness.IO.readFile(getFileNameInTheProjectTest(fileName));
}
catch (e) {
// text doesn't get defined.
@@ -288,13 +348,16 @@ class ProjectRunner extends RunnerBase {
function compileCompileDTsFiles(compilerResult: BatchCompileProjectTestCaseResult) {
const allInputFiles: { emittedFileName: string; code: string; }[] = [];
+ if (!compilerResult.program) {
+ return;
+ }
const compilerOptions = compilerResult.program.getCompilerOptions();
ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => {
- if (Harness.Compiler.isDTS(sourceFile.fileName)) {
+ if (ts.isDeclarationFile(sourceFile)) {
allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text });
}
- else if (ts.shouldEmitToOwnFile(sourceFile, compilerResult.program.getCompilerOptions())) {
+ else if (!(compilerOptions.outFile || compilerOptions.out)) {
let emitOutputFilePathWithoutExtension: string = undefined;
if (compilerOptions.outDir) {
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, compilerResult.program.getCurrentDirectory());
@@ -320,7 +383,8 @@ class ProjectRunner extends RunnerBase {
}
});
- return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile);
+ // Dont allow config files since we are compiling existing source options
+ return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile, compilerResult.compilerOptions);
function findOutpuDtsFile(fileName: string) {
return ts.forEach(compilerResult.outputFiles, outputFile => outputFile.emittedFileName === fileName ? outputFile : undefined);
@@ -346,11 +410,16 @@ class ProjectRunner extends RunnerBase {
}
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
- const inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
+ const inputFiles = compilerResult.program ? ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => {
- return { unitName: RunnerBase.removeFullPaths(sourceFile.fileName), content: sourceFile.text };
- });
+ return {
+ unitName: ts.isRootedDiskPath(sourceFile.fileName) ?
+ RunnerBase.removeFullPaths(sourceFile.fileName) :
+ sourceFile.fileName,
+ content: sourceFile.text
+ };
+ }) : [];
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
@@ -363,30 +432,13 @@ class ProjectRunner extends RunnerBase {
let compilerResult: BatchCompileProjectTestCaseResult;
function getCompilerResolutionInfo() {
- const resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
- scenario: testCase.scenario,
- projectRoot: testCase.projectRoot,
- inputFiles: testCase.inputFiles,
- out: testCase.out,
- outDir: testCase.outDir,
- sourceMap: testCase.sourceMap,
- mapRoot: testCase.mapRoot,
- resolveMapRoot: testCase.resolveMapRoot,
- sourceRoot: testCase.sourceRoot,
- resolveSourceRoot: testCase.resolveSourceRoot,
- declaration: testCase.declaration,
- baselineCheck: testCase.baselineCheck,
- runTest: testCase.runTest,
- bug: testCase.bug,
- rootDir: testCase.rootDir,
- resolvedInputFiles: ts.map(compilerResult.program.getSourceFiles(), inputFile => {
- return ts.convertToRelativePath(inputFile.fileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
- }),
- emittedFiles: ts.map(compilerResult.outputFiles, outputFile => {
- return ts.convertToRelativePath(outputFile.emittedFileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
- })
- };
-
+ const resolutionInfo: ProjectRunnerTestCaseResolutionInfo & ts.CompilerOptions = JSON.parse(JSON.stringify(testCase));
+ resolutionInfo.resolvedInputFiles = ts.map(compilerResult.program.getSourceFiles(), inputFile => {
+ return ts.convertToRelativePath(inputFile.fileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
+ });
+ resolutionInfo.emittedFiles = ts.map(compilerResult.outputFiles, outputFile => {
+ return ts.convertToRelativePath(outputFile.emittedFileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
+ });
return resolutionInfo;
}
@@ -442,7 +494,7 @@ class ProjectRunner extends RunnerBase {
it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
const dTsCompileResult = compileCompileDTsFiles(compilerResult);
- if (dTsCompileResult.errors.length) {
+ if (dTsCompileResult && dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline("Errors in generated Dts files for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
return getErrorsBaseline(dTsCompileResult);
});
diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts
index a350eda08f3..ce570a7d6ad 100644
--- a/src/harness/rwcRunner.ts
+++ b/src/harness/rwcRunner.ts
@@ -27,8 +27,8 @@ namespace RWC {
export function runRWCTest(jsonPath: string) {
describe("Testing a RWC project: " + jsonPath, () => {
- let inputFiles: { unitName: string; content: string; }[] = [];
- let otherFiles: { unitName: string; content: string; }[] = [];
+ let inputFiles: Harness.Compiler.TestFile[] = [];
+ let otherFiles: Harness.Compiler.TestFile[] = [];
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
@@ -55,7 +55,6 @@ namespace RWC {
});
it("can compile", () => {
- const harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
const ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
@@ -71,8 +70,6 @@ namespace RWC {
});
runWithIOLog(ioLog, oldIO => {
- harnessCompiler.reset();
-
let fileNames = opts.fileNames;
const tsconfigFile = ts.forEach(ioLog.filesRead, f => isTsConfigFile(f) ? f : undefined);
@@ -128,17 +125,21 @@ namespace RWC {
opts.options.noLib = true;
// Emit the results
- compilerOptions = harnessCompiler.compileFiles(
+ compilerOptions = null;
+ const output = Harness.Compiler.compileFiles(
inputFiles,
otherFiles,
- newCompilerResults => { compilerResult = newCompilerResults; },
- /*settingsCallback*/ undefined, opts.options,
+ /* harnessOptions */ undefined,
+ opts.options,
// Since each RWC json file specifies its current directory in its json file, we need
// to pass this information in explicitly instead of acquiring it from the process.
currentDirectory);
+
+ compilerOptions = output.options;
+ compilerResult = output.result;
});
- function getHarnessCompilerInputUnit(fileName: string) {
+ function getHarnessCompilerInputUnit(fileName: string): Harness.Compiler.TestFile {
const unitName = ts.normalizeSlashes(Harness.IO.resolvePath(fileName));
let content: string = null;
try {
@@ -201,8 +202,9 @@ namespace RWC {
it("has the expected errors in generated declaration files", () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline("has the expected errors in generated declaration files", baseName + ".dts.errors.txt", () => {
- const declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
- /*settingscallback*/ undefined, compilerOptions, currentDirectory);
+ const declFileCompilationResult = Harness.Compiler.compileDeclarationFiles(
+ inputFiles, otherFiles, compilerResult, /*harnessSettings*/ undefined, compilerOptions, currentDirectory);
+
if (declFileCompilationResult.declResult.errors.length === 0) {
return null;
}
diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts
index ce0a6a6528e..806ca7a845d 100644
--- a/src/harness/sourceMapRecorder.ts
+++ b/src/harness/sourceMapRecorder.ts
@@ -172,7 +172,6 @@ namespace Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 5. Check if there is name:
- decodeOfEncodedMapping.nameIndex = -1;
if (!isSourceMappingSegmentEnd()) {
prevNameIndex += base64VLQFormatDecode();
decodeOfEncodedMapping.nameIndex = prevNameIndex;
@@ -190,7 +189,7 @@ namespace Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
- createErrorIfCondition(true, "No encoded entry found");
+ createErrorIfCondition(/*condition*/ true, "No encoded entry found");
}
export function hasCompletedDecoding() {
@@ -249,7 +248,7 @@ namespace Harness.SourceMapRecoder {
mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")";
}
else {
- if (mapEntry.nameIndex !== -1 || getAbsentNameIndex) {
+ if ((mapEntry.nameIndex && mapEntry.nameIndex !== -1) || getAbsentNameIndex) {
mapString += " nameIndex (" + mapEntry.nameIndex + ")";
}
}
diff --git a/src/harness/test262Runner.ts b/src/harness/test262Runner.ts
index f25e0c79b63..262145b4764 100644
--- a/src/harness/test262Runner.ts
+++ b/src/harness/test262Runner.ts
@@ -5,9 +5,9 @@
class Test262BaselineRunner extends RunnerBase {
private static basePath = "internal/cases/test262";
private static helpersFilePath = "tests/cases/test262-harness/helpers.d.ts";
- private static helperFile = {
+ private static helperFile: Harness.Compiler.TestFile = {
unitName: Test262BaselineRunner.helpersFilePath,
- content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath)
+ content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath),
};
private static testFileExtensionRegex = /\.js$/;
private static options: ts.CompilerOptions = {
@@ -31,8 +31,7 @@ class Test262BaselineRunner extends RunnerBase {
let testState: {
filename: string;
compilerResult: Harness.Compiler.CompilerResult;
- inputFiles: { unitName: string; content: string }[];
- program: ts.Program;
+ inputFiles: Harness.Compiler.TestFile[];
};
before(() => {
@@ -40,8 +39,9 @@ class Test262BaselineRunner extends RunnerBase {
const testFilename = ts.removeFileExtension(filePath).replace(/\//g, "_") + ".test";
const testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
- const inputFiles = testCaseContent.testUnitData.map(unit => {
- return { unitName: Test262BaselineRunner.getTestFilePath(unit.name), content: unit.content };
+ const inputFiles: Harness.Compiler.TestFile[] = testCaseContent.testUnitData.map(unit => {
+ const unitName = Test262BaselineRunner.getTestFilePath(unit.name);
+ return { unitName, content: unit.content };
});
// Emit the results
@@ -49,13 +49,16 @@ class Test262BaselineRunner extends RunnerBase {
filename: testFilename,
inputFiles: inputFiles,
compilerResult: undefined,
- program: undefined,
};
- Harness.Compiler.getCompiler().compileFiles([Test262BaselineRunner.helperFile].concat(inputFiles), /*otherFiles*/ [], (compilerResult, program) => {
- testState.compilerResult = compilerResult;
- testState.program = program;
- }, /*settingsCallback*/ undefined, Test262BaselineRunner.options);
+ const output = Harness.Compiler.compileFiles(
+ [Test262BaselineRunner.helperFile].concat(inputFiles),
+ /*otherFiles*/ [],
+ /* harnessOptions */ undefined,
+ Test262BaselineRunner.options,
+ /* currentDirectory */ undefined
+ );
+ testState.compilerResult = output.result;
});
after(() => {
@@ -80,14 +83,14 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
- it("satisfies inletiants", () => {
- const sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
+ it("satisfies invariants", () => {
+ const sourceFile = testState.compilerResult.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it("has the expected AST", () => {
Harness.Baseline.runBaseline("has the expected AST", testState.filename + ".AST.txt", () => {
- const sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
+ const sourceFile = testState.compilerResult.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
});
diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts
index ac039198b4b..5984505c4cf 100644
--- a/src/lib/dom.generated.d.ts
+++ b/src/lib/dom.generated.d.ts
@@ -2058,6 +2058,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Gets or sets the version attribute specified in the declaration of an XML document.
*/
xmlVersion: string;
+ currentScript: HTMLScriptElement;
adoptNode(source: Node): Node;
captureEvents(): void;
clear(): void;
@@ -2977,6 +2978,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
webkitRequestFullScreen(): void;
webkitRequestFullscreen(): void;
getElementsByClassName(classNames: string): NodeListOf;
+ matches(selector: string): boolean;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -3961,7 +3963,6 @@ interface HTMLElement extends Element {
title: string;
blur(): void;
click(): void;
- contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
insertAdjacentElement(position: string, insertedElement: Element): Element;
@@ -6135,7 +6136,7 @@ interface HTMLSelectElement extends HTMLElement {
* Sets or retrieves the name of the object.
*/
name: string;
- options: HTMLSelectElement;
+ options: HTMLCollection;
/**
* When present, marks an element that can't be submitted without a value.
*/
@@ -6421,19 +6422,19 @@ interface HTMLTableElement extends HTMLElement {
/**
* Creates an empty caption element in the table.
*/
- createCaption(): HTMLElement;
+ createCaption(): HTMLTableCaptionElement;
/**
* Creates an empty tBody element in the table.
*/
- createTBody(): HTMLElement;
+ createTBody(): HTMLTableSectionElement;
/**
* Creates an empty tFoot element in the table.
*/
- createTFoot(): HTMLElement;
+ createTFoot(): HTMLTableSectionElement;
/**
* Returns the tHead element object if successful, or null otherwise.
*/
- createTHead(): HTMLElement;
+ createTHead(): HTMLTableSectionElement;
/**
* Deletes the caption element and its contents from the table.
*/
@@ -6455,7 +6456,7 @@ interface HTMLTableElement extends HTMLElement {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
- insertRow(index?: number): HTMLElement;
+ insertRow(index?: number): HTMLTableRowElement;
}
declare var HTMLTableElement: {
@@ -6506,7 +6507,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment {
* Creates a new cell in the table row, and adds the cell to the cells collection.
* @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.
*/
- insertCell(index?: number): HTMLElement;
+ insertCell(index?: number): HTMLTableCellElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6533,7 +6534,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
- insertRow(index?: number): HTMLElement;
+ insertRow(index?: number): HTMLTableRowElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -7071,7 +7072,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
- data: number[];
+ data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -7869,6 +7870,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
+ vibrate(pattern: number | number[]): boolean;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -7909,6 +7911,7 @@ interface Node extends EventTarget {
normalize(): void;
removeChild(oldChild: Node): Node;
replaceChild(newChild: Node, oldChild: Node): Node;
+ contains(node: Node): boolean;
ATTRIBUTE_NODE: number;
CDATA_SECTION_NODE: number;
COMMENT_NODE: number;
diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts
index a2ed9682f1b..8001511a98b 100644
--- a/src/lib/webworker.generated.d.ts
+++ b/src/lib/webworker.generated.d.ts
@@ -460,7 +460,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
- data: number[];
+ data: Uint8ClampedArray;
height: number;
width: number;
}
diff --git a/src/server/client.ts b/src/server/client.ts
index ae234750d88..08939b2b44a 100644
--- a/src/server/client.ts
+++ b/src/server/client.ts
@@ -120,8 +120,8 @@ namespace ts.server {
return response;
}
- openFile(fileName: string): void {
- var args: protocol.FileRequestArgs = { file: fileName };
+ openFile(fileName: string, content?: string): void {
+ var args: protocol.OpenRequestArgs = { file: fileName, fileContent: content };
this.processRequest(CommandNames.Open, args);
}
diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts
index 333cea2745d..0305b7595c2 100644
--- a/src/server/editorServices.ts
+++ b/src/server/editorServices.ts
@@ -388,7 +388,7 @@ namespace ts.server {
}
openReferencedFile(filename: string) {
- return this.projectService.openFile(filename, false);
+ return this.projectService.openFile(filename, /*openedByClient*/ false);
}
getRootFiles() {
@@ -564,7 +564,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
- if (fileName && !ts.isSupportedSourceFileName(fileName)) {
+ if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) {
return;
}
@@ -1006,14 +1006,15 @@ namespace ts.server {
/**
* @param filename is absolute pathname
+ * @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
- openFile(fileName: string, openedByClient: boolean) {
+ openFile(fileName: string, openedByClient: boolean, fileContent?: string) {
fileName = ts.normalizePath(fileName);
let info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
let content: string;
if (this.host.fileExists(fileName)) {
- content = this.host.readFile(fileName);
+ content = fileContent || this.host.readFile(fileName);
}
if (!content) {
if (openedByClient) {
@@ -1030,6 +1031,9 @@ namespace ts.server {
}
}
if (info) {
+ if (fileContent) {
+ info.svc.reload(fileContent);
+ }
if (openedByClient) {
info.isOpen = true;
}
@@ -1060,10 +1064,11 @@ namespace ts.server {
/**
* Open file whose contents is managed by the client
* @param filename is absolute pathname
+ * @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
- openClientFile(fileName: string) {
+ openClientFile(fileName: string, fileContent?: string) {
this.openOrUpdateConfiguredProjectForFile(fileName);
- const info = this.openFile(fileName, true);
+ const info = this.openFile(fileName, /*openedByClient*/ true, fileContent);
this.addOpenFile(info);
this.printProjects();
return info;
@@ -1272,7 +1277,7 @@ namespace ts.server {
for (const fileName of fileNamesToAdd) {
let info = this.getScriptInfo(fileName);
if (!info) {
- info = this.openFile(fileName, false);
+ info = this.openFile(fileName, /*openedByClient*/ false);
}
else {
// if the root file was opened by client, it would belong to either
diff --git a/src/server/protocol.d.ts b/src/server/protocol.d.ts
index ad1fc5e92de..3a669753323 100644
--- a/src/server/protocol.d.ts
+++ b/src/server/protocol.d.ts
@@ -513,6 +513,11 @@ declare namespace ts.server.protocol {
* Information found in an "open" request.
*/
export interface OpenRequestArgs extends FileRequestArgs {
+ /**
+ * Used when a version of the file content is known to be more up to date than the one on disk.
+ * Then the known content will be used upon opening instead of the disk copy
+ */
+ fileContent?: string;
}
/**
diff --git a/src/server/session.ts b/src/server/session.ts
index 770256cc9f7..dae2384ce54 100644
--- a/src/server/session.ts
+++ b/src/server/session.ts
@@ -532,9 +532,13 @@ namespace ts.server {
};
}
- private openClientFile(fileName: string) {
+ /**
+ * @param fileName is the name of the file to be opened
+ * @param fileContent is a version of the file content that is known to be more up to date than the one on disk
+ */
+ private openClientFile(fileName: string, fileContent?: string) {
const file = ts.normalizePath(fileName);
- this.projectService.openClientFile(file);
+ this.projectService.openClientFile(file, fileContent);
}
private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
@@ -897,7 +901,7 @@ namespace ts.server {
}
getDiagnosticsForProject(delay: number, fileName: string) {
- const { configFileName, fileNames } = this.getProjectInfo(fileName, true);
+ const { configFileName, fileNames } = this.getProjectInfo(fileName, /*needFileNameList*/ true);
// No need to analyze lib.d.ts
let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0);
@@ -968,7 +972,7 @@ namespace ts.server {
},
[CommandNames.Open]: (request: protocol.Request) => {
const openArgs = request.arguments;
- this.openClientFile(openArgs.file);
+ this.openClientFile(openArgs.file, openArgs.fileContent);
return {responseRequired: false};
},
[CommandNames.Quickinfo]: (request: protocol.Request) => {
diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts
index e307b21979e..31ab5d2adec 100644
--- a/src/services/breakpoints.ts
+++ b/src/services/breakpoints.ts
@@ -16,7 +16,7 @@ namespace ts.BreakpointResolver {
let tokenAtLocation = getTokenAtPosition(sourceFile, position);
let lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
- if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) {
+ if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
// eg: let x =10; |--- cursor is here
// let y = 10;
@@ -39,16 +39,23 @@ namespace ts.BreakpointResolver {
return spanInNode(tokenAtLocation);
function textSpan(startNode: Node, endNode?: Node) {
- return createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd());
+ const start = startNode.decorators ?
+ skipTrivia(sourceFile.text, startNode.decorators.end) :
+ startNode.getStart(sourceFile);
+ return createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function spanInNodeIfStartsOnSameLine(node: Node, otherwiseOnNode?: Node): TextSpan {
- if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) {
+ if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
return spanInNode(node);
}
return spanInNode(otherwiseOnNode);
}
+ function spanInNodeArray(nodeArray: NodeArray) {
+ return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
+ }
+
function spanInPreviousNode(node: Node): TextSpan {
return spanInNode(findPrecedingToken(node.pos, sourceFile));
}
@@ -65,6 +72,11 @@ namespace ts.BreakpointResolver {
return spanInPreviousNode(node);
}
+ if (node.parent.kind === SyntaxKind.Decorator) {
+ // Set breakpoint on the decorator emit
+ return spanInNode(node.parent);
+ }
+
if (node.parent.kind === SyntaxKind.ForStatement) {
// For now lets set the span on this expression, fix it later
return textSpan(node);
@@ -207,6 +219,9 @@ namespace ts.BreakpointResolver {
// span in statement
return spanInNode((node).statement);
+ case SyntaxKind.Decorator:
+ return spanInNodeArray(node.parent.decorators);
+
// No breakpoint in interface, type alias
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts
index e822052a5b2..46ec807a881 100644
--- a/src/services/navigationBar.ts
+++ b/src/services/navigationBar.ts
@@ -2,7 +2,7 @@
/* @internal */
namespace ts.NavigationBar {
- export function getNavigationBarItems(sourceFile: SourceFile): ts.NavigationBarItem[] {
+ export function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[] {
// If the source file has any child items, then it included in the tree
// and takes lexical ownership of all other top-level items.
let hasGlobalNode = false;
diff --git a/src/services/services.ts b/src/services/services.ts
index 0e2dd513336..4e0a0265b91 100644
--- a/src/services/services.ts
+++ b/src/services/services.ts
@@ -132,43 +132,43 @@ namespace ts {
let scanner: Scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
let emptyArray: any[] = [];
-
+
const jsDocTagNames = [
- "augments",
- "author",
- "argument",
- "borrows",
- "class",
- "constant",
- "constructor",
- "constructs",
- "default",
- "deprecated",
- "description",
- "event",
- "example",
- "extends",
- "field",
- "fileOverview",
- "function",
- "ignore",
- "inner",
- "lends",
- "link",
- "memberOf",
- "name",
- "namespace",
- "param",
- "private",
- "property",
- "public",
- "requires",
- "returns",
- "see",
- "since",
- "static",
- "throws",
- "type",
+ "augments",
+ "author",
+ "argument",
+ "borrows",
+ "class",
+ "constant",
+ "constructor",
+ "constructs",
+ "default",
+ "deprecated",
+ "description",
+ "event",
+ "example",
+ "extends",
+ "field",
+ "fileOverview",
+ "function",
+ "ignore",
+ "inner",
+ "lends",
+ "link",
+ "memberOf",
+ "name",
+ "namespace",
+ "param",
+ "private",
+ "property",
+ "public",
+ "requires",
+ "returns",
+ "see",
+ "since",
+ "static",
+ "throws",
+ "type",
"version"
];
let jsDocCompletionEntries: CompletionEntry[];
@@ -817,7 +817,7 @@ namespace ts {
constructor(kind: SyntaxKind, pos: number, end: number) {
super(kind, pos, end)
}
-
+
public update(newText: string, textChangeRange: TextChangeRange): SourceFile {
return updateSourceFile(this, newText, textChangeRange);
}
@@ -1031,7 +1031,7 @@ namespace ts {
/*
* LS host can optionally implement this method if it wants to be completely in charge of module name resolution.
- * if implementation is omitted then language service will use built-in module resolution logic and get answers to
+ * if implementation is omitted then language service will use built-in module resolution logic and get answers to
* host specific questions using 'getScriptSnapshot'.
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
@@ -1861,7 +1861,7 @@ namespace ts {
* - allowNonTsExtensions = true
* - noLib = true
* - noResolve = true
- */
+ */
export function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput {
let options = transpileOptions.compilerOptions ? clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions();
@@ -1901,7 +1901,7 @@ namespace ts {
sourceMapText = text;
}
else {
- Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
+ Debug.assert(outputText === undefined, `Unexpected multiple outputs for the file: '${name}'`);
outputText = text;
}
},
@@ -2023,7 +2023,7 @@ namespace ts {
let getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames);
function getKeyFromCompilationSettings(settings: CompilerOptions): string {
- return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx;
+ return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs;
}
function getBucketForCompilationSettings(settings: CompilerOptions, createIfMissing: boolean): FileMap {
@@ -2320,7 +2320,7 @@ namespace ts {
return true;
}
-
+
return false;
}
@@ -2339,7 +2339,7 @@ namespace ts {
}
return false;
}
-
+
function tryConsumeDefine(): boolean {
let token = scanner.getToken();
if (token === SyntaxKind.Identifier && scanner.getTokenValue() === "define") {
@@ -2365,7 +2365,7 @@ namespace ts {
if (token !== SyntaxKind.OpenBracketToken) {
return true;
}
-
+
// skip open bracket
token = scanner.scan();
let i = 0;
@@ -2380,7 +2380,7 @@ namespace ts {
token = scanner.scan();
}
return true;
-
+
}
return false;
}
@@ -2670,7 +2670,7 @@ namespace ts {
}
}
- export function createLanguageService(host: LanguageServiceHost,
+ export function createLanguageService(host: LanguageServiceHost,
documentRegistry: DocumentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory())): LanguageService {
let syntaxTreeCache: SyntaxTreeCache = new SyntaxTreeCache(host);
@@ -2746,7 +2746,8 @@ namespace ts {
(oldSettings.target !== newSettings.target ||
oldSettings.module !== newSettings.module ||
oldSettings.noResolve !== newSettings.noResolve ||
- oldSettings.jsx !== newSettings.jsx);
+ oldSettings.jsx !== newSettings.jsx ||
+ oldSettings.allowJs !== newSettings.allowJs);
// Now create a new compiler
let compilerHost: CompilerHost = {
@@ -2758,10 +2759,10 @@ namespace ts {
getDefaultLibFileName: (options) => host.getDefaultLibFileName(options),
writeFile: (fileName, data, writeByteOrderMark) => { },
getCurrentDirectory: () => currentDirectory,
- fileExists: (fileName): boolean => {
+ fileExists: (fileName): boolean => {
// stub missing host functionality
Debug.assert(!host.resolveModuleNames);
- return hostCache.getOrCreateEntry(fileName) !== undefined;
+ return hostCache.getOrCreateEntry(fileName) !== undefined;
},
readFile: (fileName): string => {
// stub missing host functionality
@@ -2847,8 +2848,11 @@ namespace ts {
}
function sourceFileUpToDate(sourceFile: SourceFile): boolean {
+ if (!sourceFile) {
+ return false;
+ }
let path = sourceFile.path || toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName);
- return sourceFile && sourceFile.version === hostCache.getVersion(path);
+ return sourceFile.version === hostCache.getVersion(path);
}
function programUpToDate(): boolean {
@@ -2908,13 +2912,6 @@ namespace ts {
let targetSourceFile = getValidSourceFile(fileName);
- // For JavaScript files, we don't want to report the normal typescript semantic errors.
- // Instead, we just report errors for using TypeScript-only constructs from within a
- // JavaScript file.
- if (isSourceFileJavaScript(targetSourceFile)) {
- return getJavaScriptSemanticDiagnostics(targetSourceFile);
- }
-
// Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
// Therefore only get diagnostics for given file.
@@ -2928,163 +2925,6 @@ namespace ts {
return concatenate(semanticDiagnostics, declarationDiagnostics);
}
- function getJavaScriptSemanticDiagnostics(sourceFile: SourceFile): Diagnostic[] {
- let diagnostics: Diagnostic[] = [];
- walk(sourceFile);
-
- return diagnostics;
-
- function walk(node: Node): boolean {
- if (!node) {
- return false;
- }
-
- switch (node.kind) {
- case SyntaxKind.ImportEqualsDeclaration:
- 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;
- case SyntaxKind.ClassDeclaration:
- let classDeclaration = node;
- if (checkModifiers(classDeclaration.modifiers) ||
- checkTypeParameters(classDeclaration.typeParameters)) {
- return true;
- }
- break;
- case SyntaxKind.HeritageClause:
- let heritageClause =