diff --git a/Jakefile.js b/Jakefile.js
index 57e05f8acba..0793659183b 100644
--- a/Jakefile.js
+++ b/Jakefile.js
@@ -3,7 +3,6 @@
///
const fs = require("fs");
-const fs2 = require("fs-extra");
const os = require("os");
const path = require("path");
const fold = require("travis-fold");
diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js
index 1757efbb9bd..d63145f3fc5 100644
--- a/lib/cancellationToken.js
+++ b/lib/cancellationToken.js
@@ -70,5 +70,4 @@ function createCancellationToken(args) {
}
}
module.exports = createCancellationToken;
-
-//# sourceMappingURL=cancellationToken.js.map
+//# sourceMappingURL=cancellationToken.js.map
\ No newline at end of file
diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts
index 987fbf9ae24..cd239619457 100644
--- a/lib/protocol.d.ts
+++ b/lib/protocol.d.ts
@@ -458,7 +458,7 @@ declare namespace ts.server.protocol {
scope: OrganizeImportsScope;
}
interface OrganizeImportsResponse extends Response {
- edits: ReadonlyArray;
+ body: ReadonlyArray;
}
interface GetEditsForFileRenameRequest extends Request {
command: CommandTypes.GetEditsForFileRename;
@@ -469,7 +469,7 @@ declare namespace ts.server.protocol {
readonly newFilePath: string;
}
interface GetEditsForFileRenameResponse extends Response {
- edits: ReadonlyArray;
+ body: ReadonlyArray;
}
/**
* Request for the available codefixes at a specific position.
@@ -2255,6 +2255,7 @@ declare namespace ts.server.protocol {
interface TextInsertion {
newText: string;
+ /** The position in newText the caret should point to after the insertion. */
caretOffset: number;
}
@@ -2270,9 +2271,13 @@ declare namespace ts.server.protocol {
}
enum OutliningSpanKind {
+ /** Single or multi-line comments */
Comment = "comment",
+ /** Sections marked by '// #region' and '// #endregion' comments */
Region = "region",
+ /** Declarations and expressions */
Code = "code",
+ /** Contiguous blocks of import declarations */
Imports = "imports"
}
@@ -2286,27 +2291,56 @@ declare namespace ts.server.protocol {
enum ScriptElementKind {
unknown = "",
warning = "warning",
+ /** predefined type (void) or keyword (class) */
keyword = "keyword",
+ /** top level script node */
scriptElement = "script",
+ /** module foo {} */
moduleElement = "module",
+ /** class X {} */
classElement = "class",
+ /** var x = class X {} */
localClassElement = "local class",
+ /** interface Y {} */
interfaceElement = "interface",
+ /** type T = ... */
typeElement = "type",
+ /** enum E */
enumElement = "enum",
enumMemberElement = "enum member",
+ /**
+ * Inside module and script only
+ * const v = ..
+ */
variableElement = "var",
+ /** Inside function */
localVariableElement = "local var",
+ /**
+ * Inside module and script only
+ * function f() { }
+ */
functionElement = "function",
+ /** Inside function */
localFunctionElement = "local function",
+ /** class X { [public|private]* foo() {} } */
memberFunctionElement = "method",
+ /** class X { [public|private]* [get|set] foo:number; } */
memberGetAccessorElement = "getter",
memberSetAccessorElement = "setter",
+ /**
+ * class X { [public|private]* foo:number; }
+ * interface Y { foo:number; }
+ */
memberVariableElement = "property",
+ /** class X { constructor() { } } */
constructorImplementationElement = "constructor",
+ /** interface Y { ():number; } */
callSignatureElement = "call",
+ /** interface Y { []:number; } */
indexSignatureElement = "index",
+ /** interface Y { new():Y; } */
constructSignatureElement = "construct",
+ /** function foo(*Y*: string) */
parameterElement = "parameter",
typeParameterElement = "type parameter",
primitiveType = "primitive type",
@@ -2316,7 +2350,11 @@ declare namespace ts.server.protocol {
letElement = "let",
directory = "directory",
externalModuleName = "external module name",
+ /**
+ *
+ */
jsxAttribute = "JSX attribute",
+ /** String literal */
string = "string"
}
@@ -2339,6 +2377,11 @@ declare namespace ts.server.protocol {
text?: string;
}
+ /**
+ * Type of objects whose values are all of the same type.
+ * The `in` and `for-in` operators can *not* be safely used,
+ * since `Object.prototype` may be modified by outside code.
+ */
interface MapLike {
[index: string]: T;
}
@@ -2348,9 +2391,13 @@ declare namespace ts.server.protocol {
}
interface ProjectReference {
+ /** A normalized path on disk */
path: string;
+ /** The path as the user originally wrote it */
originalPath?: string;
+ /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
prepend?: boolean;
+ /** True if it is intended that this reference form a circularity */
circular?: boolean;
}
diff --git a/lib/tsc.js b/lib/tsc.js
index 5ee4b284add..c4211aa1b3b 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -1,11 +1,14 @@
"use strict";"use strict";
-var __assign = (this && this.__assign) || Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
};
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
@@ -53963,7 +53966,7 @@ var ts;
name: "typescript:assign",
scoped: false,
priority: 1,
- text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };"
+ text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };"
};
function createAssignHelper(context, attributesSegments) {
if (context.getCompilerOptions().target >= 2) {
@@ -56440,7 +56443,7 @@ var ts;
name: "typescript:extends",
scoped: false,
priority: 0,
- text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
+ text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
var templateObjectHelper = {
name: "typescript:makeTemplateObject",
@@ -61783,13 +61786,17 @@ var ts;
var offsetLine_1 = writer.getLine();
var firstLineColumnOffset_1 = writer.getColumn();
var originalMap_1 = parsed;
+ var sourcesDirectoryPath_1 = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
+ var resolvedPathCache_1 = ts.createMap();
ts.sourcemaps.calculateDecodedMappings(originalMap_1, function (raw) {
var rawPath = originalMap_1.sources[raw.sourceIndex];
var relativePath = originalMap_1.sourceRoot ? ts.combinePaths(originalMap_1.sourceRoot, rawPath) : rawPath;
var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath);
- var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
- var resolvedPath = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, true);
- var absolutePath = ts.getNormalizedAbsolutePath(resolvedPath, sourcesDirectoryPath);
+ if (!resolvedPathCache_1.has(combinedPath)) {
+ resolvedPathCache_1.set(combinedPath, ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath_1, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, true));
+ }
+ var resolvedPath = resolvedPathCache_1.get(combinedPath);
+ var absolutePath = ts.getNormalizedAbsolutePath(resolvedPath, sourcesDirectoryPath_1);
setupSourceEntry(absolutePath, originalMap_1.sourcesContent ? originalMap_1.sourcesContent[raw.sourceIndex] : null);
var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath);
encodeLastRecordedSourceMapSpan();
@@ -70335,11 +70342,6 @@ var ts;
}
ts.createSolutionBuilder = createSolutionBuilder;
function getUpToDateStatus(host, project) {
- if (project === undefined) {
- return {
- type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build"
- };
- }
if (project === undefined) {
return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
}
@@ -70415,6 +70417,7 @@ var ts;
}
var pseudoUpToDate = false;
var usesPrepend = false;
+ var upstreamChangedProject;
if (project.projectReferences && host.parseConfigFile) {
for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
var ref = _d[_c];
@@ -70438,6 +70441,7 @@ var ts;
}
if (refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
continue;
}
ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
@@ -70461,8 +70465,12 @@ var ts;
newerInputFileName: newestInputFileName
};
}
- if (usesPrepend) {
- pseudoUpToDate = false;
+ if (usesPrepend && pseudoUpToDate) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: upstreamChangedProject
+ };
}
return {
type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate,
diff --git a/lib/tsserver.js b/lib/tsserver.js
index de09a6a2e03..0fe2f989a21 100644
--- a/lib/tsserver.js
+++ b/lib/tsserver.js
@@ -65494,7 +65494,7 @@ var ts;
name: "typescript:assign",
scoped: false,
priority: 1,
- text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };"
+ text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };"
};
function createAssignHelper(context, attributesSegments) {
if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
@@ -69112,7 +69112,7 @@ var ts;
name: "typescript:extends",
scoped: false,
priority: 0,
- text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
+ text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
var templateObjectHelper = {
name: "typescript:makeTemplateObject",
@@ -76863,15 +76863,19 @@ var ts;
var firstLineColumnOffset_1 = writer.getColumn();
// First, decode the old component sourcemap
var originalMap_1 = parsed;
+ var sourcesDirectoryPath_1 = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
+ var resolvedPathCache_1 = ts.createMap();
ts.sourcemaps.calculateDecodedMappings(originalMap_1, function (raw) {
// Apply offsets to each position and fixup source entries
var rawPath = originalMap_1.sources[raw.sourceIndex];
var relativePath = originalMap_1.sourceRoot ? ts.combinePaths(originalMap_1.sourceRoot, rawPath) : rawPath;
var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath);
- var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
- var resolvedPath = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName,
- /*isAbsolutePathAnUrl*/ true);
- var absolutePath = ts.getNormalizedAbsolutePath(resolvedPath, sourcesDirectoryPath);
+ if (!resolvedPathCache_1.has(combinedPath)) {
+ resolvedPathCache_1.set(combinedPath, ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath_1, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName,
+ /*isAbsolutePathAnUrl*/ true));
+ }
+ var resolvedPath = resolvedPathCache_1.get(combinedPath);
+ var absolutePath = ts.getNormalizedAbsolutePath(resolvedPath, sourcesDirectoryPath_1);
// tslint:disable-next-line:no-null-keyword
setupSourceEntry(absolutePath, originalMap_1.sourcesContent ? originalMap_1.sourcesContent[raw.sourceIndex] : null); // TODO: Lookup content for inlining?
var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath);
@@ -82959,7 +82963,7 @@ var ts;
}
function parseProjectReferenceConfigFile(ref) {
// The actual filename (i.e. add "/tsconfig.json" if necessary)
- var refPath = resolveProjectReferencePath(host, ref); // TODO: GH#18217
+ var refPath = resolveProjectReferencePath(host, ref);
// An absolute path pointing to the containing directory of the config file
var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
@@ -86542,11 +86546,6 @@ var ts;
* Gets the UpToDateStatus for a project
*/
function getUpToDateStatus(host, project) {
- if (project === undefined) {
- return {
- type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build"
- };
- }
if (project === undefined) {
return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
}
@@ -86633,6 +86632,7 @@ var ts;
}
var pseudoUpToDate = false;
var usesPrepend = false;
+ var upstreamChangedProject;
if (project.projectReferences && host.parseConfigFile) {
for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
var ref = _d[_c];
@@ -86662,6 +86662,7 @@ var ts;
// *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
if (refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
continue;
}
// We have an output older than an upstream output - we are out of date
@@ -86686,8 +86687,12 @@ var ts;
newerInputFileName: newestInputFileName
};
}
- if (usesPrepend) {
- pseudoUpToDate = false;
+ if (usesPrepend && pseudoUpToDate) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: upstreamChangedProject
+ };
}
// Up to date
return {
@@ -86745,7 +86750,6 @@ var ts;
}
ts.formatUpToDateStatus = formatUpToDateStatus;
})(ts || (ts = {}));
-
//# sourceMappingURL=compiler.js.map
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
@@ -111803,7 +111807,6 @@ var TypeScript;
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-
//# sourceMappingURL=services.js.map
"use strict";
/* @internal */
@@ -112214,7 +112217,6 @@ var ts;
}());
ts.Semver = Semver;
})(ts || (ts = {}));
-
//# sourceMappingURL=jsTyping.js.map
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
@@ -118419,8 +118421,8 @@ var ts;
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-
//# sourceMappingURL=server.js.map
+// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types)
var ts;
(function (ts) {
var server;
@@ -118472,7 +118474,7 @@ var ts;
output: process.stdout,
terminal: false,
});
- var Logger = (function () {
+ var Logger = /** @class */ (function () {
function Logger(logFilename, traceToConsole, level) {
this.logFilename = logFilename;
this.traceToConsole = traceToConsole;
@@ -118486,6 +118488,7 @@ var ts;
this.fd = fs.openSync(this.logFilename, "w");
}
catch (_) {
+ // swallow the error and keep logging disabled if file cannot be opened
}
}
}
@@ -118546,7 +118549,8 @@ var ts;
Logger.prototype.write = function (s) {
if (this.fd >= 0) {
var buf = new Buffer(s);
- fs.writeSync(this.fd, buf, 0, buf.length, null);
+ // tslint:disable-next-line no-null-keyword
+ fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null); // TODO: GH#18217
}
if (this.traceToConsole) {
console.warn(s);
@@ -118554,7 +118558,7 @@ var ts;
};
return Logger;
}());
- var NodeTypingsInstaller = (function () {
+ var NodeTypingsInstaller = /** @class */ (function () {
function NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, event) {
this.telemetryEnabled = telemetryEnabled;
this.logger = logger;
@@ -118566,11 +118570,12 @@ var ts;
this.event = event;
this.activeRequestCount = 0;
this.requestQueue = [];
- this.requestMap = ts.createMap();
+ this.requestMap = ts.createMap(); // Maps operation ID to newest requestQueue entry with that ID
}
NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) {
+ // We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package.
var validationResult = ts.JsTyping.validatePackageName(name);
- if (validationResult !== 0) {
+ if (validationResult !== 0 /* Ok */) {
return false;
}
if (this.requestedRegistry) {
@@ -118616,6 +118621,8 @@ var ts;
var arg = _a[_i];
var match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg);
if (match) {
+ // if port is specified - use port + 1
+ // otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1
var currentPort = match[2] !== undefined
? +match[2]
: match[1].charAt(0) === "d" ? 5858 : 9229;
@@ -118681,6 +118688,7 @@ var ts;
}
this.packageInstalledPromise = undefined;
this.projectService.updateTypingsForProject(response);
+ // The behavior is the same as for setTypings, so send the same event.
this.event(response, "setTypings");
break;
}
@@ -118765,11 +118773,16 @@ var ts;
this.activeRequestCount++;
this.host.setTimeout(request.operation, NodeTypingsInstaller.requestDelayMillis);
};
+ // This number is essentially arbitrary. Processing more than one typings request
+ // at a time makes sense, but having too many in the pipe results in a hang
+ // (see https://github.com/nodejs/node/issues/7657).
+ // It would be preferable to base our limit on the amount of space left in the
+ // buffer, but we have yet to find a way to retrieve that value.
NodeTypingsInstaller.maxActiveRequestCount = 10;
NodeTypingsInstaller.requestDelayMillis = 100;
return NodeTypingsInstaller;
}());
- var IOSession = (function (_super) {
+ var IOSession = /** @class */ (function (_super) {
__extends(IOSession, _super);
function IOSession() {
var _this = this;
@@ -118778,6 +118791,10 @@ var ts;
_this.event(body, eventName);
}
else {
+ // It is unsafe to dereference `this` before initialization completes,
+ // so we defer until the next tick.
+ //
+ // Construction should finish before the next tick fires, so we do not need to do this recursively.
setImmediate(function () { return _this.event(body, eventName); });
}
};
@@ -118807,6 +118824,7 @@ var ts;
var s_1 = net.connect({ port: _this.eventPort }, function () {
_this.eventSocket = s_1;
if (_this.socketEventQueue) {
+ // flush queue.
for (var _i = 0, _a = _this.socketEventQueue; _i < _a.length; _i++) {
var event_1 = _a[_i];
_this.writeToEventSocket(event_1.body, event_1.eventName);
@@ -118890,13 +118908,13 @@ var ts;
function getEntireValue(initialIndex) {
var pathStart = args[initialIndex];
var extraPartCounter = 0;
- if (pathStart.charCodeAt(0) === 34 &&
- pathStart.charCodeAt(pathStart.length - 1) !== 34) {
+ if (pathStart.charCodeAt(0) === 34 /* doubleQuote */ &&
+ pathStart.charCodeAt(pathStart.length - 1) !== 34 /* doubleQuote */) {
for (var i = initialIndex + 1; i < args.length; i++) {
pathStart += " ";
pathStart += args[i];
extraPartCounter++;
- if (pathStart.charCodeAt(pathStart.length - 1) === 34)
+ if (pathStart.charCodeAt(pathStart.length - 1) === 34 /* doubleQuote */)
break;
}
}
@@ -118914,6 +118932,7 @@ var ts;
}
return undefined;
}
+ // TSS_LOG "{ level: "normal | verbose | terse", file?: string}"
function createLogger() {
var cmdLineLogFileName = server.findArgument("--logFile");
var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity"));
@@ -118924,8 +118943,12 @@ var ts;
? envLogOptions.file || (__dirname + "/.log" + process.pid.toString())
: undefined;
var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel;
- return new Logger(logFileName, envLogOptions.traceToConsole, logVerbosity);
+ return new Logger(logFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217
}
+ // This places log file in the directory containing editorServices.js
+ // TODO: check that this location is writable
+ // average async stat takes about 30 microseconds
+ // set chunk size to do 30 files in < 1 millisecond
function createPollingWatchedFileSet(interval, chunkSize) {
if (interval === void 0) { interval = 2500; }
if (chunkSize === void 0) { chunkSize = 30; }
@@ -118957,6 +118980,9 @@ var ts;
}
});
}
+ // this implementation uses polling and
+ // stat due to inconsistencies of fs.watch
+ // and efficiency of stat on modern filesystems
function startWatchTimer() {
setInterval(function () {
var count = 0;
@@ -118982,7 +119008,7 @@ var ts;
callback: callback,
mtime: sys.fileExists(fileName)
? getModifiedTime(fileName)
- : ts.missingFileModifiedTime
+ : ts.missingFileModifiedTime // Any subsequent modification will occur after this time
};
watchedFiles.push(file);
if (watchedFiles.length === 1) {
@@ -118994,6 +119020,19 @@ var ts;
ts.unorderedRemoveItem(watchedFiles, file);
}
}
+ // 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
+ // 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
+ // pause less than 1.5 milliseconds); question is
+ // do we anticipate reference sets in the 100s and
+ // do we care about waiting 10-20 seconds to detect
+ // changes for large reference sets? If so, do we want
+ // to increase the chunk size or decrease the interval
+ // time dynamically to match the large reference set?
var pollingWatchedFileSet = createPollingWatchedFileSet();
var pending = [];
var canWrite = true;
@@ -119015,30 +119054,40 @@ var ts;
function extractWatchDirectoryCacheKey(path, currentDriveKey) {
path = ts.normalizeSlashes(path);
if (isUNCPath(path)) {
+ // UNC path: extract server name
+ // //server/location
+ // ^ <- from 0 to this position
var firstSlash = path.indexOf(ts.directorySeparator, 2);
return firstSlash !== -1 ? path.substring(0, firstSlash).toLowerCase() : path;
}
var rootLength = ts.getRootLength(path);
if (rootLength === 0) {
+ // relative path - assume file is on the current drive
return currentDriveKey;
}
- if (path.charCodeAt(1) === 58 && path.charCodeAt(2) === 47) {
+ if (path.charCodeAt(1) === 58 /* colon */ && path.charCodeAt(2) === 47 /* slash */) {
+ // rooted path that starts with c:/... - extract drive letter
return path.charAt(0).toLowerCase();
}
- if (path.charCodeAt(0) === 47 && path.charCodeAt(1) !== 47) {
+ if (path.charCodeAt(0) === 47 /* slash */ && path.charCodeAt(1) !== 47 /* slash */) {
+ // rooted path that starts with slash - /somename - use key for current drive
return currentDriveKey;
}
+ // do not cache any other cases
return undefined;
}
function isUNCPath(s) {
- return s.length > 2 && s.charCodeAt(0) === 47 && s.charCodeAt(1) === 47;
+ return s.length > 2 && s.charCodeAt(0) === 47 /* slash */ && s.charCodeAt(1) === 47 /* slash */;
}
var logger = createLogger();
var sys = ts.sys;
var nodeVersion = ts.getNodeMajorVersion();
+ // use watchGuard process on Windows when node version is 4 or later
var useWatchGuard = process.platform === "win32" && nodeVersion >= 4;
var originalWatchDirectory = sys.watchDirectory.bind(sys);
var noopWatcher = { close: ts.noop };
+ // This is the function that catches the exceptions when watching directory, and yet lets project service continue to function
+ // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
function watchDirectorySwallowingException(path, callback, recursive) {
try {
return originalWatchDirectory(path, callback, recursive);
@@ -119049,7 +119098,7 @@ var ts;
}
}
if (useWatchGuard) {
- var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), undefined);
+ var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), /*currentDriveKey*/ undefined);
var statusCache_1 = ts.createMap();
sys.watchDirectory = function (path, callback, recursive) {
var cacheKey = extractWatchDirectoryCacheKey(path, currentDrive_1);
@@ -119083,9 +119132,11 @@ var ts;
logger.info("watchDirectory for " + path + " uses cached drive information.");
}
if (status) {
+ // this drive is safe to use - call real 'watchDirectory'
return watchDirectorySwallowingException(path, callback, recursive);
}
else {
+ // this drive is unsafe - return no-op watcher
return noopWatcher;
}
};
@@ -119093,6 +119144,7 @@ var ts;
else {
sys.watchDirectory = watchDirectorySwallowingException;
}
+ // Override sys.write because fs.writeSync is not reliable on Node 4
sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); };
sys.watchFile = function (fileName, callback) {
var watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
@@ -119136,7 +119188,7 @@ var ts;
ts.validateLocaleAndSetLanguage(localeStr, sys);
}
ts.setStackTraceLimit();
- var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
+ var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217
var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(sys.getExecutingFilePath(), "../typesMap.json");
var npmLocation = server.findArgument(server.Arguments.NpmLocation);
function parseStringArray(argName) {
@@ -119164,9 +119216,11 @@ var ts;
process.on("uncaughtException", function (err) {
ioSession.logError(err, "unknown");
});
+ // See https://github.com/Microsoft/TypeScript/issues/11348
+ // tslint:disable-next-line no-unnecessary-type-assertion-2
process.noAsar = true;
+ // Start listening
ioSession.listen();
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-
-//# sourceMappingURL=tsserver.js.map
+//# sourceMappingURL=tsserver.js.map
\ No newline at end of file
diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts
index 785921fa685..44036c3fe28 100644
--- a/lib/tsserverlibrary.d.ts
+++ b/lib/tsserverlibrary.d.ts
@@ -14,6 +14,7 @@ and limitations under the License.
***************************************************************************** */
+
declare namespace ts {
const versionMajorMinor = "3.0";
/** The version of the TypeScript compiler release */
@@ -12460,7 +12461,7 @@ declare namespace ts.server.protocol {
scope: OrganizeImportsScope;
}
interface OrganizeImportsResponse extends Response {
- edits: ReadonlyArray;
+ body: ReadonlyArray;
}
interface GetEditsForFileRenameRequest extends Request {
command: CommandTypes.GetEditsForFileRename;
@@ -12471,7 +12472,7 @@ declare namespace ts.server.protocol {
readonly newFilePath: string;
}
interface GetEditsForFileRenameResponse extends Response {
- edits: ReadonlyArray;
+ body: ReadonlyArray;
}
interface CodeFixRequest extends Request {
command: CommandTypes.GetCodeFixes;
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index d86ab147651..d9addcbcdbf 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -16,15 +16,22 @@ and limitations under the License.
declare namespace ts {
const versionMajorMinor = "3.0";
+ /** The version of the TypeScript compiler release */
const version: string;
}
declare namespace ts {
+ /**
+ * Type of objects whose values are all of the same type.
+ * The `in` and `for-in` operators can *not* be safely used,
+ * since `Object.prototype` may be modified by outside code.
+ */
interface MapLike {
[index: string]: T;
}
interface SortedArray extends Array {
" __sortedArrayBrand": any;
}
+ /** ES6 Map interface, only read methods included. */
interface ReadonlyMap {
get(key: string): T | undefined;
has(key: string): boolean;
@@ -34,11 +41,13 @@ declare namespace ts {
values(): Iterator;
entries(): Iterator<[string, T]>;
}
+ /** ES6 Map interface. */
interface Map extends ReadonlyMap {
set(key: string, value: T): this;
delete(key: string): boolean;
clear(): void;
}
+ /** ES6 Iterator type. */
interface Iterator {
next(): {
value: T;
@@ -48,6 +57,7 @@ declare namespace ts {
done: true;
};
}
+ /** Array that is only intended to be pushed to, never read. */
interface Push {
push(...values: T[]): void;
}
@@ -452,7 +462,9 @@ declare namespace ts {
}
enum JsxFlags {
None = 0,
+ /** An element from a named property of the JSX.IntrinsicElements interface */
IntrinsicNamedElement = 1,
+ /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 2,
IntrinsicElement = 3
}
@@ -492,6 +504,10 @@ declare namespace ts {
type ModifiersArray = NodeArray;
interface Identifier extends PrimaryExpression, Declaration {
kind: SyntaxKind.Identifier;
+ /**
+ * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.)
+ * Text of identifier, but if the identifier begins with two underscores, this will begin with three.
+ */
escapedText: __String;
originalKeywordKind?: SyntaxKind;
isInJSDocNamespace?: boolean;
@@ -635,6 +651,14 @@ declare namespace ts {
}
type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
type ArrayBindingElement = BindingElement | OmittedExpression;
+ /**
+ * Several node kinds share function-like features such as a signature,
+ * a name, and a body. These nodes should extend FunctionLikeDeclarationBase.
+ * Examples:
+ * - FunctionDeclaration
+ * - MethodDeclaration
+ * - AccessorDeclaration
+ */
interface FunctionLikeDeclarationBase extends SignatureDeclarationBase {
_functionLikeDeclarationBrand: any;
asteriskToken?: AsteriskToken;
@@ -642,6 +666,7 @@ declare namespace ts {
body?: Block | Expression;
}
type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction;
+ /** @deprecated Use SignatureDeclaration */
type FunctionLike = SignatureDeclaration;
interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement {
kind: SyntaxKind.FunctionDeclaration;
@@ -664,6 +689,7 @@ declare namespace ts {
parent: ClassLikeDeclaration;
body?: FunctionBody;
}
+ /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */
interface SemicolonClassElement extends ClassElement {
kind: SyntaxKind.SemicolonClassElement;
parent: ClassLikeDeclaration;
@@ -803,6 +829,7 @@ declare namespace ts {
interface UnaryExpression extends Expression {
_unaryExpressionBrand: any;
}
+ /** Deprecated, please use UpdateExpression */
type IncrementExpression = UpdateExpression;
interface UpdateExpression extends UnaryExpression {
_updateExpressionBrand: any;
@@ -984,6 +1011,12 @@ declare namespace ts {
parent: ArrayLiteralExpression | CallExpression | NewExpression;
expression: Expression;
}
+ /**
+ * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to
+ * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be
+ * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type
+ * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.)
+ */
interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration {
properties: NodeArray;
}
@@ -1000,6 +1033,7 @@ declare namespace ts {
interface SuperPropertyAccessExpression extends PropertyAccessExpression {
expression: SuperExpression;
}
+ /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */
interface PropertyAccessEntityNameExpression extends PropertyAccessExpression {
_propertyAccessExpressionLikeQualifiedNameBrand?: any;
expression: EntityNameExpression;
@@ -1136,6 +1170,9 @@ declare namespace ts {
interface NotEmittedStatement extends Statement {
kind: SyntaxKind.NotEmittedStatement;
}
+ /**
+ * A list of comma-separated expressions. This node is only created by transformations.
+ */
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
elements: NodeArray;
@@ -1272,6 +1309,7 @@ declare namespace ts {
}
interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement {
kind: SyntaxKind.ClassDeclaration;
+ /** May be undefined in `export default class { ... }`. */
name?: Identifier;
}
interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression {
@@ -1341,6 +1379,11 @@ declare namespace ts {
statements: NodeArray;
}
type ModuleReference = EntityName | ExternalModuleReference;
+ /**
+ * One of:
+ * - import x = require("mod");
+ * - import x = M.x;
+ */
interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer {
kind: SyntaxKind.ImportEqualsDeclaration;
parent: SourceFile | ModuleBlock;
@@ -1356,6 +1399,7 @@ declare namespace ts {
kind: SyntaxKind.ImportDeclaration;
parent: SourceFile | ModuleBlock;
importClause?: ImportClause;
+ /** If this is not a StringLiteral it will be a grammar error. */
moduleSpecifier: Expression;
}
type NamedImportBindings = NamespaceImport | NamedImports;
@@ -1377,7 +1421,9 @@ declare namespace ts {
interface ExportDeclaration extends DeclarationStatement {
kind: SyntaxKind.ExportDeclaration;
parent: SourceFile | ModuleBlock;
+ /** Will not be assigned in the case of `export * from "foo";` */
exportClause?: NamedExports;
+ /** If this is not a StringLiteral it will be a grammar error. */
moduleSpecifier?: Expression;
}
interface NamedImports extends Node {
@@ -1404,6 +1450,10 @@ declare namespace ts {
name: Identifier;
}
type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier;
+ /**
+ * This is either an `export =` or an `export default` declaration.
+ * Unless `isExportEquals` is set, this node was parsed as an `export default`.
+ */
interface ExportAssignment extends DeclarationStatement {
kind: SyntaxKind.ExportAssignment;
parent: SourceFile;
@@ -1474,6 +1524,10 @@ declare namespace ts {
interface JSDocUnknownTag extends JSDocTag {
kind: SyntaxKind.JSDocTag;
}
+ /**
+ * Note that `@extends` is a synonym of `@augments`.
+ * Both tags are represented by this interface.
+ */
interface JSDocAugmentsTag extends JSDocTag {
kind: SyntaxKind.JSDocAugmentsTag;
class: ExpressionWithTypeArguments & {
@@ -1523,6 +1577,7 @@ declare namespace ts {
parent: JSDoc;
name: EntityName;
typeExpression?: JSDocTypeExpression;
+ /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */
isNameFirst: boolean;
isBracketed: boolean;
}
@@ -1535,6 +1590,7 @@ declare namespace ts {
interface JSDocTypeLiteral extends JSDocType {
kind: SyntaxKind.JSDocTypeLiteral;
jsDocPropertyTags?: ReadonlyArray;
+ /** If true, then this type literal represents an *array* of its type. */
isArrayType?: boolean;
}
enum FlowFlags {
@@ -1615,6 +1671,14 @@ declare namespace ts {
libReferenceDirectives: ReadonlyArray;
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
+ /**
+ * lib.d.ts should have a reference comment like
+ *
+ * ///
+ *
+ * If any other file has this comment, it signals not to include lib.d.ts
+ * because this containing file is intended to act as a default library.
+ */
hasNoDefaultLib: boolean;
languageVersion: ScriptTarget;
}
@@ -1661,9 +1725,18 @@ declare namespace ts {
interface ParseConfigHost {
useCaseSensitiveFileNames: boolean;
readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[];
+ /**
+ * Gets a value indicating whether the specified path exists and is a file.
+ * @param path The path to test.
+ */
fileExists(path: string): boolean;
readFile(path: string): string | undefined;
}
+ /**
+ * Branded string for keeping track of when we've turned an ambiguous path
+ * specified like "./blah" to an absolute path to an actual
+ * tsconfig file, e.g. "/root/blah/tsconfig.json"
+ */
type ResolvedConfigFileName = string & {
_isResolvedConfigFileName: never;
};
@@ -1672,18 +1745,39 @@ declare namespace ts {
}
interface CancellationToken {
isCancellationRequested(): boolean;
+ /** @throws OperationCanceledException if isCancellationRequested is true */
throwIfCancellationRequested(): void;
}
interface Program extends ScriptReferenceHost {
+ /**
+ * Get a list of root file names that were passed to a 'createProgram'
+ */
getRootFileNames(): ReadonlyArray;
+ /**
+ * Get a list of files in the program
+ */
getSourceFiles(): ReadonlyArray;
+ /**
+ * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then
+ * the JavaScript and declaration files will be produced for all the files in this program.
+ * If targetSourceFile is specified, then only the JavaScript and declaration for that
+ * specific file will be generated.
+ *
+ * If writeFile is not specified then the writeFile callback from the compiler host will be
+ * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
+ * will be invoked when writing the JavaScript and declaration files.
+ */
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;
getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray;
getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray;
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray;
+ /** The first time this is called, it will return global diagnostics (no location). */
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray;
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray;
getConfigFileParsingDiagnostics(): ReadonlyArray;
+ /**
+ * Gets a type checker that can be used to semantically analyze source files in the program.
+ */
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
@@ -1693,16 +1787,25 @@ declare namespace ts {
sourceFile: SourceFile;
}
interface CustomTransformers {
+ /** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory[];
+ /** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory[];
+ /** Custom transformers to evaluate after built-in .d.ts transformations. */
afterDeclarations?: TransformerFactory[];
}
interface SourceMapSpan {
+ /** Line number in the .js file. */
emittedLine: number;
+ /** Column number in the .js file. */
emittedColumn: number;
+ /** Line number in the .ts file. */
sourceLine: number;
+ /** Column number in the .ts file. */
sourceColumn: number;
+ /** Optional name (index into names array) associated with this span. */
nameIndex?: number;
+ /** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
interface SourceMapData {
@@ -1717,6 +1820,7 @@ declare namespace ts {
sourceMapMappings: string;
sourceMapDecodedMappings: SourceMapSpan[];
}
+ /** Return code used by getEmitOutput function to indicate status of the function */
enum ExitStatus {
Success = 0,
DiagnosticsPresent_OutputsSkipped = 1,
@@ -1724,6 +1828,7 @@ declare namespace ts {
}
interface EmitResult {
emitSkipped: boolean;
+ /** Contains declaration emit diagnostics */
diagnostics: ReadonlyArray;
emittedFiles?: string[];
}
@@ -1741,21 +1846,41 @@ declare namespace ts {
getReturnTypeOfSignature(signature: Signature): Type;
getNullableType(type: Type, flags: TypeFlags): Type;
getNonNullableType(type: Type): Type;
+ /** Note that the resulting nodes cannot be checked. */
typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined;
+ /** Note that the resulting nodes cannot be checked. */
signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & {
typeArguments?: NodeArray;
}) | undefined;
+ /** Note that the resulting nodes cannot be checked. */
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined;
+ /** Note that the resulting nodes cannot be checked. */
symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined;
+ /** Note that the resulting nodes cannot be checked. */
symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined;
+ /** Note that the resulting nodes cannot be checked. */
symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined;
+ /** Note that the resulting nodes cannot be checked. */
symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined;
+ /** Note that the resulting nodes cannot be checked. */
typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol | undefined;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
+ /**
+ * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment.
+ * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value.
+ */
getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined;
+ /**
+ * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol.
+ * Otherwise returns its input.
+ * For example, at `export type T = number;`:
+ * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`.
+ * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol.
+ * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol.
+ */
getExportSymbolOfSymbol(symbol: Symbol): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeAtLocation(node: Node): Type | undefined;
@@ -1764,11 +1889,20 @@ declare namespace ts {
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string;
typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
+ /**
+ * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead
+ * This will be removed in a future version.
+ */
getSymbolDisplayBuilder(): SymbolDisplayBuilder;
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
getContextualType(node: Expression): Type | undefined;
+ /**
+ * returns unknownSignature in the case of an error.
+ * returns undefined if the node is not valid.
+ * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`.
+ */
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined;
@@ -1777,6 +1911,7 @@ declare namespace ts {
isUnknownSymbol(symbol: Symbol): boolean;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean;
+ /** Follow all aliases to get the original symbol. */
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
@@ -1790,6 +1925,11 @@ declare namespace ts {
getSuggestionForNonexistentModule(node: Identifier, target: Symbol): string | undefined;
getBaseConstraintOfType(type: Type): Type | undefined;
getDefaultFromTypeParameter(type: Type): Type | undefined;
+ /**
+ * Depending on the operation performed, it may be appropriate to throw away the checker
+ * if the cancellation token is triggered. Typically, if it is used for error checking
+ * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep.
+ */
runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T;
}
enum NodeBuilderFlags {
@@ -1842,7 +1982,7 @@ declare namespace ts {
InElementType = 2097152,
InFirstTypeArgument = 4194304,
InTypeAlias = 8388608,
- WriteOwnNameForAnyLike = 0,
+ /** @deprecated */ WriteOwnNameForAnyLike = 0,
NodeBuilderFlagsMask = 9469291
}
enum SymbolFormatFlags {
@@ -1852,19 +1992,25 @@ declare namespace ts {
AllowAnyNodeKind = 4,
UseAliasDefinedOutsideCurrentScope = 8
}
+ /**
+ * @deprecated
+ */
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(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
- buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
- buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
+ /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
+ /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
+ /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
+ /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
+ /**
+ * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString
+ */
interface SymbolWriter extends SymbolTracker {
writeKeyword(text: string): void;
writeOperator(text: string): void;
@@ -1985,11 +2131,20 @@ declare namespace ts {
ExportEquals = "export=",
Default = "default"
}
+ /**
+ * This represents a string whose leading underscore have been escaped by adding extra leading underscores.
+ * The shape of this brand is rather unique compared to others we've used.
+ * Instead of just an intersection of a string and an object, it is that union-ed
+ * with an intersection of void and an object. This makes it wholly incompatible
+ * with a normal string (which is good, it cannot be misused on assignment or on usage),
+ * while still being comparable with a normal string via === (also good) and castable from a string.
+ */
type __String = (string & {
__escapedIdentifier: void;
}) | (void & {
__escapedIdentifier: void;
}) | InternalSymbolName;
+ /** ReadonlyMap where keys are `__String`s. */
interface ReadonlyUnderscoreEscapedMap {
get(key: __String): T | undefined;
has(key: __String): boolean;
@@ -1999,11 +2154,13 @@ declare namespace ts {
values(): Iterator;
entries(): Iterator<[__String, T]>;
}
+ /** Map where keys are `__String`s. */
interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap {
set(key: __String, value: T): this;
delete(key: __String): boolean;
clear(): void;
}
+ /** SymbolTable based on ES6 Map interface. */
type SymbolTable = UnderscoreEscapedMap;
enum TypeFlags {
Any = 1,
@@ -2095,6 +2252,7 @@ declare namespace ts {
interface ObjectType extends Type {
objectFlags: ObjectFlags;
}
+ /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */
interface InterfaceType extends ObjectType {
typeParameters: TypeParameter[] | undefined;
outerTypeParameters: TypeParameter[] | undefined;
@@ -2109,6 +2267,16 @@ declare namespace ts {
declaredStringIndexInfo?: IndexInfo;
declaredNumberIndexInfo?: IndexInfo;
}
+ /**
+ * Type references (ObjectFlags.Reference). When a class or interface has type parameters or
+ * a "this" type, references to the class or interface are made using type references. The
+ * typeArguments property specifies the types to substitute for the type parameters of the
+ * class or interface and optionally includes an extra element that specifies the type to
+ * substitute for "this" in the resulting instantiation. When no extra argument is present,
+ * the type reference itself is substituted for "this". The typeArguments property is undefined
+ * if the class or interface has no type parameters and the reference isn't specifying an
+ * explicit "this" argument.
+ */
interface TypeReference extends ObjectType {
target: GenericType;
typeArguments?: Type[];
@@ -2193,6 +2361,7 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
+ /** @deprecated Use FileExtensionInfo instead. */
type JsFileExtensionInfo = FileExtensionInfo;
interface FileExtensionInfo {
extension: string;
@@ -2206,6 +2375,12 @@ declare namespace ts {
message: string;
reportsUnnecessary?: {};
}
+ /**
+ * A linked list of formatted diagnostic messages to be used as part of a multiline message.
+ * It is built from the bottom up, leaving the head to be the "main" diagnostic.
+ * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
+ * the difference is that messages are all preformatted in DMC.
+ */
interface DiagnosticMessageChain {
messageText: string;
category: DiagnosticCategory;
@@ -2214,6 +2389,7 @@ declare namespace ts {
}
interface Diagnostic extends DiagnosticRelatedInformation {
category: DiagnosticCategory;
+ /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
code: number;
source?: string;
@@ -2244,9 +2420,13 @@ declare namespace ts {
name: string;
}
interface ProjectReference {
+ /** A normalized path on disk */
path: string;
+ /** The path as the user originally wrote it */
originalPath?: string;
+ /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
prepend?: boolean;
+ /** True if it is intended that this reference form a circularity */
circular?: boolean;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined;
@@ -2323,6 +2503,7 @@ declare namespace ts {
traceResolution?: boolean;
resolveJsonModule?: boolean;
types?: string[];
+ /** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
@@ -2354,6 +2535,7 @@ declare namespace ts {
LineFeed = 1
}
interface LineAndCharacter {
+ /** 0-based. */
line: number;
character: number;
}
@@ -2365,6 +2547,10 @@ declare namespace ts {
TSX = 4,
External = 5,
JSON = 6,
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
Deferred = 7
}
enum ScriptTarget {
@@ -2382,6 +2568,7 @@ declare namespace ts {
Standard = 0,
JSX = 1
}
+ /** Either a parsed command line or a parsed tsconfig.json */
interface ParsedCommandLine {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
@@ -2422,21 +2609,57 @@ declare namespace ts {
readFile(fileName: string): string | undefined;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
+ /**
+ * Resolve a symbolic link.
+ * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options
+ */
realpath?(path: string): string;
getCurrentDirectory?(): string;
getDirectories?(path: string): string[];
}
+ /**
+ * Represents the result of module resolution.
+ * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off.
+ * The Program will then filter results based on these flags.
+ *
+ * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred.
+ */
interface ResolvedModule {
+ /** Path of the file the module was resolved to. */
resolvedFileName: string;
+ /** True if `resolvedFileName` comes from `node_modules`. */
isExternalLibraryImport?: boolean;
}
+ /**
+ * ResolvedModule with an explicitly provided `extension` property.
+ * Prefer this over `ResolvedModule`.
+ * If changing this, remember to change `moduleResolutionIsEqualTo`.
+ */
interface ResolvedModuleFull extends ResolvedModule {
+ /**
+ * Extension of resolvedFileName. This must match what's at the end of resolvedFileName.
+ * This is optional for backwards-compatibility, but will be added if not provided.
+ */
extension: Extension;
packageId?: PackageId;
}
+ /**
+ * Unique identifier with a package name and version.
+ * If changing this, remember to change `packageIdIsEqual`.
+ */
interface PackageId {
+ /**
+ * Name of the package.
+ * Should not include `@types`.
+ * If accessing a non-index file, this should include its name e.g. "foo/bar".
+ */
name: string;
+ /**
+ * Name of a submodule within this package.
+ * May be "".
+ */
subModuleName: string;
+ /** Version of the package, e.g. "1.2.3" */
version: string;
}
enum Extension {
@@ -2473,6 +2696,9 @@ declare namespace ts {
getNewLine(): string;
readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
+ /**
+ * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
+ */
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getEnvironmentVariable?(name: string): string | undefined;
createHash?(data: string): string;
@@ -2534,42 +2760,163 @@ declare namespace ts {
Unspecified = 4
}
interface TransformationContext {
+ /** Gets the compiler options supplied to the transformer. */
getCompilerOptions(): CompilerOptions;
+ /** Starts a new lexical environment. */
startLexicalEnvironment(): void;
+ /** Suspends the current lexical environment, usually after visiting a parameter list. */
suspendLexicalEnvironment(): void;
+ /** Resumes a suspended lexical environment, usually before visiting a function body. */
resumeLexicalEnvironment(): void;
+ /** Ends a lexical environment, returning any declarations. */
endLexicalEnvironment(): Statement[] | undefined;
+ /** Hoists a function declaration to the containing scope. */
hoistFunctionDeclaration(node: FunctionDeclaration): void;
+ /** Hoists a variable declaration to the containing scope. */
hoistVariableDeclaration(node: Identifier): void;
+ /** Records a request for a non-scoped emit helper in the current context. */
requestEmitHelper(helper: EmitHelper): void;
+ /** Gets and resets the requested non-scoped emit helpers. */
readEmitHelpers(): EmitHelper[] | undefined;
+ /** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */
enableSubstitution(kind: SyntaxKind): void;
+ /** Determines whether expression substitutions are enabled for the provided node. */
isSubstitutionEnabled(node: Node): boolean;
+ /**
+ * Hook used by transformers to substitute expressions just before they
+ * are emitted by the pretty printer.
+ *
+ * NOTE: Transformation hooks should only be modified during `Transformer` initialization,
+ * before returning the `NodeTransformer` callback.
+ */
onSubstituteNode: (hint: EmitHint, node: Node) => Node;
+ /**
+ * Enables before/after emit notifications in the pretty printer for the provided
+ * SyntaxKind.
+ */
enableEmitNotification(kind: SyntaxKind): void;
+ /**
+ * Determines whether before/after emit notifications should be raised in the pretty
+ * printer when it emits a node.
+ */
isEmitNotificationEnabled(node: Node): boolean;
+ /**
+ * Hook used to allow transformers to capture state before or after
+ * the printer emits a node.
+ *
+ * NOTE: Transformation hooks should only be modified during `Transformer` initialization,
+ * before returning the `NodeTransformer` callback.
+ */
onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void;
}
interface TransformationResult {
+ /** Gets the transformed source files. */
transformed: T[];
+ /** Gets diagnostics for the transformation. */
diagnostics?: DiagnosticWithLocation[];
+ /**
+ * Gets a substitute for a node, if one is available; otherwise, returns the original node.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to substitute.
+ */
substituteNode(hint: EmitHint, node: Node): Node;
+ /**
+ * Emits a node with possible notification.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to emit.
+ * @param emitCallback A callback used to emit the node.
+ */
emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
+ /**
+ * Clean up EmitNode entries on any parse-tree nodes.
+ */
dispose(): void;
}
+ /**
+ * A function that is used to initialize and return a `Transformer` callback, which in turn
+ * will be used to transform one or more nodes.
+ */
type TransformerFactory = (context: TransformationContext) => Transformer;
+ /**
+ * A function that transforms a node.
+ */
type Transformer = (node: T) => T;
+ /**
+ * A function that accepts and possibly transforms a node.
+ */
type Visitor = (node: Node) => VisitResult;
type VisitResult = T | T[] | undefined;
interface Printer {
+ /**
+ * Print a node and its subtree as-is, without any emit transformations.
+ * @param hint A value indicating the purpose of a node. This is primarily used to
+ * distinguish between an `Identifier` used in an expression position, versus an
+ * `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you
+ * should just pass `Unspecified`.
+ * @param node The node to print. The node and its subtree are printed as-is, without any
+ * emit transformations.
+ * @param sourceFile A source file that provides context for the node. The source text of
+ * the file is used to emit the original source content for literals and identifiers, while
+ * the identifiers of the source file are used when generating unique names to avoid
+ * collisions.
+ */
printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string;
+ /**
+ * Prints a list of nodes using the given format flags
+ */
printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string;
+ /**
+ * Prints a source file as-is, without any emit transformations.
+ */
printFile(sourceFile: SourceFile): string;
+ /**
+ * Prints a bundle of source files as-is, without any emit transformations.
+ */
printBundle(bundle: Bundle): string;
}
interface PrintHandlers {
+ /**
+ * A hook used by the Printer when generating unique names to avoid collisions with
+ * globally defined names that exist outside of the current source file.
+ */
hasGlobalName?(name: string): boolean;
+ /**
+ * A hook used by the Printer to provide notifications prior to emitting a node. A
+ * compatible implementation **must** invoke `emitCallback` with the provided `hint` and
+ * `node` values.
+ * @param hint A hint indicating the intended purpose of the node.
+ * @param node The node to emit.
+ * @param emitCallback A callback that, when invoked, will emit the node.
+ * @example
+ * ```ts
+ * var printer = createPrinter(printerOptions, {
+ * onEmitNode(hint, node, emitCallback) {
+ * // set up or track state prior to emitting the node...
+ * emitCallback(hint, node);
+ * // restore state after emitting the node...
+ * }
+ * });
+ * ```
+ */
onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void;
+ /**
+ * A hook used by the Printer to perform just-in-time substitution of a node. This is
+ * primarily used by node transformations that need to substitute one node for another,
+ * such as replacing `myExportedVar` with `exports.myExportedVar`.
+ * @param hint A hint indicating the intended purpose of the node.
+ * @param node The node to emit.
+ * @example
+ * ```ts
+ * var printer = createPrinter(printerOptions, {
+ * substituteNode(hint, node) {
+ * // perform substitution if necessary...
+ * return node;
+ * }
+ * });
+ * ```
+ */
substituteNode?(hint: EmitHint, node: Node): Node;
}
interface PrinterOptions {
@@ -2582,6 +2929,7 @@ declare namespace ts {
directoryExists?(directoryName: string): boolean;
getCurrentDirectory?(): string;
}
+ /** @deprecated See comment on SymbolWriter */
interface SymbolTracker {
trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
reportInaccessibleThisError?(): void;
@@ -2684,6 +3032,10 @@ declare namespace ts {
readFile(path: string, encoding?: string): string | undefined;
getFileSize?(path: string): number;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
+ /**
+ * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that
+ * use native OS file watching
+ */
watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
@@ -2697,7 +3049,11 @@ declare namespace ts {
getModifiedTime?(path: string): Date;
setModifiedTime?(path: string, time: Date): void;
deleteFile?(path: string): void;
+ /**
+ * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
+ */
createHash?(data: string): string;
+ /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
@@ -2751,6 +3107,7 @@ declare namespace ts {
function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number;
function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter;
function isWhiteSpaceLike(ch: number): boolean;
+ /** Does not include line breaks. For that, see isWhiteSpaceLike. */
function isWhiteSpaceSingleLine(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function couldStartTrivia(text: string, pos: number): boolean;
@@ -2762,11 +3119,13 @@ declare namespace ts {
function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
+ /** Optionally, get the shebang */
function getShebang(text: string): string | undefined;
function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
+/** Non-internal stuff goes here */
declare namespace ts {
function isExternalModuleNameRelative(moduleName: string): boolean;
function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[];
@@ -2790,6 +3149,14 @@ declare namespace ts {
function textChangeRangeIsUnchanged(range: TextChangeRange): boolean;
function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange;
let unchangedTextChangeRange: TextChangeRange;
+ /**
+ * Called to merge all the changes that occurred across several versions of a script snapshot
+ * into a single change. i.e. if a user keeps making successive edits to a script we will
+ * have a text change from V1 to V2, V2 to V3, ..., Vn.
+ *
+ * This function will then merge those changes into a single change range valid between V1 and
+ * Vn.
+ */
function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration | undefined;
type ParameterPropertyDeclaration = ParameterDeclaration & {
@@ -2801,6 +3168,10 @@ declare namespace ts {
function isEmptyBindingElement(node: BindingElement): boolean;
function getCombinedModifierFlags(node: Node): ModifierFlags;
function getCombinedNodeFlags(node: Node): NodeFlags;
+ /**
+ * Checks to see if the locale is in the appropriate format,
+ * and if it is, attempts to set the appropriate language.
+ */
function validateLocaleAndSetLanguage(locale: string, sys: {
getExecutingFilePath(): string;
resolvePath(path: string): string;
@@ -2811,26 +3182,100 @@ declare namespace ts {
function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T;
function getOriginalNode(node: Node | undefined): Node | undefined;
function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined;
+ /**
+ * Gets a value indicating whether a node originated in the parse tree.
+ *
+ * @param node The node to test.
+ */
function isParseTreeNode(node: Node): boolean;
+ /**
+ * Gets the original parse tree node for a node.
+ *
+ * @param node The original node.
+ * @returns The original parse tree node if found; otherwise, undefined.
+ */
function getParseTreeNode(node: Node): Node;
+ /**
+ * Gets the original parse tree node for a node.
+ *
+ * @param node The original node.
+ * @param nodeTest A callback used to ensure the correct type of parse tree node is returned.
+ * @returns The original parse tree node if found; otherwise, undefined.
+ */
function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined;
+ /**
+ * Remove extra underscore from escaped identifier text content.
+ *
+ * @param identifier The escaped identifier text.
+ * @returns The unescaped identifier text.
+ */
function unescapeLeadingUnderscores(identifier: __String): string;
function idText(identifier: Identifier): string;
function symbolName(symbol: Symbol): string;
+ /**
+ * Remove extra underscore from escaped identifier text content.
+ * @deprecated Use `id.text` for the unescaped text.
+ * @param identifier The escaped identifier text.
+ * @returns The unescaped identifier text.
+ */
function unescapeIdentifier(id: string): string;
function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined;
function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName;
+ /**
+ * Gets the JSDoc parameter tags for the node if present.
+ *
+ * @remarks Returns any JSDoc param tag that matches the provided
+ * parameter, whether a param tag on a containing function
+ * expression, or a param tag on a variable declaration whose
+ * initializer is the containing function. The tags closest to the
+ * node are returned first, so in the previous example, the param
+ * tag on the containing function expression would be first.
+ *
+ * Does not return tags for binding patterns, because JSDoc matches
+ * parameters by name and binding patterns do not have a name.
+ */
function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray;
+ /**
+ * Return true if the node has JSDoc parameter tags.
+ *
+ * @remarks Includes parameter tags that are not directly on the node,
+ * for example on a variable declaration whose initializer is a function expression.
+ */
function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean;
+ /** Gets the JSDoc augments tag for the node if present */
function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined;
+ /** Gets the JSDoc class tag for the node if present */
function getJSDocClassTag(node: Node): JSDocClassTag | undefined;
+ /** Gets the JSDoc this tag for the node if present */
function getJSDocThisTag(node: Node): JSDocThisTag | undefined;
+ /** Gets the JSDoc return tag for the node if present */
function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined;
+ /** Gets the JSDoc template tag for the node if present */
function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined;
+ /** Gets the JSDoc type tag for the node if present and valid */
function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined;
+ /**
+ * Gets the type node for the node if provided via JSDoc.
+ *
+ * @remarks The search includes any JSDoc param tag that relates
+ * to the provided parameter, for example a type tag on the
+ * parameter itself, or a param tag on a containing function
+ * expression, or a param tag on a variable declaration whose
+ * initializer is the containing function. The tags closest to the
+ * node are examined first, so in the previous example, the type
+ * tag directly on the node would be returned.
+ */
function getJSDocType(node: Node): TypeNode | undefined;
+ /**
+ * Gets the return type node for the node if provided via JSDoc's return tag.
+ *
+ * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
+ * gets the type from inside the braces.
+ */
function getJSDocReturnType(node: Node): TypeNode | undefined;
+ /** Get all JSDoc tags related to a node, including those on parent nodes. */
function getJSDocTags(node: Node): ReadonlyArray;
+ /** Gets all JSDoc tags of a specified kind, or undefined if not present. */
function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray;
}
declare namespace ts {
@@ -3001,6 +3446,11 @@ declare namespace ts {
function isJSDocSignature(node: Node): node is JSDocSignature;
}
declare namespace ts {
+ /**
+ * True if node is of some token syntax kind.
+ * For example, this is true for an IfKeyword but not for an IfStatement.
+ * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
+ */
function isToken(n: Node): boolean;
function isLiteralExpression(node: Node): node is LiteralExpression;
type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail;
@@ -3018,6 +3468,11 @@ declare namespace ts {
function isTypeElement(node: Node): node is TypeElement;
function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement;
function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike;
+ /**
+ * Node test that determines whether a node is a valid type node.
+ * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
+ * of a TypeNode.
+ */
function isTypeNode(node: Node): node is TypeNode;
function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode;
function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName;
@@ -3029,6 +3484,7 @@ declare namespace ts {
function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement;
function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement;
function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause;
+ /** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node: Node): boolean;
function isSetAccessor(node: Node): node is SetAccessorDeclaration;
function isGetAccessor(node: Node): node is GetAccessorDeclaration;
@@ -3037,9 +3493,27 @@ declare namespace ts {
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
+ /**
+ * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
+ * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
+ * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
+ * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
+ *
+ * @param node a given node to visit its children
+ * @param cbNode a callback to be invoked for all child nodes
+ * @param cbNodes a callback to be invoked for embedded array
+ *
+ * @remarks `forEachChild` must visit the children of a node in the order
+ * that they appear in the source code. The language service depends on this property to locate nodes by position.
+ */
function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined;
+ /**
+ * Parse json text into SyntaxTree and return node and parse errors if any
+ * @param fileName
+ * @param sourceText
+ */
function parseJsonText(fileName: string, sourceText: string): JsonSourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
@@ -3047,24 +3521,66 @@ declare namespace ts {
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine;
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
+ /**
+ * Reports config file diagnostics
+ */
interface ConfigFileDiagnosticsReporter {
+ /**
+ * Reports unrecoverable error when parsing config file
+ */
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
+ /**
+ * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
+ */
interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
getCurrentDirectory(): string;
}
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
+ /**
+ * Read tsconfig.json file
+ * @param fileName The path to the config file
+ */
function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): {
config?: any;
error?: Diagnostic;
};
+ /**
+ * Parse the text of the tsconfig.json file
+ * @param fileName The path to the config file
+ * @param jsonText The text of the config file
+ */
function parseConfigFileTextToJson(fileName: string, jsonText: string): {
config?: any;
error?: Diagnostic;
};
+ /**
+ * Read tsconfig.json file
+ * @param fileName The path to the config file
+ */
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
+ /**
+ * Convert the json syntax tree into the json value
+ */
function convertToObject(sourceFile: JsonSourceFile, errors: Push): any;
+ /**
+ * Parse the contents of a config file (tsconfig.json).
+ * @param json The contents of the config file to parse
+ * @param host Instance of ParseConfigHost used to enumerate files in folder.
+ * @param basePath A root directory to resolve relative path entries in the config
+ * file to. e.g. outDir
+ */
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ /**
+ * Parse the contents of a config file (tsconfig.json).
+ * @param jsonNode The contents of the config file to parse
+ * @param host Instance of ParseConfigHost used to enumerate files in folder.
+ * @param basePath A root directory to resolve relative path entries in the config
+ * file to. e.g. outDir
+ */
function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
@@ -3077,11 +3593,32 @@ declare namespace ts {
}
declare namespace ts {
function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined;
+ /**
+ * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
+ * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
+ * is assumed to be the same as root directory of the project.
+ */
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
+ /**
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[];
+ /**
+ * Cached module resolutions per containing directory.
+ * This assumes that any module id will have the same resolution for sibling files located in the same folder.
+ */
interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache {
getOrCreateCacheForDirectory(directoryName: string): Map;
}
+ /**
+ * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory
+ * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive.
+ */
interface NonRelativeModuleNameResolutionCache {
getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache;
}
@@ -3097,6 +3634,7 @@ declare namespace ts {
}
declare namespace ts {
function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray;
+ /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */
function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral;
function createLiteral(value: number): NumericLiteral;
function createLiteral(value: boolean): BooleanLiteral;
@@ -3106,11 +3644,17 @@ declare namespace ts {
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
+ /** Create a unique temporary variable. */
function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier;
+ /** Create a unique temporary variable for use in a loop. */
function createLoopVariable(): Identifier;
+ /** Create a unique name based on the supplied text. */
function createUniqueName(text: string): Identifier;
+ /** Create a unique name based on the supplied text. */
function createOptimisticUniqueName(text: string): Identifier;
+ /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text: string): Identifier;
+ /** Create a unique name generated for a node. */
function getGeneratedNameForNode(node: Node): Identifier;
function createToken(token: TKind): Token;
function createSuper(): SuperExpression;
@@ -3379,8 +3923,25 @@ declare namespace ts {
function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember;
function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember;
function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]): SourceFile;
+ /**
+ * Creates a shallow, memberwise clone of a node for mutation.
+ */
function getMutableClone(node: T): T;
+ /**
+ * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
+ * order to preserve comments.
+ *
+ * @param original The original statement.
+ */
function createNotEmittedStatement(original: Node): NotEmittedStatement;
+ /**
+ * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
+ * order to preserve comments or sourcemap positions.
+ *
+ * @param expression The inner expression to emit.
+ * @param original The original outer expression.
+ * @param location The location for the expression. Defaults to the positions from "original" if provided.
+ */
function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression;
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray): CommaListExpression;
@@ -3410,15 +3971,43 @@ declare namespace ts {
function createVoidZero(): VoidExpression;
function createExportDefault(expression: Expression): ExportAssignment;
function createExternalModuleExport(exportName: Identifier): ExportDeclaration;
+ /**
+ * Clears any EmitNode entries from parse-tree nodes.
+ * @param sourceFile A source file.
+ */
function disposeEmitNodes(sourceFile: SourceFile): void;
function setTextRange(range: T, location: TextRange | undefined): T;
+ /**
+ * Sets flags that control emit behavior of a node.
+ */
function setEmitFlags(node: T, emitFlags: EmitFlags): T;
+ /**
+ * Gets a custom text range to use when emitting source maps.
+ */
function getSourceMapRange(node: Node): SourceMapRange;
+ /**
+ * Sets a custom text range to use when emitting source maps.
+ */
function setSourceMapRange(node: T, range: SourceMapRange | undefined): T;
+ /**
+ * Create an external source map source file reference
+ */
function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource;
+ /**
+ * Gets the TextRange to use for source maps for a token of a node.
+ */
function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined;
+ /**
+ * Sets the TextRange to use for source maps for a token of a node.
+ */
function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T;
+ /**
+ * Gets a custom text range to use when emitting comments.
+ */
function getCommentRange(node: Node): TextRange;
+ /**
+ * Sets a custom text range to use when emitting comments.
+ */
function setCommentRange(node: T, range: TextRange): T;
function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T;
@@ -3427,26 +4016,115 @@ declare namespace ts {
function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T;
function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
function moveSyntheticComments(node: T, original: Node): T;
+ /**
+ * Gets the constant value to emit for an expression.
+ */
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
+ /**
+ * Sets the constant value to emit for an expression.
+ */
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression;
+ /**
+ * Adds an EmitHelper to a node.
+ */
function addEmitHelper(node: T, helper: EmitHelper): T;
+ /**
+ * Add EmitHelpers to a node.
+ */
function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T;
+ /**
+ * Removes an EmitHelper from a node.
+ */
function removeEmitHelper(node: Node, helper: EmitHelper): boolean;
+ /**
+ * Gets the EmitHelpers of a node.
+ */
function getEmitHelpers(node: Node): EmitHelper[] | undefined;
+ /**
+ * Moves matching emit helpers from a source node to a target node.
+ */
function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void;
function setOriginalNode(node: T, original: Node | undefined): T;
}
declare namespace ts {
+ /**
+ * Visits a Node using the supplied visitor, possibly returning a new Node in its place.
+ *
+ * @param node The Node to visit.
+ * @param visitor The callback used to visit the Node.
+ * @param test A callback to execute to verify the Node is valid.
+ * @param lift An optional callback to execute to lift a NodeArray into a valid Node.
+ */
function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T;
+ /**
+ * Visits a Node using the supplied visitor, possibly returning a new Node in its place.
+ *
+ * @param node The Node to visit.
+ * @param visitor The callback used to visit the Node.
+ * @param test A callback to execute to verify the Node is valid.
+ * @param lift An optional callback to execute to lift a NodeArray into a valid Node.
+ */
function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined;
+ /**
+ * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
+ *
+ * @param nodes The NodeArray to visit.
+ * @param visitor The callback used to visit a Node.
+ * @param test A node test to execute for each node.
+ * @param start An optional value indicating the starting offset at which to start visiting.
+ * @param count An optional value indicating the maximum number of nodes to visit.
+ */
function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray;
+ /**
+ * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
+ *
+ * @param nodes The NodeArray to visit.
+ * @param visitor The callback used to visit a Node.
+ * @param test A node test to execute for each node.
+ * @param start An optional value indicating the starting offset at which to start visiting.
+ * @param count An optional value indicating the maximum number of nodes to visit.
+ */
function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | undefined;
+ /**
+ * Starts a new lexical environment and visits a statement list, ending the lexical environment
+ * and merging hoisted declarations upon completion.
+ */
function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean): NodeArray;
+ /**
+ * Starts a new lexical environment and visits a parameter list, suspending the lexical
+ * environment upon completion.
+ */
function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray;
+ /**
+ * Resumes a suspended lexical environment and visits a function body, ending the lexical
+ * environment and merging hoisted declarations upon completion.
+ */
function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody;
+ /**
+ * Resumes a suspended lexical environment and visits a function body, ending the lexical
+ * environment and merging hoisted declarations upon completion.
+ */
function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined;
+ /**
+ * Resumes a suspended lexical environment and visits a concise body, ending the lexical
+ * environment and merging hoisted declarations upon completion.
+ */
function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody;
+ /**
+ * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
+ *
+ * @param node The Node whose children will be visited.
+ * @param visitor The callback used to visit each child.
+ * @param context A lexical environment context for the visitor.
+ */
function visitEachChild(node: T, visitor: Visitor, context: TransformationContext): T;
+ /**
+ * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
+ *
+ * @param node The Node whose children will be visited.
+ * @param visitor The callback used to visit each child.
+ * @param context A lexical environment context for the visitor.
+ */
function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined;
}
declare namespace ts {
@@ -3467,8 +4145,35 @@ declare namespace ts {
function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string;
function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray;
+ /**
+ * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
+ * that represent a compilation unit.
+ *
+ * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
+ * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
+ *
+ * @param createProgramOptions - The options for creating a program.
+ * @returns A 'Program' object.
+ */
function createProgram(createProgramOptions: CreateProgramOptions): Program;
+ /**
+ * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
+ * that represent a compilation unit.
+ *
+ * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
+ * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
+ *
+ * @param rootNames - A set of root files.
+ * @param options - The compiler options which should be used.
+ * @param host - The host interacts with the underlying file system.
+ * @param oldProgram - Reuses an old program structure.
+ * @param configFileParsingDiagnostics - error during config file parsing
+ * @returns A 'Program' object.
+ */
function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program;
+ /**
+ * Returns the target config filename of a project reference
+ */
function resolveProjectReferencePath(host: CompilerHost | UpToDateHost, ref: ProjectReference): ResolvedConfigFileName;
}
declare namespace ts {
@@ -3488,43 +4193,137 @@ declare namespace ts {
affected: SourceFile | Program;
} | undefined;
interface BuilderProgramHost {
+ /**
+ * return true if file names are treated with case sensitivity
+ */
useCaseSensitiveFileNames(): boolean;
+ /**
+ * If provided this would be used this hash instead of actual file shape text for detecting changes
+ */
createHash?: (data: string) => string;
+ /**
+ * When emit or emitNextAffectedFile are called without writeFile,
+ * this callback if present would be used to write files
+ */
writeFile?: WriteFileCallback;
}
+ /**
+ * Builder to manage the program state changes
+ */
interface BuilderProgram {
+ /**
+ * Returns current program
+ */
getProgram(): Program;
+ /**
+ * Get compiler options of the program
+ */
getCompilerOptions(): CompilerOptions;
+ /**
+ * Get the source file in the program with file name
+ */
getSourceFile(fileName: string): SourceFile | undefined;
+ /**
+ * Get a list of files in the program
+ */
getSourceFiles(): ReadonlyArray;
+ /**
+ * Get the diagnostics for compiler options
+ */
getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray;
+ /**
+ * Get the diagnostics that dont belong to any file
+ */
getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray;
+ /**
+ * Get the diagnostics from config file parsing
+ */
getConfigFileParsingDiagnostics(): ReadonlyArray;
+ /**
+ * Get the syntax diagnostics, for all source files if source file is not supplied
+ */
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray;
+ /**
+ * Get all the dependencies of the file
+ */
getAllDependencies(sourceFile: SourceFile): ReadonlyArray;
+ /**
+ * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
+ * The semantic diagnostics are cached and managed here
+ * Note that it is assumed that when asked about semantic diagnostics through this API,
+ * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
+ * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
+ * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
+ */
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray;
+ /**
+ * Emits the JavaScript and declaration files.
+ * When targetSource file is specified, emits the files corresponding to that source file,
+ * otherwise for the whole program.
+ * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
+ * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
+ * it will only emit all the affected files instead of whole program
+ *
+ * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
+ * in that order would be used to write the files
+ */
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;
+ /**
+ * Get the current directory of the program
+ */
getCurrentDirectory(): string;
}
+ /**
+ * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files
+ */
interface SemanticDiagnosticsBuilderProgram extends BuilderProgram {
+ /**
+ * Gets the semantic diagnostics from the program for the next affected file and caches it
+ * Returns undefined if the iteration is complete
+ */
getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>;
}
+ /**
+ * The builder that can handle the changes in program and iterate through changed file to emit the files
+ * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files
+ */
interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram {
+ /**
+ * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
+ * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
+ * in that order would be used to write the files
+ */
emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult;
}
+ /**
+ * Create the builder to manage semantic diagnostics and cache them
+ */
function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram;
function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram;
+ /**
+ * Create the builder that can handle the changes in program and iterate through changed files
+ * to emit the those files and manage semantic diagnostics cache as well
+ */
function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram;
function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram;
+ /**
+ * Creates a builder thats just abstraction over program and can be used with watch
+ */
function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram;
function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram;
}
declare namespace ts {
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
+ /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T;
interface WatchCompilerHost {
+ /**
+ * Used to create the program when need for program creation or recreation detected
+ */
createProgram: CreateProgram;
+ /** If provided, callback to invoke after every new program creation */
afterProgramCreate?(program: T): void;
+ /** If provided, called with Diagnostic message that informs about change in watch status */
onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
@@ -3532,41 +4331,92 @@ declare namespace ts {
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
createHash?(data: string): string;
+ /**
+ * Use to check file presence for source files and
+ * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well
+ */
fileExists(path: string): boolean;
+ /**
+ * Use to read file text for source files and
+ * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well
+ */
readFile(path: string, encoding?: string): string | undefined;
+ /** If provided, used for module resolution as well as to handle directory structure */
directoryExists?(path: string): boolean;
+ /** If provided, used in resolutions as well as handling directory structure */
getDirectories?(path: string): string[];
+ /** If provided, used to cache and handle directory structure modifications */
readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[];
+ /** Symbol links resolution */
realpath?(path: string): string;
+ /** If provided would be used to write log about compilation */
trace?(s: string): void;
+ /** If provided is used to get the environment variable */
getEnvironmentVariable?(name: string): string | undefined;
+ /** If provided, used to resolve the module names, otherwise typescript's default module resolution */
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
+ /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
+ /** Used to watch changes in source files, missing files needed to update the program or config file */
watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher;
+ /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */
watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
+ /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */
setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
+ /** If provided, will be used to reset existing delayed compilation */
clearTimeout?(timeoutId: any): void;
}
+ /**
+ * Host to create watch with root files and options
+ */
interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost {
+ /** root files to use to generate program */
rootFiles: string[];
+ /** Compiler options */
options: CompilerOptions;
}
+ /**
+ * Host to create watch with config file
+ */
interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter {
+ /** Name of the config file to compile */
configFileName: string;
+ /** Options to extend */
optionsToExtend?: CompilerOptions;
+ /**
+ * Used to generate source file names from the config file and its include, exclude, files rules
+ * and also to cache the directory stucture
+ */
readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[];
}
interface Watch {
+ /** Synchronize with host and get updated program */
getProgram(): T;
}
+ /**
+ * Creates the watch what generates program using the config file
+ */
interface WatchOfConfigFile extends Watch {
}
+ /**
+ * Creates the watch that generates program using the root files and compiler options
+ */
interface WatchOfFilesAndCompilerOptions extends Watch {
+ /** Updates the root files in the program, only if this is not config file compilation */
updateRootFileNames(fileNames: string[]): void;
}
+ /**
+ * Create the watch compiler host for either configFile or fileNames and its options
+ */
function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions;
function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile;
+ /**
+ * Creates the watch from the host for root files and compiler options
+ */
function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions;
+ /**
+ * Creates the watch from the host for config file
+ */
function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile;
}
declare namespace ts {
@@ -3576,9 +4426,28 @@ declare namespace ts {
errorDiagnostic(diag: Diagnostic): void;
message(diag: DiagnosticMessage, ...args: string[]): void;
}
+ /**
+ * A BuildContext tracks what's going on during the course of a build.
+ *
+ * Callers may invoke any number of build requests within the same context;
+ * until the context is reset, each project will only be built at most once.
+ *
+ * Example: In a standard setup where project B depends on project A, and both are out of date,
+ * a failed build of A will result in A remaining out of date. When we try to build
+ * B, we should immediately bail instead of recomputing A's up-to-date status again.
+ *
+ * This also matters for performing fast (i.e. fake) downstream builds of projects
+ * when their upstream .d.ts files haven't changed content (but have newer timestamps)
+ */
interface BuildContext {
options: BuildOptions;
+ /**
+ * Map from output file name to its pre-build timestamp
+ */
unchangedOutputs: FileMap;
+ /**
+ * Map from config file name to up-to-date status
+ */
projectStatus: FileMap;
invalidatedProjects: FileMap;
queuedProjects: FileMap;
@@ -3597,23 +4466,42 @@ declare namespace ts {
enum UpToDateStatusType {
Unbuildable = 0,
UpToDate = 1,
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
+ */
UpToDateWithUpstreamTypes = 2,
OutputMissing = 3,
OutOfDateWithSelf = 4,
OutOfDateWithUpstream = 5,
UpstreamOutOfDate = 6,
UpstreamBlocked = 7,
+ /**
+ * Projects with no outputs (i.e. "solution" files)
+ */
ContainerOnly = 8
}
type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly;
namespace Status {
+ /**
+ * The project can't be built at all in its current state. For example,
+ * its config file cannot be parsed, or it has a syntax error or missing file
+ */
interface Unbuildable {
type: UpToDateStatusType.Unbuildable;
reason: string;
}
+ /**
+ * This project doesn't have any outputs, so "is it up to date" is a meaningless question.
+ */
interface ContainerOnly {
type: UpToDateStatusType.ContainerOnly;
}
+ /**
+ * The project is up to date with respect to its inputs.
+ * We track what the newest input file is.
+ */
interface UpToDate {
type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes;
newestInputFileTime: Date;
@@ -3623,23 +4511,42 @@ declare namespace ts {
newestOutputFileName: string;
oldestOutputFileName: string;
}
+ /**
+ * One or more of the outputs of the project does not exist.
+ */
interface OutputMissing {
type: UpToDateStatusType.OutputMissing;
+ /**
+ * The name of the first output file that didn't exist
+ */
missingOutputFileName: string;
}
+ /**
+ * One or more of the project's outputs is older than its newest input.
+ */
interface OutOfDateWithSelf {
type: UpToDateStatusType.OutOfDateWithSelf;
outOfDateOutputFileName: string;
newerInputFileName: string;
}
+ /**
+ * This project depends on an out-of-date project, so shouldn't be built yet
+ */
interface UpstreamOutOfDate {
type: UpToDateStatusType.UpstreamOutOfDate;
upstreamProjectName: string;
}
+ /**
+ * This project depends an upstream project with build errors
+ */
interface UpstreamBlocked {
type: UpToDateStatusType.UpstreamBlocked;
upstreamProjectName: string;
}
+ /**
+ * One or more of the project's outputs is older than the newest output of
+ * an upstream project.
+ */
interface OutOfDateWithUpstream {
type: UpToDateStatusType.OutOfDateWithUpstream;
outOfDateOutputFileName: string;
@@ -3662,6 +4569,10 @@ declare namespace ts {
};
function createBuildContext(options: BuildOptions): BuildContext;
function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined;
+ /**
+ * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but
+ * can dynamically add/remove other projects based on changes on the rootNames' references
+ */
function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): {
buildAllProjects: () => ExitStatus;
getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus;
@@ -3675,6 +4586,9 @@ declare namespace ts {
resolveProjectName: (name: string) => ResolvedConfigFileName | undefined;
startWatching: () => void;
};
+ /**
+ * Gets the UpToDateStatus for a project
+ */
function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus;
function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray;
function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined;
@@ -3754,10 +4668,25 @@ declare namespace ts {
interface SourceMapSource {
getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
}
+ /**
+ * Represents an immutable snapshot of a script at a specified time.Once acquired, the
+ * snapshot is observably immutable. i.e. the same calls with the same parameters will return
+ * the same values.
+ */
interface IScriptSnapshot {
+ /** Gets a portion of the script snapshot specified by [start, end). */
getText(start: number, end: number): string;
+ /** Gets the length of this script snapshot. */
getLength(): number;
+ /**
+ * Gets the TextChangeRange that describe how the text changed between this text and
+ * an older version. This information is used by the incremental parser to determine
+ * what sections of the script need to be re-parsed. 'undefined' can be returned if the
+ * change range cannot be determined. However, in that case, incremental parsing will
+ * not happen and the entire document will be re - parsed.
+ */
getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined;
+ /** Releases all resources held by this script snapshot */
dispose?(): void;
}
namespace ScriptSnapshot {
@@ -3804,6 +4733,9 @@ declare namespace ts {
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
+ /**
+ * Gets a set of custom transformers to use during emit.
+ */
getCustomTransformers?(): CustomTransformers | undefined;
isKnownTypesPackageName?(name: string): boolean;
installPackage?(options: InstallPackageOptions): Promise;
@@ -3819,10 +4751,17 @@ declare namespace ts {
interface LanguageService {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[];
+ /** The first time this is called, it will return global diagnostics (no location). */
getSemanticDiagnostics(fileName: string): Diagnostic[];
getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[];
getCompilerOptionsDiagnostics(): Diagnostic[];
+ /**
+ * @deprecated Use getEncodedSyntacticClassifications instead.
+ */
getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
+ /**
+ * @deprecated Use getEncodedSemanticClassifications instead.
+ */
getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications;
getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications;
@@ -3842,6 +4781,7 @@ declare namespace ts {
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined;
findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined;
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined;
+ /** @deprecated */
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined;
getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
@@ -3855,6 +4795,10 @@ declare namespace ts {
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
+ /**
+ * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag.
+ * Editors should call this after `>` is typed.
+ */
getJsxClosingTagAtPosition(fileName: string, position: number): JsxClosingTagInfo | undefined;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined;
toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
@@ -3863,8 +4807,11 @@ declare namespace ts {
applyCodeActionCommand(action: CodeActionCommand): Promise;
applyCodeActionCommand(action: CodeActionCommand[]): Promise;
applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise;
+ /** @deprecated `fileName` will be ignored */
applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise;
+ /** @deprecated `fileName` will be ignored */
applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise;
+ /** @deprecated `fileName` will be ignored */
applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise;
getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[];
getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined;
@@ -3884,8 +4831,11 @@ declare namespace ts {
type OrganizeImportsScope = CombinedCodeFixScope;
type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
+ /** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
triggerCharacter?: CompletionsTriggerCharacter;
+ /** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
+ /** @deprecated Use includeCompletionsWithInsertText */
includeInsertTextCompletions?: boolean;
}
interface ApplyCodeActionCommandResult {
@@ -3899,6 +4849,12 @@ declare namespace ts {
textSpan: TextSpan;
classificationType: ClassificationTypeNames;
}
+ /**
+ * Navigation bar interface designed for visual studio's dual-column layout.
+ * This does not form a proper tree.
+ * The navbar is returned as a list of top-level items, each of which has a list of child items.
+ * Child items always have an empty array for their `childItems`.
+ */
interface NavigationBarItem {
text: string;
kind: ScriptElementKind;
@@ -3909,12 +4865,23 @@ declare namespace ts {
bolded: boolean;
grayed: boolean;
}
+ /**
+ * Node in a tree of nested declarations in a file.
+ * The top node is always a script or module node.
+ */
interface NavigationTree {
+ /** Name of the declaration, or a short description, e.g. "". */
text: string;
kind: ScriptElementKind;
+ /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */
kindModifiers: string;
+ /**
+ * Spans of the nodes that generated this declaration.
+ * There will be more than one if this is the result of merging.
+ */
spans: TextSpan[];
nameSpan: TextSpan | undefined;
+ /** Present if non-empty */
childItems?: NavigationTree[];
}
interface TodoCommentDescriptor {
@@ -3936,12 +4903,23 @@ declare namespace ts {
isNewFile?: boolean;
}
interface CodeAction {
+ /** Description of the code action to display in the UI of the editor */
description: string;
+ /** Text changes to apply to each file as part of the code action */
changes: FileTextChanges[];
+ /**
+ * If the user accepts the code fix, the editor should send the action back in a `applyAction` request.
+ * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix.
+ */
commands?: CodeActionCommand[];
}
interface CodeFixAction extends CodeAction {
+ /** Short name to identify the fix, for use by telemetry. */
fixName: string;
+ /**
+ * If present, one may call 'getCombinedCodeFix' with this fixId.
+ * This may be omitted to indicate that the code fix can't be applied in a group.
+ */
fixId?: {};
fixAllDescription?: string;
}
@@ -3952,16 +4930,49 @@ declare namespace ts {
type CodeActionCommand = InstallPackageAction;
interface InstallPackageAction {
}
+ /**
+ * A set of one or more available refactoring actions, grouped under a parent refactoring.
+ */
interface ApplicableRefactorInfo {
+ /**
+ * The programmatic name of the refactoring
+ */
name: string;
+ /**
+ * A description of this refactoring category to show to the user.
+ * If the refactoring gets inlined (see below), this text will not be visible.
+ */
description: string;
+ /**
+ * Inlineable refactorings can have their actions hoisted out to the top level
+ * of a context menu. Non-inlineanable refactorings should always be shown inside
+ * their parent grouping.
+ *
+ * If not specified, this value is assumed to be 'true'
+ */
inlineable?: boolean;
actions: RefactorActionInfo[];
}
+ /**
+ * Represents a single refactoring action - for example, the "Extract Method..." refactor might
+ * offer several actions, each corresponding to a surround class or closure to extract into.
+ */
interface RefactorActionInfo {
+ /**
+ * The programmatic name of the refactoring action
+ */
name: string;
+ /**
+ * A description of this refactoring action to show to the user.
+ * If the parent refactoring is inlined away, this will be the only text shown,
+ * so this description should make sense by itself if the parent is inlineable=true
+ */
description: string;
}
+ /**
+ * A set of edits to make in response to a refactor action, plus an optional
+ * location where renaming should be invoked from
+ */
interface RefactorEditInfo {
edits: FileTextChanges[];
renameFilename?: string;
@@ -3970,11 +4981,16 @@ declare namespace ts {
}
interface TextInsertion {
newText: string;
+ /** The position in newText the caret should point to after the insertion. */
caretOffset: number;
}
interface DocumentSpan {
textSpan: TextSpan;
fileName: string;
+ /**
+ * If the span represents a location that was remapped (e.g. via a .d.ts.map file),
+ * then the original filename and span will be specified here
+ */
originalTextSpan?: TextSpan;
originalFileName?: string;
}
@@ -4146,6 +5162,13 @@ declare namespace ts {
displayParts: SymbolDisplayPart[];
isOptional: boolean;
}
+ /**
+ * Represents a single signature to show in signature help.
+ * The id is used for subsequent calls into the language service to ask questions about the
+ * signature help item in the context of any documents that have been updated. i.e. after
+ * an edit has happened, while signature help is still active, the host can ask important
+ * questions like 'what parameter is the user currently contained within?'.
+ */
interface SignatureHelpItem {
isVariadic: boolean;
prefixDisplayParts: SymbolDisplayPart[];
@@ -4155,6 +5178,9 @@ declare namespace ts {
documentation: SymbolDisplayPart[];
tags: JSDocTagInfo[];
}
+ /**
+ * Represents a set of signature help items, and the preferred item that should be selected.
+ */
interface SignatureHelpItems {
items: SignatureHelpItem[];
applicableSpan: TextSpan;
@@ -4163,8 +5189,12 @@ declare namespace ts {
argumentCount: number;
}
interface CompletionInfo {
+ /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */
isGlobalCompletion: boolean;
isMemberCompletion: boolean;
+ /**
+ * true when the current location also allows for a new identifier
+ */
isNewIdentifierLocation: boolean;
entries: CompletionEntry[];
}
@@ -4174,6 +5204,11 @@ declare namespace ts {
kindModifiers?: string;
sortText: string;
insertText?: string;
+ /**
+ * An optional span that indicates the text to be replaced by this completion item.
+ * If present, this span should be used instead of the default one.
+ * It will be set if the required span differs from the one generated by the default replacement behavior.
+ */
replacementSpan?: TextSpan;
hasAction?: true;
source?: string;
@@ -4190,16 +5225,30 @@ declare namespace ts {
source?: SymbolDisplayPart[];
}
interface OutliningSpan {
+ /** The span of the document to actually collapse. */
textSpan: TextSpan;
+ /** The span of the document to display when the user hovers over the collapsed span. */
hintSpan: TextSpan;
+ /** The text to display in the editor for the collapsed region. */
bannerText: string;
+ /**
+ * Whether or not this region should be automatically collapsed when
+ * the 'Collapse to Definitions' command is invoked.
+ */
autoCollapse: boolean;
+ /**
+ * Classification of the contents of the span
+ */
kind: OutliningSpanKind;
}
enum OutliningSpanKind {
+ /** Single or multi-line comments */
Comment = "comment",
+ /** Sections marked by '// #region' and '// #endregion' comments */
Region = "region",
+ /** Declarations and expressions */
Code = "code",
+ /** Contiguous blocks of import declarations */
Imports = "imports"
}
enum OutputFileType {
@@ -4236,33 +5285,82 @@ declare namespace ts {
classification: TokenClass;
}
interface Classifier {
+ /**
+ * Gives lexical classifications of tokens on a line without any syntactic context.
+ * For instance, a token consisting of the text 'string' can be either an identifier
+ * named 'string' or the keyword 'string', however, because this classifier is not aware,
+ * it relies on certain heuristics to give acceptable results. For classifications where
+ * speed trumps accuracy, this function is preferable; however, for true accuracy, the
+ * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the
+ * lexical, syntactic, and semantic classifiers may issue the best user experience.
+ *
+ * @param text The text of a line to classify.
+ * @param lexState The state of the lexical classifier at the end of the previous line.
+ * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier.
+ * If there is no syntactic classifier (syntacticClassifierAbsent=true),
+ * certain heuristics may be used in its place; however, if there is a
+ * syntactic classifier (syntacticClassifierAbsent=false), certain
+ * classifications which may be incorrectly categorized will be given
+ * back as Identifiers in order to allow the syntactic classifier to
+ * subsume the classification.
+ * @deprecated Use getLexicalClassifications instead.
+ */
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult;
getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications;
}
enum ScriptElementKind {
unknown = "",
warning = "warning",
+ /** predefined type (void) or keyword (class) */
keyword = "keyword",
+ /** top level script node */
scriptElement = "script",
+ /** module foo {} */
moduleElement = "module",
+ /** class X {} */
classElement = "class",
+ /** var x = class X {} */
localClassElement = "local class",
+ /** interface Y {} */
interfaceElement = "interface",
+ /** type T = ... */
typeElement = "type",
+ /** enum E */
enumElement = "enum",
enumMemberElement = "enum member",
+ /**
+ * Inside module and script only
+ * const v = ..
+ */
variableElement = "var",
+ /** Inside function */
localVariableElement = "local var",
+ /**
+ * Inside module and script only
+ * function f() { }
+ */
functionElement = "function",
+ /** Inside function */
localFunctionElement = "local function",
+ /** class X { [public|private]* foo() {} } */
memberFunctionElement = "method",
+ /** class X { [public|private]* [get|set] foo:number; } */
memberGetAccessorElement = "getter",
memberSetAccessorElement = "setter",
+ /**
+ * class X { [public|private]* foo:number; }
+ * interface Y { foo:number; }
+ */
memberVariableElement = "property",
+ /** class X { constructor() { } } */
constructorImplementationElement = "constructor",
+ /** interface Y { ():number; } */
callSignatureElement = "call",
+ /** interface Y { []:number; } */
indexSignatureElement = "index",
+ /** interface Y { new():Y; } */
constructSignatureElement = "construct",
+ /** function foo(*Y*: string) */
parameterElement = "parameter",
typeParameterElement = "type parameter",
primitiveType = "primitive type",
@@ -4272,7 +5370,11 @@ declare namespace ts {
letElement = "let",
directory = "directory",
externalModuleName = "external module name",
+ /**
+ *
+ */
jsxAttribute = "JSX attribute",
+ /** String literal */
string = "string"
}
enum ScriptElementKindModifier {
@@ -4342,12 +5444,62 @@ declare namespace ts {
function createClassifier(): Classifier;
}
declare namespace ts {
+ /**
+ * The document registry represents a store of SourceFile objects that can be shared between
+ * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST)
+ * of files in the context.
+ * SourceFile objects account for most of the memory usage by the language service. Sharing
+ * the same DocumentRegistry instance between different instances of LanguageService allow
+ * for more efficient memory utilization since all projects will share at least the library
+ * file (lib.d.ts).
+ *
+ * A more advanced use of the document registry is to serialize sourceFile objects to disk
+ * and re-hydrate them when needed.
+ *
+ * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it
+ * to all subsequent createLanguageService calls.
+ */
interface DocumentRegistry {
+ /**
+ * Request a stored SourceFile with a given fileName and compilationSettings.
+ * The first call to acquire will call createLanguageServiceSourceFile to generate
+ * the SourceFile if was not found in the registry.
+ *
+ * @param fileName The name of the file requested
+ * @param compilationSettings Some compilation settings like target affects the
+ * shape of a the resulting SourceFile. This allows the DocumentRegistry to store
+ * multiple copies of the same file for different compilation settings.
+ * @param scriptSnapshot Text of the file. Only used if the file was not found
+ * in the registry and a new one was created.
+ * @param version Current version of the file. Only used if the file was not found
+ * in the registry and a new one was created.
+ */
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
+ /**
+ * Request an updated version of an already existing SourceFile with a given fileName
+ * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
+ * to get an updated SourceFile.
+ *
+ * @param fileName The name of the file requested
+ * @param compilationSettings Some compilation settings like target affects the
+ * shape of a the resulting SourceFile. This allows the DocumentRegistry to store
+ * multiple copies of the same file for different compilation settings.
+ * @param scriptSnapshot Text of the file.
+ * @param version Current version of the file.
+ */
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
+ /**
+ * Informs the DocumentRegistry that a file is not needed any longer.
+ *
+ * Note: It is not allowed to call release on a SourceFile that was not acquired from
+ * this registry originally.
+ *
+ * @param fileName The name of the file to be released
+ * @param compilationSettings The compilation settings used to acquire the file
+ */
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
reportStats(): string;
@@ -4378,6 +5530,7 @@ declare namespace ts {
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
}
declare namespace ts {
+ /** The version of the language service API */
const servicesVersion = "0.8";
function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings;
function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string;
@@ -4387,10 +5540,21 @@ declare namespace ts {
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService;
+ /**
+ * Get the path of the default library files (lib.d.ts) as distributed with the typescript
+ * node package.
+ * The functionality is not supported if the ts module is consumed outside of a node module.
+ */
function getDefaultLibFilePath(options: CompilerOptions): string;
}
declare namespace ts {
+ /**
+ * Transform one or more nodes using the supplied transformers.
+ * @param source A single `Node` or an array of `Node` objects.
+ * @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
+ * @param compilerOptions Optional compiler options.
+ */
function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult;
}
//# sourceMappingURL=typescriptServices.d.ts.map
-export = ts;
\ No newline at end of file
+export = ts
\ No newline at end of file
diff --git a/lib/typescript.js b/lib/typescript.js
index 6794e291e7c..c1ead6a1fac 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -15,22 +15,28 @@ and limitations under the License.
"use strict";
-var __assign = (this && this.__assign) || Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
};
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ var extendStatics = function (d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ }
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
@@ -39,10 +45,14 @@ var __extends = (this && this.__extends) || (function () {
})();
var ts;
(function (ts) {
+ // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
+ // If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.0";
+ /** The version of the TypeScript compiler release */
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
+ /* @internal */
var Comparison;
(function (Comparison) {
Comparison[Comparison["LessThan"] = -1] = "LessThan";
@@ -50,13 +60,19 @@ var ts;
Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
})(Comparison = ts.Comparison || (ts.Comparison = {}));
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
+ /** Create a MapLike with good performance. */
function createDictionaryObject() {
- var map = Object.create(null);
+ var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
+ // Using 'delete' on an object causes V8 to put the object in dictionary mode.
+ // This disables creation of hidden classes, which are expensive when an object is
+ // constantly changing shape.
map.__ = undefined;
delete map.__;
return map;
}
+ /** Create a new map. If a template object is provided, the map will copy entries from it. */
function createMap() {
return new ts.MapCtr();
}
@@ -72,6 +88,8 @@ var ts;
ts.createMapFromEntries = createMapFromEntries;
function createMapFromTemplate(template) {
var map = new ts.MapCtr();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
for (var key in template) {
if (hasOwnProperty.call(template, key)) {
map.set(key, template[key]);
@@ -80,9 +98,12 @@ var ts;
return map;
}
ts.createMapFromTemplate = createMapFromTemplate;
+ // Internet Explorer's Map doesn't support iteration, so don't use it.
+ // tslint:disable-next-line no-in-operator variable-name
ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
+ // Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
- var MapIterator = (function () {
+ var MapIterator = /** @class */ (function () {
function MapIterator(data, selector) {
this.index = 0;
this.data = data;
@@ -99,7 +120,7 @@ var ts;
};
return MapIterator;
}());
- return (function () {
+ return /** @class */ (function () {
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
@@ -115,6 +136,7 @@ var ts;
return this;
};
class_1.prototype.has = function (key) {
+ // tslint:disable-next-line:no-in-operator
return key in this.data;
};
class_1.prototype.delete = function (key) {
@@ -150,6 +172,11 @@ var ts;
return array ? array.length : 0;
}
ts.length = length;
+ /**
+ * Iterates through 'array' by index and performs the callback on each element of array until the callback
+ * returns a truthy value, then returns that value.
+ * If no such value is found, the callback is applied to each element of array and undefined is returned.
+ */
function forEach(array, callback) {
if (array) {
for (var i = 0; i < array.length; i++) {
@@ -162,6 +189,7 @@ var ts;
return undefined;
}
ts.forEach = forEach;
+ /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
function firstDefined(array, callback) {
if (array === undefined) {
return undefined;
@@ -220,6 +248,11 @@ var ts;
return map;
}
ts.zipToMap = zipToMap;
+ /**
+ * Iterates through `array` by index and performs the callback on each element of array until the callback
+ * returns a falsey value, then returns false.
+ * If no such value is found, the callback is applied to each element of array and `true` is returned.
+ */
function every(array, callback) {
if (array) {
for (var i = 0; i < array.length; i++) {
@@ -251,6 +284,7 @@ var ts;
return undefined;
}
ts.findLast = findLast;
+ /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
function findIndex(array, predicate, startIndex) {
for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
@@ -269,6 +303,10 @@ var ts;
return -1;
}
ts.findLastIndex = findLastIndex;
+ /**
+ * Returns the first truthy result of `callback`, or else fails.
+ * This is like `forEach`, but never returns undefined.
+ */
function findMap(array, callback) {
for (var i = 0; i < array.length; i++) {
var result = callback(array[i], i);
@@ -599,6 +637,7 @@ var ts;
return false;
}
ts.some = some;
+ /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
function getRangesWhere(arr, pred, cb) {
var start;
for (var i = 0; i < arr.length; i++) {
@@ -625,6 +664,8 @@ var ts;
}
ts.concatenate = concatenate;
function deduplicateRelational(array, equalityComparer, comparer) {
+ // Perform a stable sort of the array. This ensures the first entry in a list of
+ // duplicates remains the first entry in the result.
var indices = array.map(function (_, i) { return i; });
stableSortIndices(array, indices, comparer);
var last = array[indices[0]];
@@ -637,6 +678,7 @@ var ts;
last = item;
}
}
+ // restore original order
deduplicated.sort();
return deduplicated.map(function (i) { return array[i]; });
}
@@ -666,10 +708,13 @@ var ts;
for (var i = 1; i < array.length; i++) {
var next = array[i];
switch (comparer(next, last)) {
+ // equality comparison
case true:
- case 0:
+ // relational comparison
+ case 0 /* EqualTo */:
continue;
- case -1:
+ case -1 /* LessThan */:
+ // If `array` is sorted, `next` should **never** be less than `last`.
return Debug.fail("Array is unsorted.");
}
deduplicated.push(last = next);
@@ -725,25 +770,41 @@ var ts;
return result || array;
}
ts.compact = compact;
+ /**
+ * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
+ * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
+ * based on the provided comparer.
+ */
function relativeComplement(arrayA, arrayB, comparer) {
if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
return arrayB;
var result = [];
loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
if (offsetB > 0) {
- Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0);
+ // Ensure `arrayB` is properly sorted.
+ Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
}
loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
if (offsetA > startA) {
- Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0);
+ // Ensure `arrayA` is properly sorted. We only need to perform this check if
+ // `offsetA` has changed since we entered the loop.
+ Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
}
switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
- case -1:
+ case -1 /* LessThan */:
+ // If B is less than A, B does not exist in arrayA. Add B to the result and
+ // move to the next element in arrayB without changing the current position
+ // in arrayA.
result.push(arrayB[offsetB]);
continue loopB;
- case 0:
+ case 0 /* EqualTo */:
+ // If B is equal to A, B exists in arrayA. Move to the next element in
+ // arrayB without adding B to the result or changing the current position
+ // in arrayA.
continue loopB;
- case 1:
+ case 1 /* GreaterThan */:
+ // If B is greater than A, we need to keep looking for B in arrayA. Move to
+ // the next element in arrayA and recheck.
continue loopA;
}
}
@@ -769,6 +830,10 @@ var ts;
return to;
}
ts.append = append;
+ /**
+ * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
+ * position offset from the end of the array.
+ */
function toOffset(array, offset) {
return offset < 0 ? array.length + offset : offset;
}
@@ -787,6 +852,9 @@ var ts;
return to;
}
ts.addRange = addRange;
+ /**
+ * @return Whether the value was added.
+ */
function pushIfUnique(array, toAdd, equalityComparer) {
if (contains(array, toAdd, equalityComparer)) {
return false;
@@ -797,6 +865,9 @@ var ts;
}
}
ts.pushIfUnique = pushIfUnique;
+ /**
+ * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
+ */
function appendIfUnique(array, toAdd, equalityComparer) {
if (array) {
pushIfUnique(array, toAdd, equalityComparer);
@@ -808,8 +879,12 @@ var ts;
}
ts.appendIfUnique = appendIfUnique;
function stableSortIndices(array, indices, comparer) {
+ // sort indices by value then position
indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
}
+ /**
+ * Returns a new sorted array.
+ */
function sort(array, comparer) {
return array.slice().sort(comparer);
}
@@ -844,6 +919,9 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ /**
+ * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
+ */
function stableSort(array, comparer) {
var indices = array.map(function (_, i) { return i; });
stableSortIndices(array, indices, comparer);
@@ -860,6 +938,10 @@ var ts;
return true;
}
ts.rangeEquals = rangeEquals;
+ /**
+ * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
+ * A negative offset indicates the element should be retrieved from the end of the array.
+ */
function elementAt(array, offset) {
if (array) {
offset = toOffset(array, offset);
@@ -870,6 +952,9 @@ var ts;
return undefined;
}
ts.elementAt = elementAt;
+ /**
+ * Returns the first element of an array if non-empty, `undefined` otherwise.
+ */
function firstOrUndefined(array) {
return array.length === 0 ? undefined : array[0];
}
@@ -879,6 +964,9 @@ var ts;
return array[0];
}
ts.first = first;
+ /**
+ * Returns the last element of an array if non-empty, `undefined` otherwise.
+ */
function lastOrUndefined(array) {
return array.length === 0 ? undefined : array[array.length - 1];
}
@@ -888,6 +976,9 @@ var ts;
return array[array.length - 1];
}
ts.last = last;
+ /**
+ * Returns the only element of an array if it contains only one element, `undefined` otherwise.
+ */
function singleOrUndefined(array) {
return array && array.length === 1
? array[0]
@@ -906,6 +997,17 @@ var ts;
return result;
}
ts.replaceElement = replaceElement;
+ /**
+ * Performs a binary search, finding the index at which `value` occurs in `array`.
+ * If no such index is found, returns the 2's-complement of first index at which
+ * `array[index]` exceeds `value`.
+ * @param array A sorted array whose first element must be no larger than number
+ * @param value The value to be searched for in the array.
+ * @param keySelector A callback used to select the search key from `value` and each element of
+ * `array`.
+ * @param keyComparer A callback used to compare two keys in a sorted array.
+ * @param offset An offset into `array` at which to start the search.
+ */
function binarySearch(array, value, keySelector, keyComparer, offset) {
if (!array || array.length === 0) {
return -1;
@@ -917,12 +1019,12 @@ var ts;
var middle = low + ((high - low) >> 1);
var midKey = keySelector(array[middle]);
switch (keyComparer(midKey, key)) {
- case -1:
+ case -1 /* LessThan */:
low = middle + 1;
break;
- case 0:
+ case 0 /* EqualTo */:
return middle;
- case 1:
+ case 1 /* GreaterThan */:
high = middle - 1;
break;
}
@@ -955,14 +1057,29 @@ var ts;
}
ts.reduceLeft = reduceLeft;
var hasOwnProperty = Object.prototype.hasOwnProperty;
+ /**
+ * Indicates whether a map-like contains an own property with the specified key.
+ *
+ * @param map A map-like.
+ * @param key A property key.
+ */
function hasProperty(map, key) {
return hasOwnProperty.call(map, key);
}
ts.hasProperty = hasProperty;
+ /**
+ * Gets the value of an owned property in a map-like.
+ *
+ * @param map A map-like.
+ * @param key A property key.
+ */
function getProperty(map, key) {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
}
ts.getProperty = getProperty;
+ /**
+ * Gets the owned, enumerable property keys of a map-like.
+ */
function getOwnKeys(map) {
var keys = [];
for (var key in map) {
@@ -1001,13 +1118,19 @@ var ts;
var arg = args_1[_a];
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p];
+ t[p] = arg[p]; // TODO: GH#23368
}
}
}
return t;
}
ts.assign = assign;
+ /**
+ * Performs a shallow equality comparison of the contents of two map-likes.
+ *
+ * @param left A map-like whose properties should be compared.
+ * @param right A map-like whose properties should be compared.
+ */
function equalOwnProperties(left, right, equalityComparer) {
if (equalityComparer === void 0) { equalityComparer = equateValues; }
if (left === right)
@@ -1118,6 +1241,9 @@ var ts;
}
}
}
+ /**
+ * Tests whether a value is an array.
+ */
function isArray(value) {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
@@ -1126,6 +1252,9 @@ var ts;
return isArray(value) ? value : [value];
}
ts.toArray = toArray;
+ /**
+ * Tests whether a value is string
+ */
function isString(text) {
return typeof text === "string";
}
@@ -1140,16 +1269,22 @@ var ts;
return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'.");
}
ts.cast = cast;
- function noop(_) { }
+ /** Does nothing. */
+ function noop(_) { } // tslint:disable-line no-empty
ts.noop = noop;
+ /** Do nothing and return false */
function returnFalse() { return false; }
ts.returnFalse = returnFalse;
+ /** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
+ /** Returns lower case string */
function toLowerCase(x) { return x.toLowerCase(); }
ts.toLowerCase = toLowerCase;
+ /** Throws an error because a function is not implemented. */
function notImplemented() {
throw new Error("Not implemented");
}
@@ -1224,7 +1359,7 @@ var ts;
})(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
var Debug;
(function (Debug) {
- Debug.currentAssertionLevel = 0;
+ Debug.currentAssertionLevel = 0 /* None */;
Debug.isDebugging = false;
function shouldAssert(level) {
return Debug.currentAssertionLevel >= level;
@@ -1310,6 +1445,14 @@ var ts;
return a === b;
}
ts.equateValues = equateValues;
+ /**
+ * Compare the equality of two strings using a case-sensitive ordinal comparison.
+ *
+ * Case-sensitive comparisons compare both strings one code-point at a time using the integer
+ * value of each code-point after applying `toUpperCase` to each string. We always map both
+ * strings to their upper-case form as some unicode characters do not properly round-trip to
+ * lowercase (such as `ẞ` (German sharp capital s)).
+ */
function equateStringsCaseInsensitive(a, b) {
return a === b
|| a !== undefined
@@ -1317,37 +1460,69 @@ var ts;
&& a.toUpperCase() === b.toUpperCase();
}
ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
+ /**
+ * Compare the equality of two strings using a case-sensitive ordinal comparison.
+ *
+ * Case-sensitive comparisons compare both strings one code-point at a time using the
+ * integer value of each code-point.
+ */
function equateStringsCaseSensitive(a, b) {
return equateValues(a, b);
}
ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
function compareComparableValues(a, b) {
- return a === b ? 0 :
- a === undefined ? -1 :
- b === undefined ? 1 :
- a < b ? -1 :
- 1;
+ return a === b ? 0 /* EqualTo */ :
+ a === undefined ? -1 /* LessThan */ :
+ b === undefined ? 1 /* GreaterThan */ :
+ a < b ? -1 /* LessThan */ :
+ 1 /* GreaterThan */;
}
+ /**
+ * Compare two numeric values for their order relative to each other.
+ * To compare strings, use any of the `compareStrings` functions.
+ */
function compareValues(a, b) {
return compareComparableValues(a, b);
}
ts.compareValues = compareValues;
function min(a, b, compare) {
- return compare(a, b) === -1 ? a : b;
+ return compare(a, b) === -1 /* LessThan */ ? a : b;
}
ts.min = min;
+ /**
+ * Compare two strings using a case-insensitive ordinal comparison.
+ *
+ * Ordinal comparisons are based on the difference between the unicode code points of both
+ * strings. Characters with multiple unicode representations are considered unequal. Ordinal
+ * comparisons provide predictable ordering, but place "a" after "B".
+ *
+ * Case-insensitive comparisons compare both strings one code-point at a time using the integer
+ * value of each code-point after applying `toUpperCase` to each string. We always map both
+ * strings to their upper-case form as some unicode characters do not properly round-trip to
+ * lowercase (such as `ẞ` (German sharp capital s)).
+ */
function compareStringsCaseInsensitive(a, b) {
if (a === b)
- return 0;
+ return 0 /* EqualTo */;
if (a === undefined)
- return -1;
+ return -1 /* LessThan */;
if (b === undefined)
- return 1;
+ return 1 /* GreaterThan */;
a = a.toUpperCase();
b = b.toUpperCase();
- return a < b ? -1 : a > b ? 1 : 0;
+ return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
}
ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
+ /**
+ * Compare two strings using a case-sensitive ordinal comparison.
+ *
+ * Ordinal comparisons are based on the difference between the unicode code points of both
+ * strings. Characters with multiple unicode representations are considered unequal. Ordinal
+ * comparisons provide predictable ordering, but place "a" after "B".
+ *
+ * Case-sensitive comparisons compare both strings one code-point at a time using the integer
+ * value of each code-point.
+ */
function compareStringsCaseSensitive(a, b) {
return compareComparableValues(a, b);
}
@@ -1356,6 +1531,9 @@ var ts;
return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
}
ts.getStringComparer = getStringComparer;
+ /**
+ * Creates a string comparer for use with string collation in the UI.
+ */
var createUIStringComparer = (function () {
var defaultComparer;
var enUSComparer;
@@ -1363,19 +1541,22 @@ var ts;
return createStringComparer;
function compareWithCallback(a, b, comparer) {
if (a === b)
- return 0;
+ return 0 /* EqualTo */;
if (a === undefined)
- return -1;
+ return -1 /* LessThan */;
if (b === undefined)
- return 1;
+ return 1 /* GreaterThan */;
var value = comparer(a, b);
- return value < 0 ? -1 : value > 0 ? 1 : 0;
+ return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
}
function createIntlCollatorStringComparer(locale) {
+ // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
+ // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
return function (a, b) { return compareWithCallback(a, b, comparer); };
}
function createLocaleCompareStringComparer(locale) {
+ // if the locale is not the default locale (`undefined`), use the fallback comparer.
if (locale !== undefined)
return createFallbackStringComparer();
return function (a, b) { return compareWithCallback(a, b, compareStrings); };
@@ -1384,26 +1565,39 @@ var ts;
}
}
function createFallbackStringComparer() {
+ // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
+ // We first sort case insensitively. So "Aaa" will come before "baa".
+ // Then we sort case sensitively, so "aaa" will come before "Aaa".
+ //
+ // For case insensitive comparisons we always map both strings to their
+ // upper-case form as some unicode characters do not properly round-trip to
+ // lowercase (such as `ẞ` (German sharp capital s)).
return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
function compareDictionaryOrder(a, b) {
return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
}
function compareStrings(a, b) {
- return a < b ? -1 : a > b ? 1 : 0;
+ return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
}
}
function getStringComparerFactory() {
+ // If the host supports Intl, we use it for comparisons using the default locale.
if (typeof Intl === "object" && typeof Intl.Collator === "function") {
return createIntlCollatorStringComparer;
}
+ // If the host does not support Intl, we fall back to localeCompare.
+ // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
if (typeof String.prototype.localeCompare === "function" &&
typeof String.prototype.toLocaleUpperCase === "function" &&
"a".localeCompare("B") < 0) {
return createLocaleCompareStringComparer;
}
+ // Otherwise, fall back to ordinal comparison:
return createFallbackStringComparer;
}
function createStringComparer(locale) {
+ // Hold onto common string comparers. This avoids constantly reallocating comparers during
+ // tests.
if (locale === undefined) {
return defaultComparer || (defaultComparer = stringComparerFactory(locale));
}
@@ -1428,25 +1622,50 @@ var ts;
}
}
ts.setUILocale = setUILocale;
+ /**
+ * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
+ *
+ * Ordering is not predictable between different host locales, but is best for displaying
+ * ordered data for UI presentation. Characters with multiple unicode representations may
+ * be considered equal.
+ *
+ * Case-sensitive comparisons compare strings that differ in base characters, or
+ * accents/diacritic marks, or case as unequal.
+ */
function compareStringsCaseSensitiveUI(a, b) {
var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
return comparer(a, b);
}
ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
function compareProperties(a, b, key, comparer) {
- return a === b ? 0 :
- a === undefined ? -1 :
- b === undefined ? 1 :
+ return a === b ? 0 /* EqualTo */ :
+ a === undefined ? -1 /* LessThan */ :
+ b === undefined ? 1 /* GreaterThan */ :
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
+ /** True is greater than false. */
function compareBooleans(a, b) {
return compareValues(a ? 1 : 0, b ? 1 : 0);
}
ts.compareBooleans = compareBooleans;
+ /**
+ * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
+ * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
+ *
+ * If there is a candidate that's the same except for case, return that.
+ * If there is a candidate that's within one edit of the name, return that.
+ * Otherwise, return the candidate with the smallest Levenshtein distance,
+ * except for candidates:
+ * * With no name
+ * * Whose length differs from the target name by more than 0.34 of the length of the name.
+ * * Whose levenshtein distance is more than 0.4 of the length of the name
+ * (0.4 allows 1 substitution/transposition for every 5 characters,
+ * and 1 insertion/deletion at 3 characters)
+ */
function getSpellingSuggestion(name, candidates, getName) {
var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
- var bestDistance = Math.floor(name.length * 0.4) + 1;
+ var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
var bestCandidate;
var justCheckExactMatches = false;
var nameLowerCase = name.toLowerCase();
@@ -1462,8 +1681,10 @@ var ts;
continue;
}
if (candidateName.length < 3) {
+ // Don't bother, user would have noticed a 2-character name having an extra character
continue;
}
+ // Only care about a result better than the best so far.
var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
if (distance === undefined) {
continue;
@@ -1473,7 +1694,7 @@ var ts;
bestCandidate = candidate;
}
else {
- Debug.assert(distance < bestDistance);
+ Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
bestDistance = distance;
bestCandidate = candidate;
}
@@ -1485,6 +1706,7 @@ var ts;
function levenshteinWithMax(s1, s2, max) {
var previous = new Array(s2.length + 1);
var current = new Array(s2.length + 1);
+ /** Represents any value > max. We don't care about the particular value. */
var big = max + 1;
for (var i = 0; i <= s2.length; i++) {
previous[i] = i;
@@ -1494,6 +1716,7 @@ var ts;
var minJ = i > max ? i - max : 1;
var maxJ = s2.length > max + i ? max + i : s2.length;
current[0] = i;
+ /** Smallest value of the matrix in the ith column. */
var colMin = i;
for (var j = 1; j < minJ; j++) {
current[j] = big;
@@ -1501,7 +1724,7 @@ var ts;
for (var j = minJ; j <= maxJ; j++) {
var dist = c1 === s2.charCodeAt(j - 1)
? previous[j - 1]
- : Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + 2);
+ : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
current[j] = dist;
colMin = Math.min(colMin, dist);
}
@@ -1509,6 +1732,7 @@ var ts;
current[j] = big;
}
if (colMin > max) {
+ // Give up -- everything in this column is > max and it can't get better in future columns.
return undefined;
}
var temp = previous;
@@ -1549,11 +1773,17 @@ var ts;
return false;
}
ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
+ /**
+ * Takes a string like "jquery-min.4.2.3" and returns "jquery"
+ */
function removeMinAndVersionNumbers(fileName) {
+ // Match a "." or "-" followed by a version number or 'min' at the end of the name
var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
+ // The "min" or version may both be present, in either order, so try applying the above twice.
return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
}
ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
+ /** Remove an item from an array, moving everything to its right one space left. */
function orderedRemoveItem(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
@@ -1564,7 +1794,9 @@ var ts;
return false;
}
ts.orderedRemoveItem = orderedRemoveItem;
+ /** Remove an item by index from an array, moving everything to its right one space left. */
function orderedRemoveItemAt(array, index) {
+ // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
for (var i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
@@ -1572,14 +1804,17 @@ var ts;
}
ts.orderedRemoveItemAt = orderedRemoveItemAt;
function unorderedRemoveItemAt(array, index) {
+ // Fill in the "hole" left at `index`.
array[index] = array[array.length - 1];
array.pop();
}
ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
+ /** Remove the *first* occurrence of `item` from the array. */
function unorderedRemoveItem(array, item) {
return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
}
ts.unorderedRemoveItem = unorderedRemoveItem;
+ /** Remove the *first* element satisfying `predicate`. */
function unorderedRemoveFirstItemWhere(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
@@ -1598,13 +1833,19 @@ var ts;
return prefix + "*" + suffix;
}
ts.patternText = patternText;
+ /**
+ * Given that candidate matches pattern, returns the text matching the '*'.
+ * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
+ */
function matchedText(pattern, candidate) {
Debug.assert(isPatternMatch(pattern, candidate));
return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
ts.matchedText = matchedText;
+ /** Return the object corresponding to the best pattern to match `candidate`. */
function findBestPatternMatch(values, getPattern, candidate) {
var matchedValue;
+ // use length of prefix as betterness criteria
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var v = values_2[_i];
@@ -1643,7 +1884,7 @@ var ts;
return function (arg) { return f(arg) || g(arg); };
}
ts.or = or;
- function assertTypeIsNever(_) { }
+ function assertTypeIsNever(_) { } // tslint:disable-line no-empty
ts.assertTypeIsNever = assertTypeIsNever;
function singleElementArray(t) {
return t === undefined ? undefined : [t];
@@ -1659,11 +1900,11 @@ var ts;
var newItem = newItems[newIndex];
var oldItem = oldItems[oldIndex];
var compareResult = comparer(newItem, oldItem);
- if (compareResult === -1) {
+ if (compareResult === -1 /* LessThan */) {
inserted(newItem);
newIndex++;
}
- else if (compareResult === 1) {
+ else if (compareResult === 1 /* GreaterThan */) {
deleted(oldItem);
oldIndex++;
}
@@ -1682,19 +1923,29 @@ var ts;
}
ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
})(ts || (ts = {}));
+/*@internal*/
var ts;
(function (ts) {
+ /** Gets a timestamp with (at least) ms resolution */
ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
})(ts || (ts = {}));
+/*@internal*/
+/** Performance measurements for the compiler. */
(function (ts) {
var performance;
(function (performance) {
+ // NOTE: cannot use ts.noop as core.ts loads after this
var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
var enabled = false;
var profilerStart = 0;
var counts;
var marks;
var measures;
+ /**
+ * Marks a performance event.
+ *
+ * @param markName The name of the mark.
+ */
function mark(markName) {
if (enabled) {
marks.set(markName, ts.timestamp());
@@ -1703,6 +1954,15 @@ var ts;
}
}
performance.mark = mark;
+ /**
+ * Adds a performance measurement with the specified name.
+ *
+ * @param measureName The name of the performance measurement.
+ * @param startMarkName The name of the starting mark. If not supplied, the point at which the
+ * profiler was enabled is used.
+ * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
+ * used.
+ */
function measure(measureName, startMarkName, endMarkName) {
if (enabled) {
var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
@@ -1711,20 +1971,36 @@ var ts;
}
}
performance.measure = measure;
+ /**
+ * Gets the number of times a marker was encountered.
+ *
+ * @param markName The name of the mark.
+ */
function getCount(markName) {
return counts && counts.get(markName) || 0;
}
performance.getCount = getCount;
+ /**
+ * Gets the total duration of all measurements with the supplied name.
+ *
+ * @param measureName The name of the measure whose durations should be accumulated.
+ */
function getDuration(measureName) {
return measures && measures.get(measureName) || 0;
}
performance.getDuration = getDuration;
+ /**
+ * Iterate over each measure, performing some action
+ *
+ * @param cb The action to perform for each measure
+ */
function forEachMeasure(cb) {
measures.forEach(function (measure, key) {
cb(key, measure);
});
}
performance.forEachMeasure = forEachMeasure;
+ /** Enables (and resets) performance measurements for the compiler. */
function enable() {
counts = ts.createMap();
marks = ts.createMap();
@@ -1733,6 +2009,7 @@ var ts;
profilerStart = ts.timestamp();
}
performance.enable = enable;
+ /** Disables performance measurements for the compiler. */
function disable() {
enabled = false;
}
@@ -1741,6 +2018,8 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ // token > SyntaxKind.Identifier => token is a keyword
+ // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
var SyntaxKind;
(function (SyntaxKind) {
SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
@@ -1749,17 +2028,23 @@ var ts;
SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
+ // We detect and preserve #! on the first line
SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
+ // We detect and provide better error recovery when we encounter a git merge marker. This
+ // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
+ // Literals
SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral";
SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText";
SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces";
SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral";
SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral";
+ // Pseudo-literals
SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead";
SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle";
SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail";
+ // Punctuation
SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken";
SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken";
SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken";
@@ -1801,6 +2086,7 @@ var ts;
SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken";
SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken";
SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken";
+ // Assignments
SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken";
SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken";
SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken";
@@ -1814,7 +2100,9 @@ var ts;
SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken";
SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken";
SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken";
+ // Identifiers
SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier";
+ // Reserved words
SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword";
SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword";
SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword";
@@ -1851,6 +2139,7 @@ var ts;
SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword";
SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword";
SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword";
+ // Strict mode reserved words
SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword";
SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword";
SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword";
@@ -1860,6 +2149,7 @@ var ts;
SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword";
SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword";
SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword";
+ // Contextual keywords
SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword";
SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword";
SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword";
@@ -1889,11 +2179,15 @@ var ts;
SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword";
SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword";
SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword";
+ // Parse tree nodes
+ // Names
SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName";
SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName";
+ // Signature elements
SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter";
SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter";
SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator";
+ // TypeMember
SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature";
SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration";
SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature";
@@ -1904,6 +2198,7 @@ var ts;
SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature";
SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature";
SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature";
+ // Type
SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate";
SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference";
SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType";
@@ -1923,9 +2218,11 @@ var ts;
SyntaxKind[SyntaxKind["MappedType"] = 177] = "MappedType";
SyntaxKind[SyntaxKind["LiteralType"] = 178] = "LiteralType";
SyntaxKind[SyntaxKind["ImportType"] = 179] = "ImportType";
+ // Binding patterns
SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 180] = "ObjectBindingPattern";
SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 181] = "ArrayBindingPattern";
SyntaxKind[SyntaxKind["BindingElement"] = 182] = "BindingElement";
+ // Expression
SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 183] = "ArrayLiteralExpression";
SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 184] = "ObjectLiteralExpression";
SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 185] = "PropertyAccessExpression";
@@ -1954,8 +2251,10 @@ var ts;
SyntaxKind[SyntaxKind["AsExpression"] = 208] = "AsExpression";
SyntaxKind[SyntaxKind["NonNullExpression"] = 209] = "NonNullExpression";
SyntaxKind[SyntaxKind["MetaProperty"] = 210] = "MetaProperty";
+ // Misc
SyntaxKind[SyntaxKind["TemplateSpan"] = 211] = "TemplateSpan";
SyntaxKind[SyntaxKind["SemicolonClassElement"] = 212] = "SemicolonClassElement";
+ // Element
SyntaxKind[SyntaxKind["Block"] = 213] = "Block";
SyntaxKind[SyntaxKind["VariableStatement"] = 214] = "VariableStatement";
SyntaxKind[SyntaxKind["EmptyStatement"] = 215] = "EmptyStatement";
@@ -1997,7 +2296,9 @@ var ts;
SyntaxKind[SyntaxKind["NamedExports"] = 251] = "NamedExports";
SyntaxKind[SyntaxKind["ExportSpecifier"] = 252] = "ExportSpecifier";
SyntaxKind[SyntaxKind["MissingDeclaration"] = 253] = "MissingDeclaration";
+ // Module references
SyntaxKind[SyntaxKind["ExternalModuleReference"] = 254] = "ExternalModuleReference";
+ // JSX
SyntaxKind[SyntaxKind["JsxElement"] = 255] = "JsxElement";
SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 256] = "JsxSelfClosingElement";
SyntaxKind[SyntaxKind["JsxOpeningElement"] = 257] = "JsxOpeningElement";
@@ -2009,20 +2310,27 @@ var ts;
SyntaxKind[SyntaxKind["JsxAttributes"] = 263] = "JsxAttributes";
SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 264] = "JsxSpreadAttribute";
SyntaxKind[SyntaxKind["JsxExpression"] = 265] = "JsxExpression";
+ // Clauses
SyntaxKind[SyntaxKind["CaseClause"] = 266] = "CaseClause";
SyntaxKind[SyntaxKind["DefaultClause"] = 267] = "DefaultClause";
SyntaxKind[SyntaxKind["HeritageClause"] = 268] = "HeritageClause";
SyntaxKind[SyntaxKind["CatchClause"] = 269] = "CatchClause";
+ // Property assignments
SyntaxKind[SyntaxKind["PropertyAssignment"] = 270] = "PropertyAssignment";
SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 271] = "ShorthandPropertyAssignment";
SyntaxKind[SyntaxKind["SpreadAssignment"] = 272] = "SpreadAssignment";
+ // Enum
SyntaxKind[SyntaxKind["EnumMember"] = 273] = "EnumMember";
+ // Top-level nodes
SyntaxKind[SyntaxKind["SourceFile"] = 274] = "SourceFile";
SyntaxKind[SyntaxKind["Bundle"] = 275] = "Bundle";
SyntaxKind[SyntaxKind["UnparsedSource"] = 276] = "UnparsedSource";
SyntaxKind[SyntaxKind["InputFiles"] = 277] = "InputFiles";
+ // JSDoc nodes
SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 278] = "JSDocTypeExpression";
+ // The * type
SyntaxKind[SyntaxKind["JSDocAllType"] = 279] = "JSDocAllType";
+ // The ? type
SyntaxKind[SyntaxKind["JSDocUnknownType"] = 280] = "JSDocUnknownType";
SyntaxKind[SyntaxKind["JSDocNullableType"] = 281] = "JSDocNullableType";
SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 282] = "JSDocNonNullableType";
@@ -2043,13 +2351,17 @@ var ts;
SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 297] = "JSDocTemplateTag";
SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 298] = "JSDocTypedefTag";
SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 299] = "JSDocPropertyTag";
+ // Synthesized list
SyntaxKind[SyntaxKind["SyntaxList"] = 300] = "SyntaxList";
+ // Transformation nodes
SyntaxKind[SyntaxKind["NotEmittedStatement"] = 301] = "NotEmittedStatement";
SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 302] = "PartiallyEmittedExpression";
SyntaxKind[SyntaxKind["CommaListExpression"] = 303] = "CommaListExpression";
SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 304] = "MergeDeclarationMarker";
SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 305] = "EndOfDeclarationMarker";
+ // Enum value count
SyntaxKind[SyntaxKind["Count"] = 306] = "Count";
+ // Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment";
@@ -2079,8 +2391,8 @@ var ts;
SyntaxKind[SyntaxKind["LastJSDocNode"] = 299] = "LastJSDocNode";
SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 289] = "FirstJSDocTagNode";
SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 299] = "LastJSDocTagNode";
- SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
- SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword";
+ /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
+ /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
var NodeFlags;
(function (NodeFlags) {
@@ -2104,18 +2416,32 @@ var ts;
NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile";
NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError";
NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData";
- NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport";
- NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta";
+ // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
+ // walking the tree if the flags are not set. However, these flags are just a approximation
+ // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
+ // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
+ // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
+ // However, the removal operation should not occur often and in the case of the
+ // removal, it is likely that users will add the import anyway.
+ // The advantage of this approach is its simplicity. For the case of batch compilation,
+ // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
+ /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport";
+ /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta";
NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
- NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
- NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
+ /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
+ /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
+ // Parsing context flags
NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags";
+ // Exclude these flags when parsing a Type
NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags";
- NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags";
+ // Represents all flags that are potentially set once and
+ // never cleared on SourceFiles which get re-used in between incremental parses.
+ // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
+ /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags";
})(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
var ModifierFlags;
(function (ModifierFlags) {
@@ -2133,6 +2459,7 @@ var ts;
ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
+ // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
@@ -2142,28 +2469,35 @@ var ts;
var JsxFlags;
(function (JsxFlags) {
JsxFlags[JsxFlags["None"] = 0] = "None";
+ /** An element from a named property of the JSX.IntrinsicElements interface */
JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
+ /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
})(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
+ /* @internal */
var RelationComparisonResult;
(function (RelationComparisonResult) {
RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported";
})(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
+ /*@internal*/
var GeneratedIdentifierFlags;
(function (GeneratedIdentifierFlags) {
+ // Kinds
GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
+ // Flags
GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
+ /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
@@ -2198,24 +2532,32 @@ var ts;
FlowFlags[FlowFlags["Label"] = 12] = "Label";
FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
})(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
- var OperationCanceledException = (function () {
+ var OperationCanceledException = /** @class */ (function () {
function OperationCanceledException() {
}
return OperationCanceledException;
}());
ts.OperationCanceledException = OperationCanceledException;
+ /* @internal */
var StructureIsReused;
(function (StructureIsReused) {
StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
})(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
+ /** Return code used by getEmitOutput function to indicate status of the function */
var ExitStatus;
(function (ExitStatus) {
+ // Compiler ran successfully. Either this was a simple do-nothing compilation (for example,
+ // when -version or -help was provided, or this was a normal compilation, no diagnostics
+ // were produced, and all outputs were generated successfully.
ExitStatus[ExitStatus["Success"] = 0] = "Success";
+ // Diagnostics were produced and because of them no code was generated.
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
+ // Diagnostics were produced and outputs were generated in spite of them.
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
})(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
+ /* @internal */
var UnionReduction;
(function (UnionReduction) {
UnionReduction[UnionReduction["None"] = 0] = "None";
@@ -2225,6 +2567,7 @@ var ts;
var NodeBuilderFlags;
(function (NodeBuilderFlags) {
NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
+ // Options
NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
@@ -2240,6 +2583,7 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
+ // Error handling
NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
@@ -2248,49 +2592,70 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
+ // State
NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
})(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
+ // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
var TypeFormatFlags;
(function (TypeFormatFlags) {
TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
+ // hole because there's a hole in node builder flags
TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
+ // hole because there's a hole in node builder flags
TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
+ // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
+ // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
+ // even though `T` can't be accessed in the current scope.
+ // Error Handling
TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
+ // TypeFormatFlags exclusive
TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
+ // State
TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
- TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
+ /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask";
})(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
var SymbolFormatFlags;
(function (SymbolFormatFlags) {
SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
+ // Write symbols's type argument if it is instantiated symbol
+ // eg. class C { p: T } <-- Show p as C.p here
+ // var a: C;
+ // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p
SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
+ // Use only external alias information to get the symbol name in the given context
+ // eg. module m { export class c { } } import x = m.c;
+ // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
+ // Build symbol name using any nodes needed, instead of just components of an entity name
SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
+ // Prefer aliases which are not directly visible
SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
})(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
+ /* @internal */
var SymbolAccessibility;
(function (SymbolAccessibility) {
SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
})(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
+ /* @internal */
var SyntheticSymbolKind;
(function (SyntheticSymbolKind) {
SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
@@ -2301,10 +2666,16 @@ var ts;
TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
})(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
+ /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
+ /* @internal */
var TypeReferenceSerializationKind;
(function (TypeReferenceSerializationKind) {
TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
+ // should be emitted using a safe fallback.
TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
+ // function that can be reached at runtime (e.g. a `class`
+ // declaration or a `var` declaration for the static side
+ // of a type, such as the global `Promise` type in lib.d.ts).
TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType";
@@ -2313,6 +2684,7 @@ var ts;
TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType";
TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise";
TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature";
+ // with call signatures.
TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType";
})(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
var SymbolFlags;
@@ -2345,6 +2717,7 @@ var ts;
SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer";
+ /* @internal */
SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
@@ -2353,7 +2726,11 @@ var ts;
SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
+ // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
+ // same name, or any other value that is not a variable, e.g. ValueModule or Class
SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes";
+ // Block-scoped declarations are not allowed to be re-declared
+ // they can not merge with anything in the value space
SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes";
SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes";
SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
@@ -2378,14 +2755,20 @@ var ts;
SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
+ /* @internal */
+ // The set of things we consider semantically classifiable. Used to speed up the LS during
+ // classification.
SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
+ /* @internal */
SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer";
})(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
+ /* @internal */
var EnumKind;
(function (EnumKind) {
EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
- EnumKind[EnumKind["Literal"] = 1] = "Literal";
+ EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
})(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
+ /* @internal */
var CheckFlags;
(function (CheckFlags) {
CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
@@ -2421,6 +2804,7 @@ var ts;
InternalSymbolName["ExportEquals"] = "export=";
InternalSymbolName["Default"] = "default";
})(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
+ /* @internal */
var NodeCheckFlags;
(function (NodeCheckFlags) {
NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
@@ -2472,20 +2856,31 @@ var ts;
TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional";
TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive";
+ /* @internal */
TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral";
+ /* @internal */
TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes";
+ /* @internal */
TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
+ /* @internal */
TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
+ /* @internal */
TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
+ /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
+ /* @internal */
TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable";
TypeFlags[TypeFlags["Literal"] = 448] = "Literal";
TypeFlags[TypeFlags["Unit"] = 27072] = "Unit";
TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral";
+ /* @internal */
TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique";
+ /* @internal */
TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy";
TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy";
+ /* @internal */
TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic";
+ /* @internal */
TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive";
TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike";
TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike";
@@ -2493,6 +2888,7 @@ var ts;
TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike";
TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike";
TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike";
+ /* @internal */
TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains";
TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection";
TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType";
@@ -2501,15 +2897,27 @@ var ts;
TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable";
+ // 'Narrowable' types are types where narrowing actually narrows.
+ // This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit";
+ /* @internal */
TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit";
+ /* @internal */
TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
+ /* @internal */
TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ // The following flags are used for different purposes during union and intersection type construction
+ /* @internal */
TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ /* @internal */
TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ /* @internal */
TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ /* @internal */
TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ // The following flag is used for different purposes by maybeTypeOfKind
+ /* @internal */
TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
@@ -2530,6 +2938,7 @@ var ts;
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
+ /* @internal */
var Variance;
(function (Variance) {
Variance[Variance["Invariant"] = 0] = "Invariant";
@@ -2559,6 +2968,7 @@ var ts;
InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict";
InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination";
})(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
+ /* @internal */
var InferenceFlags;
(function (InferenceFlags) {
InferenceFlags[InferenceFlags["None"] = 0] = "None";
@@ -2566,20 +2976,37 @@ var ts;
InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
+ /**
+ * Ternary values are defined such that
+ * x & y is False if either x or y is False.
+ * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
+ * x & y is True if both x and y are True.
+ * x | y is False if both x and y are False.
+ * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
+ * x | y is True if either x or y is True.
+ */
+ /* @internal */
var Ternary;
(function (Ternary) {
Ternary[Ternary["False"] = 0] = "False";
Ternary[Ternary["Maybe"] = 1] = "Maybe";
Ternary[Ternary["True"] = -1] = "True";
})(Ternary = ts.Ternary || (ts.Ternary = {}));
+ /* @internal */
var SpecialPropertyAssignmentKind;
(function (SpecialPropertyAssignmentKind) {
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None";
+ /// exports.name = expr
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty";
+ /// module.exports = expr
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports";
+ /// className.prototype.name = expr
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty";
+ /// this.name = expr
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty";
+ // F.name = expr
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property";
+ // F.prototype = { ... }
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype";
})(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {}));
var DiagnosticCategory;
@@ -2589,6 +3016,7 @@ var ts;
DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ /* @internal */
function diagnosticCategoryName(d, lowerCase) {
if (lowerCase === void 0) { lowerCase = true; }
var name = DiagnosticCategory[d.category];
@@ -2631,6 +3059,10 @@ var ts;
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
ScriptKind[ScriptKind["External"] = 5] = "External";
ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
})(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
var ScriptTarget;
@@ -2655,6 +3087,7 @@ var ts;
WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
})(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
+ /* @internal */
var CharacterCodes;
(function (CharacterCodes) {
CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
@@ -2664,6 +3097,7 @@ var ts;
CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
+ // Unicode 3.0 space characters
CharacterCodes[CharacterCodes["space"] = 32] = "space";
CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
@@ -2791,9 +3225,12 @@ var ts;
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
})(Extension = ts.Extension || (ts.Extension = {}));
+ /* @internal */
var TransformFlags;
(function (TransformFlags) {
TransformFlags[TransformFlags["None"] = 0] = "None";
+ // Facts
+ // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
@@ -2806,6 +3243,8 @@ var ts;
TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ // Markers
+ // - Flags used to indicate that a subtree contains a specific transformation.
TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators";
TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer";
TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis";
@@ -2825,7 +3264,12 @@ var ts;
TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport";
TransformFlags[TransformFlags["Super"] = 134217728] = "Super";
TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper";
+ // Please leave this as 1 << 29.
+ // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
+ // It is a good reminder of how much room we have left
TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
+ // Assertions
+ // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
@@ -2834,6 +3278,9 @@ var ts;
TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ // Scope Exclusions
+ // - Bitmasks that exclude flags from propagating out of a specific context
+ // into the subtree flags of their container.
TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes";
TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes";
@@ -2850,6 +3297,8 @@ var ts;
TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes";
TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes";
TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes";
+ // Masks
+ // - Additional bitmasks
TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask";
TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
@@ -2884,9 +3333,14 @@ var ts;
EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
- EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
- EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
+ /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
+ /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
})(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
+ /**
+ * Used by the checker, this enum keeps track of external emit helpers that should be type
+ * checked.
+ */
+ /* @internal */
var ExternalEmitHelpers;
(function (ExternalEmitHelpers) {
ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
@@ -2908,10 +3362,15 @@ var ts;
ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject";
ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper";
+ // Helpers included by ES2015 for..of
ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
+ // Helpers included by ES2017 for..await..of
ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
+ // Helpers included by ES2017 async generators
ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
+ // Helpers included by yield* in ES2017 async generators
ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
+ // Helpers included by ES2015 spread
ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
})(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
var EmitHint;
@@ -2925,19 +3384,23 @@ var ts;
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
+ // Line separators
ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
+ // Delimiters
ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask";
ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma";
+ // Whitespace
ListFormat[ListFormat["Indented"] = 64] = "Indented";
ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces";
ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings";
+ // Brackets/Braces
ListFormat[ListFormat["Braces"] = 512] = "Braces";
ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis";
ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets";
@@ -2946,11 +3409,13 @@ var ts;
ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined";
ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty";
ListFormat[ListFormat["Optional"] = 24576] = "Optional";
+ // Other
ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine";
ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine";
ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments";
ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty";
ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement";
+ // Precomputed Formats
ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers";
ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses";
ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers";
@@ -2988,18 +3453,40 @@ var ts;
ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
})(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
+ /* @internal */
var PragmaKindFlags;
(function (PragmaKindFlags) {
PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
+ /**
+ * Triple slash comment of the form
+ * ///
+ */
PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
+ /**
+ * Single line comment of the form
+ * // @pragma-name argval1 argval2
+ * or
+ * /// @pragma-name argval1 argval2
+ */
PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
+ /**
+ * Multiline non-jsdoc pragma of the form
+ * /* @pragma-name argval1 argval2 * /
+ */
PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
})(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
+ /**
+ * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas`
+ */
+ /* @internal */
function _contextuallyTypePragmas(args) {
return args;
}
+ // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
+ // fancy effectively defining it twice, once in value-space and once in type-space
+ /* @internal */
ts.commentPragmas = _contextuallyTypePragmas({
"reference": {
args: [
@@ -3008,32 +3495,38 @@ var ts;
{ name: "path", optional: true, captureSpan: true },
{ name: "no-default-lib", optional: true }
],
- kind: 1
+ kind: 1 /* TripleSlashXML */
},
"amd-dependency": {
args: [{ name: "path" }, { name: "name", optional: true }],
- kind: 1
+ kind: 1 /* TripleSlashXML */
},
"amd-module": {
args: [{ name: "name" }],
- kind: 1
+ kind: 1 /* TripleSlashXML */
},
"ts-check": {
- kind: 2
+ kind: 2 /* SingleLine */
},
"ts-nocheck": {
- kind: 2
+ kind: 2 /* SingleLine */
},
"jsx": {
args: [{ name: "factory" }],
- kind: 4
+ kind: 4 /* MultiLine */
},
});
})(ts || (ts = {}));
var ts;
(function (ts) {
+ /**
+ * Set a high stack trace limit to provide more information in case of an error.
+ * Called for command-line and server use cases.
+ * Not called if TypeScript is used as a library.
+ */
+ /* @internal */
function setStackTraceLimit() {
- if (Error.stackTraceLimit < 100) {
+ if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
Error.stackTraceLimit = 100;
}
}
@@ -3044,6 +3537,7 @@ var ts;
FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
})(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
+ /* @internal */
var PollingInterval;
(function (PollingInterval) {
PollingInterval[PollingInterval["High"] = 2000] = "High";
@@ -3059,11 +3553,13 @@ var ts;
return pollingIntervalsForPriority[watchPriority];
}
var pollingIntervalsForPriority = getPriorityValues(250);
+ /* @internal */
function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) {
return host.watchFile(fileName, callback, pollingInterval(watchPriority));
}
ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval;
- ts.missingFileModifiedTime = new Date(0);
+ /* @internal */
+ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
function createPollingIntervalBasedLevels(levels) {
var _a;
return _a = {},
@@ -3074,7 +3570,9 @@ var ts;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
+ /* @internal */
ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
+ /* @internal */
function setCustomPollingValues(system) {
if (!system.getEnvironmentVariable) {
return;
@@ -3118,6 +3616,7 @@ var ts;
}
}
ts.setCustomPollingValues = setCustomPollingValues;
+ /* @internal */
function createDynamicPriorityPollingWatchFile(host) {
var watchedFiles = [];
var changedFilesInLastPoll = [];
@@ -3137,7 +3636,9 @@ var ts;
return {
close: function () {
file.isClosed = true;
+ // Remove from watchedFiles
ts.unorderedRemoveItem(watchedFiles, file);
+ // Do not update polling interval queue since that will happen as part of polling
}
};
}
@@ -3150,6 +3651,7 @@ var ts;
}
function pollPollingIntervalQueue(queue) {
queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
+ // Set the next polling index and timeout
if (queue.length) {
scheduleNextPoll(queue.pollingInterval);
}
@@ -3159,13 +3661,18 @@ var ts;
}
}
function pollLowPollingIntervalQueue(queue) {
- pollQueue(changedFilesInLastPoll, PollingInterval.Low, 0, changedFilesInLastPoll.length);
+ // Always poll complete list of changedFilesInLastPoll
+ pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
+ // Finally do the actual polling of the queue
pollPollingIntervalQueue(queue);
+ // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
+ // as pollPollingIntervalQueue wont schedule for next poll
if (!queue.pollScheduled && changedFilesInLastPoll.length) {
scheduleNextPoll(PollingInterval.Low);
}
}
function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
+ // Max visit would be all elements of the queue
var needsVisit = queue.length;
var definedValueCopyToIndex = pollIndex;
for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
@@ -3180,10 +3687,12 @@ var ts;
polled++;
var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
if (watchedFile.isClosed) {
+ // Closed watcher as part of callback
queue[pollIndex] = undefined;
}
else if (fileChanged) {
watchedFile.unchangedPolls = 0;
+ // Changed files go to changedFilesInLastPoll queue
if (queue !== changedFilesInLastPoll) {
queue[pollIndex] = undefined;
addChangedFileToLowPollingIntervalQueue(watchedFile);
@@ -3193,6 +3702,7 @@ var ts;
watchedFile.unchangedPolls++;
}
else if (queue === changedFilesInLastPoll) {
+ // Restart unchangedPollCount for unchanged file and move to low polling interval queue
watchedFile.unchangedPolls = 1;
queue[pollIndex] = undefined;
addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
@@ -3203,6 +3713,7 @@ var ts;
addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
}
if (queue[pollIndex]) {
+ // Copy this file to the non hole location
if (definedValueCopyToIndex < pollIndex) {
queue[definedValueCopyToIndex] = watchedFile;
queue[pollIndex] = undefined;
@@ -3210,11 +3721,13 @@ var ts;
definedValueCopyToIndex++;
}
}
+ // Return next poll index
return pollIndex;
function nextPollIndex() {
pollIndex++;
if (pollIndex === queue.length) {
if (definedValueCopyToIndex < pollIndex) {
+ // There are holes from nextDefinedValueIndex to end of queue, change queue size
queue.length = definedValueCopyToIndex;
}
pollIndex = 0;
@@ -3253,6 +3766,10 @@ var ts;
}
}
ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
+ /**
+ * Returns true if file status changed
+ */
+ /*@internal*/
function onWatchedFileStat(watchedFile, modifiedTime) {
var oldTime = watchedFile.mtime.getTime();
var newTime = modifiedTime.getTime();
@@ -3269,11 +3786,22 @@ var ts;
return false;
}
ts.onWatchedFileStat = onWatchedFileStat;
+ /**
+ * Watch the directory recursively using host provided method to watch child directories
+ * that means if this is recursive watcher, watch the children directories as well
+ * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
+ */
+ /*@internal*/
function createRecursiveDirectoryWatcher(host) {
return createDirectoryWatcher;
+ /**
+ * Create the directory watcher for the dirPath.
+ */
function createDirectoryWatcher(dirName, callback) {
var watcher = host.watchDirectory(dirName, function (fileName) {
+ // Call the actual callback
callback(fileName);
+ // Iterate through existing children and update the watches if needed
updateChildWatches(result, callback);
});
var result = {
@@ -3289,21 +3817,33 @@ var ts;
return result;
}
function updateChildWatches(watcher, callback) {
+ // Iterate through existing children and update the watches if needed
if (watcher) {
watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback);
}
}
+ /**
+ * Watch the directories in the parentDir
+ */
function watchChildDirectories(parentDir, existingChildWatches, callback) {
var newChildWatches;
ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
- return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 ? childFullName : undefined;
+ // Filter our the symbolic link directories since those arent included in recursive watch
+ // which is same behaviour when recursive: true is passed to fs.watch
+ return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
+ /**
+ * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
+ */
function createAndAddChildDirectoryWatcher(childName) {
var result = createDirectoryWatcher(childName, callback);
addChildDirectoryWatcher(result);
}
+ /**
+ * Add child directory watcher to the new ChildDirectoryWatcher list
+ */
function addChildDirectoryWatcher(childWatcher) {
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
@@ -3325,12 +3865,17 @@ var ts;
return parseInt(version.substring(1, dot));
}
ts.getNodeMajorVersion = getNodeMajorVersion;
+ // TODO: this is used as if it's certainly defined in many places.
ts.sys = (function () {
+ // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
+ // byte order mark from the specified encoding. Using any other byte order mark does
+ // not actually work.
var byteOrderMarkIndicator = "\uFEFF";
function getNodeSystem() {
var _fs = require("fs");
var _path = require("path");
var _os = require("os");
+ // crypto can be absent on reduced node installations
var _crypto;
try {
_crypto = require("crypto");
@@ -3403,7 +3948,7 @@ var ts;
return stat.size;
}
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return 0;
},
exit: function (exitCode) {
@@ -3416,6 +3961,7 @@ var ts;
require("source-map-support").install();
}
catch (_a) {
+ // Could not enable source maps.
}
},
setTimeout: setTimeout,
@@ -3441,11 +3987,14 @@ var ts;
};
return nodeSystem;
function isFileSystemCaseSensitive() {
+ // win32\win64 are case insensitive platforms
if (platform === "win32" || platform === "win64") {
return false;
}
+ // If this file exists under a different case, we must be case-insensitve.
return !fileExists(swapCase(__filename));
}
+ /** Convert all lowercase chars to uppercase, and vice-versa */
function swapCase(s) {
return s.replace(/\w/g, function (ch) {
var up = ch.toUpperCase();
@@ -3455,22 +4004,30 @@ var ts;
function getWatchFile() {
switch (tscWatchFile) {
case "PriorityPollingInterval":
+ // Use polling interval based on priority when create watch using host.watchFile
return fsWatchFile;
case "DynamicPriorityPolling":
+ // Use polling interval but change the interval depending on file changes and their default polling interval
return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout });
case "UseFsEvents":
+ // Use notifications from FS to watch with falling back to fs.watchFile
return watchFileUsingFsWatch;
case "UseFsEventsWithFallbackDynamicPolling":
+ // Use notifications from FS to watch with falling back to dynamic watch file
dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout });
return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile);
case "UseFsEventsOnParentDirectory":
+ // Use notifications from FS to watch with falling back to fs.watchFile
return createNonPollingWatchFile();
}
return useNonPollingWatchers ?
createNonPollingWatchFile() :
+ // Default to do not use polling interval as it is before this experiment branch
function (fileName, callback) { return fsWatchFile(fileName, callback); };
}
function getWatchDirectory() {
+ // 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)
var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
if (fsSupportsRecursive) {
return watchDirectoryUsingFsWatch;
@@ -3492,10 +4049,11 @@ var ts;
return watchDirectoryRecursively(directoryName, callback);
}
watchDirectory(directoryName, callback);
- return undefined;
+ return undefined; // TODO: GH#18217
};
}
function createNonPollingWatchFile() {
+ // One file can have multiple watchers
var fileWatcherCallbacks = ts.createMultiMap();
var dirWatchers = ts.createMap();
var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
@@ -3521,9 +4079,11 @@ var ts;
}
function createDirectoryWatcher(dirName, dirPath) {
var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) {
+ // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
var fileName = !ts.isString(relativeFileName)
- ? undefined
+ ? undefined // TODO: GH#18217
: ts.getNormalizedAbsolutePath(relativeFileName, dirName);
+ // Some applications save a working file via rename operations
var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName));
if (callbacks) {
for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
@@ -3544,9 +4104,12 @@ var ts;
close: function () { return _fs.unwatchFile(fileName, fileChanged); }
};
function fileChanged(curr, prev) {
+ // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears)
+ // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
if (+curr.mtime === 0) {
if (isPreviouslyDeleted) {
+ // Already deleted file, no need to callback again
return;
}
eventKind = FileWatcherEventKind.Deleted;
@@ -3554,10 +4117,12 @@ var ts;
else if (isPreviouslyDeleted) {
eventKind = FileWatcherEventKind.Created;
}
+ // If there is no change in modified time, ignore the event
else if (+curr.mtime === +prev.mtime) {
return;
}
else {
+ // File changed
eventKind = FileWatcherEventKind.Changed;
}
callback(fileName, eventKind);
@@ -3572,36 +4137,55 @@ var ts;
callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
}
else {
+ // Change
callback(fileName, FileWatcherEventKind.Changed);
}
};
}
function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
return function (eventName, relativeFileName) {
+ // In watchDirectory we only care about adding and removing files (when event name is
+ // "rename"); changes made within files are handled by corresponding fileWatchers (when
+ // event name is "change")
if (eventName === "rename") {
+ // When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
}
};
}
function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) {
var options;
+ /** Watcher for the file system entry depending on whether it is missing or present */
var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
watchMissingFileSystemEntry() :
watchPresentFileSystemEntry();
return {
close: function () {
+ // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
watcher.close();
watcher = undefined;
}
};
+ /**
+ * Invoke the callback with rename and update the watcher if not closed
+ * @param createWatcher
+ */
function invokeCallbackAndUpdateWatcher(createWatcher) {
+ // Call the callback for current directory
callback("rename", "");
+ // If watcher is not closed, update it
if (watcher) {
watcher.close();
watcher = createWatcher();
}
}
+ /**
+ * Watch the file or directory that is currently present
+ * and when the watched file or directory is deleted, switch to missing file system entry watcher
+ */
function watchPresentFileSystemEntry() {
+ // 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)
if (options === undefined) {
if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
@@ -3612,32 +4196,47 @@ var ts;
}
try {
var presentWatcher = _fs.watch(fileOrDirectory, options, callback);
+ // Watch the missing file or directory or error
presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
return presentWatcher;
}
catch (e) {
+ // Catch the exception and use polling instead
+ // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
+ // so instead of throwing error, use fs.watchFile
return watchPresentFileSystemEntryWithFsWatchFile();
}
}
+ /**
+ * Watch the file or directory using fs.watchFile since fs.watch threw exception
+ * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
+ */
function watchPresentFileSystemEntryWithFsWatchFile() {
return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval);
}
+ /**
+ * Watch the file or directory that is missing
+ * and switch to existing file or directory when the missing filesystem entry is created
+ */
function watchMissingFileSystemEntry() {
return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) {
if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
+ // Call the callback for current file or directory
+ // For now it could be callback for the inner directory creation,
+ // but just return current directory, better than current no-op
invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
}
}, pollingInterval);
}
}
function watchFileUsingFsWatch(fileName, callback, pollingInterval) {
- return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, fsWatchFile, pollingInterval);
+ return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval);
}
function createWatchFileUsingDynamicWatchFile(watchFile) {
- return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, watchFile, pollingInterval); };
+ return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); };
}
function fsWatchDirectory(directoryName, callback, recursive) {
- return fsWatch(directoryName, 1, callback, !!recursive, fsWatchFile);
+ return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile);
}
function watchDirectoryUsingFsWatch(directoryName, callback, recursive) {
return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive);
@@ -3652,7 +4251,9 @@ var ts;
var buffer = _fs.readFileSync(fileName);
var len = buffer.length;
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
- len &= ~1;
+ // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
+ // flip all byte pairs and treat as little endian.
+ len &= ~1; // Round down to a multiple of 2
for (var i = 0; i < len; i += 2) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
@@ -3661,21 +4262,25 @@ var ts;
return buffer.toString("utf16le", 2);
}
if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
+ // Little endian UTF-16 byte order mark detected
return buffer.toString("utf16le", 2);
}
if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
+ // UTF-8 byte order mark detected
return buffer.toString("utf8", 3);
}
+ // Default is UTF-8 with no byte order mark
return buffer.toString("utf8");
}
function writeFile(fileName, data, writeByteOrderMark) {
+ // If a BOM is required, emit one
if (writeByteOrderMark) {
data = byteOrderMarkIndicator + data;
}
var fd;
try {
fd = _fs.openSync(fileName, "w");
- _fs.writeSync(fd, data, undefined, "utf8");
+ _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
}
finally {
if (fd !== undefined) {
@@ -3690,6 +4295,8 @@ var ts;
var directories = [];
for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
var entry = entries_2[_i];
+ // This is necessary because on some file system node fails to exclude
+ // "." and "..". See https://github.com/nodejs/node/issues/4002
if (entry === "." || entry === "..") {
continue;
}
@@ -3721,8 +4328,8 @@ var ts;
try {
var stat = _fs.statSync(path);
switch (entryKind) {
- case 0: return stat.isFile();
- case 1: return stat.isDirectory();
+ case 0 /* File */: return stat.isFile();
+ case 1 /* Directory */: return stat.isDirectory();
default: return false;
}
}
@@ -3731,13 +4338,13 @@ var ts;
}
}
function fileExists(path) {
- return fileSystemEntryExists(path, 0);
+ return fileSystemEntryExists(path, 0 /* File */);
}
function directoryExists(path) {
- return fileSystemEntryExists(path, 1);
+ return fileSystemEntryExists(path, 1 /* Directory */);
}
function getDirectories(path) {
- return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); });
+ return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); });
}
function realpath(path) {
try {
@@ -3771,6 +4378,10 @@ var ts;
return;
}
}
+ /**
+ * djb2 hashing algorithm
+ * http://www.cse.yorku.ca/~oz/hash.html
+ */
function generateDjb2Hash(data) {
var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
@@ -3794,9 +4405,11 @@ var ts;
useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames,
write: ChakraHost.echo,
readFile: function (path, _encoding) {
+ // encoding is automatically handled by the implementation in ChakraHost
return ChakraHost.readFile(path);
},
writeFile: function (path, data, writeByteOrderMark) {
+ // If a BOM is required, emit one
if (writeByteOrderMark) {
data = byteOrderMarkIndicator + data;
}
@@ -3833,9 +4446,12 @@ var ts;
sys = getChakraSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
+ // process and process.nextTick checks if current environment is node-like
+ // process.browser check excludes webpack and browserify
sys = getNodeSystem();
}
if (sys) {
+ // patch writefile to create folder before writing the file
var originalWriteFile_1 = sys.writeFile;
sys.writeFile = function (path, data, writeBom) {
var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path));
@@ -3850,18 +4466,22 @@ var ts;
if (ts.sys && ts.sys.getEnvironmentVariable) {
setCustomPollingValues(ts.sys);
ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
- ? 1
- : 0;
+ ? 1 /* Normal */
+ : 0 /* None */;
}
if (ts.sys && ts.sys.debugMode) {
ts.Debug.isDebugging = true;
}
})(ts || (ts = {}));
+//
+// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
+/* @internal */
var ts;
(function (ts) {
function diag(code, category, key, message, reportsUnnecessary) {
return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary };
}
+ // tslint:disable-next-line variable-name
ts.Diagnostics = {
Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
@@ -4424,7 +5044,7 @@ var ts;
_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."),
Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."),
- Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true),
+ Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true),
The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"),
An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."),
@@ -4690,12 +5310,12 @@ var ts;
Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."),
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."),
File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."),
- _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", true),
+ _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."),
Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."),
- Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", true),
+ Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."),
Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."),
@@ -4748,14 +5368,14 @@ var ts;
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
- All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", true),
+ All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true),
Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."),
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
- _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true),
+ _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
- All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true),
- All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", true),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
+ All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
@@ -4805,8 +5425,8 @@ var ts;
Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."),
JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."),
- Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true),
- Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true),
+ Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
+ Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."),
Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."),
@@ -4966,157 +5586,204 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ /* @internal */
function tokenIsIdentifierOrKeyword(token) {
- return token >= 71;
+ return token >= 71 /* Identifier */;
}
ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
+ /* @internal */
function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
- return token === 29 || tokenIsIdentifierOrKeyword(token);
+ return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
}
ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
var textToToken = ts.createMapFromTemplate({
- "abstract": 117,
- "any": 119,
- "as": 118,
- "boolean": 122,
- "break": 72,
- "case": 73,
- "catch": 74,
- "class": 75,
- "continue": 77,
- "const": 76,
- "constructor": 123,
- "debugger": 78,
- "declare": 124,
- "default": 79,
- "delete": 80,
- "do": 81,
- "else": 82,
- "enum": 83,
- "export": 84,
- "extends": 85,
- "false": 86,
- "finally": 87,
- "for": 88,
- "from": 143,
- "function": 89,
- "get": 125,
- "if": 90,
- "implements": 108,
- "import": 91,
- "in": 92,
- "infer": 126,
- "instanceof": 93,
- "interface": 109,
- "is": 127,
- "keyof": 128,
- "let": 110,
- "module": 129,
- "namespace": 130,
- "never": 131,
- "new": 94,
- "null": 95,
- "number": 134,
- "object": 135,
- "package": 111,
- "private": 112,
- "protected": 113,
- "public": 114,
- "readonly": 132,
- "require": 133,
- "global": 144,
- "return": 96,
- "set": 136,
- "static": 115,
- "string": 137,
- "super": 97,
- "switch": 98,
- "symbol": 138,
- "this": 99,
- "throw": 100,
- "true": 101,
- "try": 102,
- "type": 139,
- "typeof": 103,
- "undefined": 140,
- "unique": 141,
- "unknown": 142,
- "var": 104,
- "void": 105,
- "while": 106,
- "with": 107,
- "yield": 116,
- "async": 120,
- "await": 121,
- "of": 145,
- "{": 17,
- "}": 18,
- "(": 19,
- ")": 20,
- "[": 21,
- "]": 22,
- ".": 23,
- "...": 24,
- ";": 25,
- ",": 26,
- "<": 27,
- ">": 29,
- "<=": 30,
- ">=": 31,
- "==": 32,
- "!=": 33,
- "===": 34,
- "!==": 35,
- "=>": 36,
- "+": 37,
- "-": 38,
- "**": 40,
- "*": 39,
- "/": 41,
- "%": 42,
- "++": 43,
- "--": 44,
- "<<": 45,
- "": 28,
- ">>": 46,
- ">>>": 47,
- "&": 48,
- "|": 49,
- "^": 50,
- "!": 51,
- "~": 52,
- "&&": 53,
- "||": 54,
- "?": 55,
- ":": 56,
- "=": 58,
- "+=": 59,
- "-=": 60,
- "*=": 61,
- "**=": 62,
- "/=": 63,
- "%=": 64,
- "<<=": 65,
- ">>=": 66,
- ">>>=": 67,
- "&=": 68,
- "|=": 69,
- "^=": 70,
- "@": 57,
+ "abstract": 117 /* AbstractKeyword */,
+ "any": 119 /* AnyKeyword */,
+ "as": 118 /* AsKeyword */,
+ "boolean": 122 /* BooleanKeyword */,
+ "break": 72 /* BreakKeyword */,
+ "case": 73 /* CaseKeyword */,
+ "catch": 74 /* CatchKeyword */,
+ "class": 75 /* ClassKeyword */,
+ "continue": 77 /* ContinueKeyword */,
+ "const": 76 /* ConstKeyword */,
+ "constructor": 123 /* ConstructorKeyword */,
+ "debugger": 78 /* DebuggerKeyword */,
+ "declare": 124 /* DeclareKeyword */,
+ "default": 79 /* DefaultKeyword */,
+ "delete": 80 /* DeleteKeyword */,
+ "do": 81 /* DoKeyword */,
+ "else": 82 /* ElseKeyword */,
+ "enum": 83 /* EnumKeyword */,
+ "export": 84 /* ExportKeyword */,
+ "extends": 85 /* ExtendsKeyword */,
+ "false": 86 /* FalseKeyword */,
+ "finally": 87 /* FinallyKeyword */,
+ "for": 88 /* ForKeyword */,
+ "from": 143 /* FromKeyword */,
+ "function": 89 /* FunctionKeyword */,
+ "get": 125 /* GetKeyword */,
+ "if": 90 /* IfKeyword */,
+ "implements": 108 /* ImplementsKeyword */,
+ "import": 91 /* ImportKeyword */,
+ "in": 92 /* InKeyword */,
+ "infer": 126 /* InferKeyword */,
+ "instanceof": 93 /* InstanceOfKeyword */,
+ "interface": 109 /* InterfaceKeyword */,
+ "is": 127 /* IsKeyword */,
+ "keyof": 128 /* KeyOfKeyword */,
+ "let": 110 /* LetKeyword */,
+ "module": 129 /* ModuleKeyword */,
+ "namespace": 130 /* NamespaceKeyword */,
+ "never": 131 /* NeverKeyword */,
+ "new": 94 /* NewKeyword */,
+ "null": 95 /* NullKeyword */,
+ "number": 134 /* NumberKeyword */,
+ "object": 135 /* ObjectKeyword */,
+ "package": 111 /* PackageKeyword */,
+ "private": 112 /* PrivateKeyword */,
+ "protected": 113 /* ProtectedKeyword */,
+ "public": 114 /* PublicKeyword */,
+ "readonly": 132 /* ReadonlyKeyword */,
+ "require": 133 /* RequireKeyword */,
+ "global": 144 /* GlobalKeyword */,
+ "return": 96 /* ReturnKeyword */,
+ "set": 136 /* SetKeyword */,
+ "static": 115 /* StaticKeyword */,
+ "string": 137 /* StringKeyword */,
+ "super": 97 /* SuperKeyword */,
+ "switch": 98 /* SwitchKeyword */,
+ "symbol": 138 /* SymbolKeyword */,
+ "this": 99 /* ThisKeyword */,
+ "throw": 100 /* ThrowKeyword */,
+ "true": 101 /* TrueKeyword */,
+ "try": 102 /* TryKeyword */,
+ "type": 139 /* TypeKeyword */,
+ "typeof": 103 /* TypeOfKeyword */,
+ "undefined": 140 /* UndefinedKeyword */,
+ "unique": 141 /* UniqueKeyword */,
+ "unknown": 142 /* UnknownKeyword */,
+ "var": 104 /* VarKeyword */,
+ "void": 105 /* VoidKeyword */,
+ "while": 106 /* WhileKeyword */,
+ "with": 107 /* WithKeyword */,
+ "yield": 116 /* YieldKeyword */,
+ "async": 120 /* AsyncKeyword */,
+ "await": 121 /* AwaitKeyword */,
+ "of": 145 /* OfKeyword */,
+ "{": 17 /* OpenBraceToken */,
+ "}": 18 /* CloseBraceToken */,
+ "(": 19 /* OpenParenToken */,
+ ")": 20 /* CloseParenToken */,
+ "[": 21 /* OpenBracketToken */,
+ "]": 22 /* CloseBracketToken */,
+ ".": 23 /* DotToken */,
+ "...": 24 /* DotDotDotToken */,
+ ";": 25 /* SemicolonToken */,
+ ",": 26 /* CommaToken */,
+ "<": 27 /* LessThanToken */,
+ ">": 29 /* GreaterThanToken */,
+ "<=": 30 /* LessThanEqualsToken */,
+ ">=": 31 /* GreaterThanEqualsToken */,
+ "==": 32 /* EqualsEqualsToken */,
+ "!=": 33 /* ExclamationEqualsToken */,
+ "===": 34 /* EqualsEqualsEqualsToken */,
+ "!==": 35 /* ExclamationEqualsEqualsToken */,
+ "=>": 36 /* EqualsGreaterThanToken */,
+ "+": 37 /* PlusToken */,
+ "-": 38 /* MinusToken */,
+ "**": 40 /* AsteriskAsteriskToken */,
+ "*": 39 /* AsteriskToken */,
+ "/": 41 /* SlashToken */,
+ "%": 42 /* PercentToken */,
+ "++": 43 /* PlusPlusToken */,
+ "--": 44 /* MinusMinusToken */,
+ "<<": 45 /* LessThanLessThanToken */,
+ "": 28 /* LessThanSlashToken */,
+ ">>": 46 /* GreaterThanGreaterThanToken */,
+ ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */,
+ "&": 48 /* AmpersandToken */,
+ "|": 49 /* BarToken */,
+ "^": 50 /* CaretToken */,
+ "!": 51 /* ExclamationToken */,
+ "~": 52 /* TildeToken */,
+ "&&": 53 /* AmpersandAmpersandToken */,
+ "||": 54 /* BarBarToken */,
+ "?": 55 /* QuestionToken */,
+ ":": 56 /* ColonToken */,
+ "=": 58 /* EqualsToken */,
+ "+=": 59 /* PlusEqualsToken */,
+ "-=": 60 /* MinusEqualsToken */,
+ "*=": 61 /* AsteriskEqualsToken */,
+ "**=": 62 /* AsteriskAsteriskEqualsToken */,
+ "/=": 63 /* SlashEqualsToken */,
+ "%=": 64 /* PercentEqualsToken */,
+ "<<=": 65 /* LessThanLessThanEqualsToken */,
+ ">>=": 66 /* GreaterThanGreaterThanEqualsToken */,
+ ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */,
+ "&=": 68 /* AmpersandEqualsToken */,
+ "|=": 69 /* BarEqualsToken */,
+ "^=": 70 /* CaretEqualsToken */,
+ "@": 57 /* AtToken */,
});
+ /*
+ As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
+ IdentifierStart ::
+ Can contain Unicode 3.0.0 categories:
+ Uppercase letter (Lu),
+ Lowercase letter (Ll),
+ Titlecase letter (Lt),
+ Modifier letter (Lm),
+ Other letter (Lo), or
+ Letter number (Nl).
+ IdentifierPart :: =
+ Can contain IdentifierStart + Unicode 3.0.0 categories:
+ Non-spacing mark (Mn),
+ Combining spacing mark (Mc),
+ Decimal number (Nd), or
+ Connector punctuation (Pc).
+
+ Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
+ http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
+ */
var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
+ /*
+ As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
+ IdentifierStart ::
+ Can contain Unicode 6.2 categories:
+ Uppercase letter (Lu),
+ Lowercase letter (Ll),
+ Titlecase letter (Lt),
+ Modifier letter (Lm),
+ Other letter (Lo), or
+ Letter number (Nl).
+ IdentifierPart ::
+ Can contain IdentifierStart + Unicode 6.2 categories:
+ Non-spacing mark (Mn),
+ Combining spacing mark (Mc),
+ Decimal number (Nd),
+ Connector punctuation (Pc),
+ , or
+ .
+
+ Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
+ http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
+ */
var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
function lookupInUnicodeMap(code, map) {
+ // Bail out quickly if it couldn't possibly be in the map.
if (code < map[0]) {
return false;
}
+ // Perform binary search in one of the Unicode range maps
var lo = 0;
var hi = map.length;
var mid;
while (lo + 1 < hi) {
mid = lo + (hi - lo) / 2;
+ // mid has to be even to catch a range's beginning
mid -= mid % 2;
if (map[mid] <= code && code <= map[mid + 1]) {
return true;
@@ -5130,14 +5797,14 @@ var ts;
}
return false;
}
- function isUnicodeIdentifierStart(code, languageVersion) {
- return languageVersion >= 1 ?
+ /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
+ return languageVersion >= 1 /* ES5 */ ?
lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
lookupInUnicodeMap(code, unicodeES3IdentifierStart);
}
ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
function isUnicodeIdentifierPart(code, languageVersion) {
- return languageVersion >= 1 ?
+ return languageVersion >= 1 /* ES5 */ ?
lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
lookupInUnicodeMap(code, unicodeES3IdentifierPart);
}
@@ -5153,10 +5820,12 @@ var ts;
return tokenStrings[t];
}
ts.tokenToString = tokenToString;
+ /* @internal */
function stringToToken(s) {
return textToToken.get(s);
}
ts.stringToToken = stringToToken;
+ /* @internal */
function computeLineStarts(text) {
var result = new Array();
var pos = 0;
@@ -5165,16 +5834,17 @@ var ts;
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
- case 13:
- if (text.charCodeAt(pos) === 10) {
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
}
- case 10:
+ // falls through
+ case 10 /* lineFeed */:
result.push(lineStart);
lineStart = pos;
break;
default:
- if (ch > 127 && isLineBreak(ch)) {
+ if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
result.push(lineStart);
lineStart = pos;
}
@@ -5189,6 +5859,7 @@ var ts;
return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text);
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
+ /* @internal */
function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
if (line < 0 || line >= lineStarts.length) {
ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
@@ -5198,18 +5869,30 @@ var ts;
ts.Debug.assert(res < lineStarts[line + 1]);
}
else if (debugText !== undefined) {
- ts.Debug.assert(res <= debugText.length);
+ ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
}
return res;
}
ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
+ /* @internal */
function getLineStarts(sourceFile) {
return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
}
ts.getLineStarts = getLineStarts;
+ /* @internal */
+ /**
+ * We assume the first line starts at position 0 and 'position' is non-negative.
+ */
function computeLineAndCharacterOfPosition(lineStarts, position) {
var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues);
if (lineNumber < 0) {
+ // If the actual position was not found,
+ // the binary search returns the 2's-complement of the next line start
+ // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
+ // then the search will return -2.
+ //
+ // We want the index of the previous line start, so we subtract 1.
+ // Review 2's-complement if this is confusing.
lineNumber = ~lineNumber - 1;
ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
}
@@ -5227,86 +5910,107 @@ var ts;
return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
}
ts.isWhiteSpaceLike = isWhiteSpaceLike;
+ /** Does not include line breaks. For that, see isWhiteSpaceLike. */
function isWhiteSpaceSingleLine(ch) {
- return ch === 32 ||
- ch === 9 ||
- ch === 11 ||
- ch === 12 ||
- ch === 160 ||
- ch === 133 ||
- ch === 5760 ||
- ch >= 8192 && ch <= 8203 ||
- ch === 8239 ||
- ch === 8287 ||
- ch === 12288 ||
- ch === 65279;
+ // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
+ // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
+ return ch === 32 /* space */ ||
+ ch === 9 /* tab */ ||
+ ch === 11 /* verticalTab */ ||
+ ch === 12 /* formFeed */ ||
+ ch === 160 /* nonBreakingSpace */ ||
+ ch === 133 /* nextLine */ ||
+ ch === 5760 /* ogham */ ||
+ ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
+ ch === 8239 /* narrowNoBreakSpace */ ||
+ ch === 8287 /* mathematicalSpace */ ||
+ ch === 12288 /* ideographicSpace */ ||
+ ch === 65279 /* byteOrderMark */;
}
ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
function isLineBreak(ch) {
- return ch === 10 ||
- ch === 13 ||
- ch === 8232 ||
- ch === 8233;
+ // ES5 7.3:
+ // The ECMAScript line terminator characters are listed in Table 3.
+ // Table 3: Line Terminator Characters
+ // Code Unit Value Name Formal Name
+ // \u000A Line Feed
+ // \u000D Carriage Return
+ // \u2028 Line separator
+ // \u2029 Paragraph separator
+ // Only the characters in Table 3 are treated as line terminators. Other new line or line
+ // breaking characters are treated as white space but not as line terminators.
+ return ch === 10 /* lineFeed */ ||
+ ch === 13 /* carriageReturn */ ||
+ ch === 8232 /* lineSeparator */ ||
+ ch === 8233 /* paragraphSeparator */;
}
ts.isLineBreak = isLineBreak;
function isDigit(ch) {
- return ch >= 48 && ch <= 57;
+ return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
}
+ /* @internal */
function isOctalDigit(ch) {
- return ch >= 48 && ch <= 55;
+ return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
}
ts.isOctalDigit = isOctalDigit;
function couldStartTrivia(text, pos) {
+ // Keep in sync with skipTrivia
var ch = text.charCodeAt(pos);
switch (ch) {
- case 13:
- case 10:
- case 9:
- case 11:
- case 12:
- case 32:
- case 47:
- case 60:
- case 124:
- case 61:
- case 62:
+ case 13 /* carriageReturn */:
+ case 10 /* lineFeed */:
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
+ case 47 /* slash */:
+ // starts of normal trivia
+ case 60 /* lessThan */:
+ case 124 /* bar */:
+ case 61 /* equals */:
+ case 62 /* greaterThan */:
+ // Starts of conflict marker trivia
return true;
- case 35:
+ case 35 /* hash */:
+ // Only if its the beginning can we have #! trivia
return pos === 0;
default:
- return ch > 127;
+ return ch > 127 /* maxAsciiCharacter */;
}
}
ts.couldStartTrivia = couldStartTrivia;
+ /* @internal */
function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
if (stopAtComments === void 0) { stopAtComments = false; }
if (ts.positionIsSynthesized(pos)) {
return pos;
}
+ // Keep in sync with couldStartTrivia
while (true) {
var ch = text.charCodeAt(pos);
switch (ch) {
- case 13:
- if (text.charCodeAt(pos + 1) === 10) {
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
pos++;
}
- case 10:
+ // falls through
+ case 10 /* lineFeed */:
pos++;
if (stopAfterLineBreak) {
return pos;
}
continue;
- case 9:
- case 11:
- case 12:
- case 32:
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
pos++;
continue;
- case 47:
+ case 47 /* slash */:
if (stopAtComments) {
break;
}
- if (text.charCodeAt(pos + 1) === 47) {
+ if (text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
@@ -5316,10 +6020,10 @@ var ts;
}
continue;
}
- if (text.charCodeAt(pos + 1) === 42) {
+ if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
pos += 2;
while (pos < text.length) {
- if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) === 47) {
+ if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
break;
}
@@ -5328,23 +6032,23 @@ var ts;
continue;
}
break;
- case 60:
- case 124:
- case 61:
- case 62:
+ case 60 /* lessThan */:
+ case 124 /* bar */:
+ case 61 /* equals */:
+ case 62 /* greaterThan */:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos);
continue;
}
break;
- case 35:
+ case 35 /* hash */:
if (pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
continue;
}
break;
default:
- if (ch > 127 && (isWhiteSpaceLike(ch))) {
+ if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
pos++;
continue;
}
@@ -5354,9 +6058,12 @@ var ts;
}
}
ts.skipTrivia = skipTrivia;
+ // All conflict markers consist of the same character repeated seven times. If it is
+ // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
var mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text, pos) {
ts.Debug.assert(pos >= 0);
+ // Conflict markers must be at the start of a line.
if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
var ch = text.charCodeAt(pos);
if ((pos + mergeConflictMarkerLength) < text.length) {
@@ -5365,8 +6072,8 @@ var ts;
return false;
}
}
- return ch === 61 ||
- text.charCodeAt(pos + mergeConflictMarkerLength) === 32;
+ return ch === 61 /* equals */ ||
+ text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
}
}
return false;
@@ -5377,16 +6084,18 @@ var ts;
}
var ch = text.charCodeAt(pos);
var len = text.length;
- if (ch === 60 || ch === 62) {
+ if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
pos++;
}
}
else {
- ts.Debug.assert(ch === 124 || ch === 61);
+ ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
+ // Consume everything from the start of a ||||||| or ======= marker to the start
+ // of the next ======= or >>>>>>> marker.
while (pos < len) {
var currentChar = text.charCodeAt(pos);
- if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
+ if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
break;
}
pos++;
@@ -5396,6 +6105,7 @@ var ts;
}
var shebangTriviaRegex = /^#!.*/;
function isShebangTrivia(text, pos) {
+ // Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
@@ -5404,6 +6114,26 @@ var ts;
pos = pos + shebang.length;
return pos;
}
+ /**
+ * Invokes a callback for each comment range following the provided position.
+ *
+ * Single-line comment ranges include the leading double-slash characters but not the ending
+ * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
+ * asterisk-slash characters.
+ *
+ * @param reduce If true, accumulates the result of calling the callback in a fashion similar
+ * to reduceLeft. If false, iteration stops when the callback returns a truthy value.
+ * @param text The source text to scan.
+ * @param pos The position at which to start scanning.
+ * @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.
+ * @param cb The callback to execute as each comment range is encountered.
+ * @param state A state value to pass to each iteration of the callback.
+ * @param initial An initial value to pass when accumulating results (when "reduce" is true).
+ * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
+ * return value of the callback.
+ */
function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
var pendingPos;
var pendingEnd;
@@ -5415,11 +6145,12 @@ var ts;
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
- case 13:
- if (text.charCodeAt(pos + 1) === 10) {
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
pos++;
}
- case 10:
+ // falls through
+ case 10 /* lineFeed */:
pos++;
if (trailing) {
break scan;
@@ -5429,20 +6160,20 @@ var ts;
pendingHasTrailingNewLine = true;
}
continue;
- case 9:
- case 11:
- case 12:
- case 32:
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
pos++;
continue;
- case 47:
+ case 47 /* slash */:
var nextChar = text.charCodeAt(pos + 1);
var hasTrailingNewLine = false;
- if (nextChar === 47 || nextChar === 42) {
- var kind = nextChar === 47 ? 2 : 3;
+ if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
+ var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
var startPos = pos;
pos += 2;
- if (nextChar === 47) {
+ if (nextChar === 47 /* slash */) {
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
hasTrailingNewLine = true;
@@ -5453,7 +6184,7 @@ var ts;
}
else {
while (pos < text.length) {
- if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) === 47) {
+ if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
break;
}
@@ -5464,6 +6195,7 @@ var ts;
if (hasPendingCommentRange) {
accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
if (!reduce && accumulator) {
+ // If we are not reducing and we have a truthy result, return it.
return accumulator;
}
}
@@ -5477,7 +6209,7 @@ var ts;
}
break scan;
default:
- if (ch > 127 && (isWhiteSpaceLike(ch))) {
+ if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
if (hasPendingCommentRange && isLineBreak(ch)) {
pendingHasTrailingNewLine = true;
}
@@ -5493,19 +6225,19 @@ var ts;
return accumulator;
}
function forEachLeadingCommentRange(text, pos, cb, state) {
- return iterateCommentRanges(false, text, pos, false, cb, state);
+ return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
}
ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
function forEachTrailingCommentRange(text, pos, cb, state) {
- return iterateCommentRanges(false, text, pos, true, cb, state);
+ return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
}
ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
- return iterateCommentRanges(true, text, pos, false, cb, state, initial);
+ return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
}
ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
- return iterateCommentRanges(true, text, pos, true, cb, state, initial);
+ return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
}
ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
@@ -5516,13 +6248,14 @@ var ts;
return comments;
}
function getLeadingCommentRanges(text, pos) {
- return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined);
+ return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
}
ts.getLeadingCommentRanges = getLeadingCommentRanges;
function getTrailingCommentRanges(text, pos) {
- return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined);
+ return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
}
ts.getTrailingCommentRanges = getTrailingCommentRanges;
+ /** Optionally, get the shebang */
function getShebang(text) {
var match = shebangTriviaRegex.exec(text);
if (match) {
@@ -5531,17 +6264,18 @@ var ts;
}
ts.getShebang = getShebang;
function isIdentifierStart(ch, languageVersion) {
- return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 ||
- ch === 36 || ch === 95 ||
- ch > 127 && isUnicodeIdentifierStart(ch, languageVersion);
+ return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
+ ch === 36 /* $ */ || ch === 95 /* _ */ ||
+ ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
}
ts.isIdentifierStart = isIdentifierStart;
function isIdentifierPart(ch, languageVersion) {
- return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 ||
- ch >= 48 && ch <= 57 || ch === 36 || ch === 95 ||
- ch > 127 && isUnicodeIdentifierPart(ch, languageVersion);
+ return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
+ ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
+ ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
}
ts.isIdentifierPart = isIdentifierPart;
+ /* @internal */
function isIdentifierText(name, languageVersion) {
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
return false;
@@ -5554,12 +6288,17 @@ var ts;
return true;
}
ts.isIdentifierText = isIdentifierText;
+ // Creates a scanner over a (possibly unspecified) range of a piece of text.
function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
- if (languageVariant === void 0) { languageVariant = 0; }
+ if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
var text = textInitial;
+ // Current position (end position of text of current token)
var pos;
+ // end of text
var end;
+ // Start position of whitespace before current token
var startPos;
+ // Start position of text of current token
var tokenPos;
var token;
var tokenValue;
@@ -5572,11 +6311,11 @@ var ts;
getTokenPos: function () { return tokenPos; },
getTokenText: function () { return text.substring(tokenPos, pos); },
getTokenValue: function () { return tokenValue; },
- hasExtendedUnicodeEscape: function () { return (tokenFlags & 8) !== 0; },
- hasPrecedingLineBreak: function () { return (tokenFlags & 1) !== 0; },
- isIdentifier: function () { return token === 71 || token > 107; },
- isReservedWord: function () { return token >= 72 && token <= 107; },
- isUnterminated: function () { return (tokenFlags & 4) !== 0; },
+ hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
+ hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
+ isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; },
+ isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; },
+ isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
getTokenFlags: function () { return tokenFlags; },
reScanGreaterToken: reScanGreaterToken,
reScanSlashToken: reScanSlashToken,
@@ -5613,8 +6352,8 @@ var ts;
var result = "";
while (true) {
var ch = text.charCodeAt(pos);
- if (ch === 95) {
- tokenFlags |= 512;
+ if (ch === 95 /* _ */) {
+ tokenFlags |= 512 /* ContainsSeparator */;
if (allowSeparator) {
allowSeparator = false;
isPreviousTokenSeparator = true;
@@ -5638,7 +6377,7 @@ var ts;
}
break;
}
- if (text.charCodeAt(pos - 1) === 95) {
+ if (text.charCodeAt(pos - 1) === 95 /* _ */) {
error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
}
return result + text.substring(start, pos);
@@ -5648,15 +6387,15 @@ var ts;
var mainFragment = scanNumberFragment();
var decimalFragment;
var scientificFragment;
- if (text.charCodeAt(pos) === 46) {
+ if (text.charCodeAt(pos) === 46 /* dot */) {
pos++;
decimalFragment = scanNumberFragment();
}
var end = pos;
- if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) {
+ if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
pos++;
- tokenFlags |= 16;
- if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45)
+ tokenFlags |= 16 /* Scientific */;
+ if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
pos++;
var preNumericPart = pos;
var finalFragment = scanNumberFragment();
@@ -5668,7 +6407,7 @@ var ts;
end = pos;
}
}
- if (tokenFlags & 512) {
+ if (tokenFlags & 512 /* ContainsSeparator */) {
var result = mainFragment;
if (decimalFragment) {
result += "." + decimalFragment;
@@ -5679,7 +6418,7 @@ var ts;
return "" + +result;
}
else {
- return "" + +(text.substring(start, end));
+ return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed
}
}
function scanOctalDigits() {
@@ -5689,11 +6428,19 @@ var ts;
}
return +(text.substring(start, pos));
}
+ /**
+ * Scans the given number of hexadecimal digits in the text,
+ * returning -1 if the given number is unavailable.
+ */
function scanExactNumberOfHexDigits(count, canHaveSeparators) {
- return scanHexDigits(count, false, canHaveSeparators);
+ return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
}
+ /**
+ * Scans as many hexadecimal digits as are available in the text,
+ * returning -1 if the given number of digits was unavailable.
+ */
function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
- return scanHexDigits(count, true, canHaveSeparators);
+ return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
}
function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
var digits = 0;
@@ -5702,8 +6449,8 @@ var ts;
var isPreviousTokenSeparator = false;
while (digits < minCount || scanAsManyAsPossible) {
var ch = text.charCodeAt(pos);
- if (canHaveSeparators && ch === 95) {
- tokenFlags |= 512;
+ if (canHaveSeparators && ch === 95 /* _ */) {
+ tokenFlags |= 512 /* ContainsSeparator */;
if (allowSeparator) {
allowSeparator = false;
isPreviousTokenSeparator = true;
@@ -5718,14 +6465,14 @@ var ts;
continue;
}
allowSeparator = canHaveSeparators;
- if (ch >= 48 && ch <= 57) {
- value = value * 16 + ch - 48;
+ if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
+ value = value * 16 + ch - 48 /* _0 */;
}
- else if (ch >= 65 && ch <= 70) {
- value = value * 16 + ch - 65 + 10;
+ else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
+ value = value * 16 + ch - 65 /* A */ + 10;
}
- else if (ch >= 97 && ch <= 102) {
- value = value * 16 + ch - 97 + 10;
+ else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
+ value = value * 16 + ch - 97 /* a */ + 10;
}
else {
break;
@@ -5737,7 +6484,7 @@ var ts;
if (digits < minCount) {
value = -1;
}
- if (text.charCodeAt(pos - 1) === 95) {
+ if (text.charCodeAt(pos - 1) === 95 /* _ */) {
error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
}
return value;
@@ -5751,7 +6498,7 @@ var ts;
while (true) {
if (pos >= end) {
result += text.substring(start, pos);
- tokenFlags |= 4;
+ tokenFlags |= 4 /* Unterminated */;
error(ts.Diagnostics.Unterminated_string_literal);
break;
}
@@ -5761,7 +6508,7 @@ var ts;
pos++;
break;
}
- if (ch === 92 && !jsxAttributeString) {
+ if (ch === 92 /* backslash */ && !jsxAttributeString) {
result += text.substring(start, pos);
result += scanEscapeSequence();
start = pos;
@@ -5769,7 +6516,7 @@ var ts;
}
if (isLineBreak(ch) && !jsxAttributeString) {
result += text.substring(start, pos);
- tokenFlags |= 4;
+ tokenFlags |= 4 /* Unterminated */;
error(ts.Diagnostics.Unterminated_string_literal);
break;
}
@@ -5777,8 +6524,12 @@ var ts;
}
return result;
}
+ /**
+ * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
+ * a literal component of a TemplateExpression.
+ */
function scanTemplateAndSetTokenValue() {
- var startedWithBacktick = text.charCodeAt(pos) === 96;
+ var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
pos++;
var start = pos;
var contents = "";
@@ -5786,34 +6537,39 @@ var ts;
while (true) {
if (pos >= end) {
contents += text.substring(start, pos);
- tokenFlags |= 4;
+ tokenFlags |= 4 /* Unterminated */;
error(ts.Diagnostics.Unterminated_template_literal);
- resultingToken = startedWithBacktick ? 13 : 16;
+ resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */;
break;
}
var currChar = text.charCodeAt(pos);
- if (currChar === 96) {
+ // '`'
+ if (currChar === 96 /* backtick */) {
contents += text.substring(start, pos);
pos++;
- resultingToken = startedWithBacktick ? 13 : 16;
+ resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */;
break;
}
- if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) {
+ // '${'
+ if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
contents += text.substring(start, pos);
pos += 2;
- resultingToken = startedWithBacktick ? 14 : 15;
+ resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */;
break;
}
- if (currChar === 92) {
+ // Escape character
+ if (currChar === 92 /* backslash */) {
contents += text.substring(start, pos);
contents += scanEscapeSequence();
start = pos;
continue;
}
- if (currChar === 13) {
+ // Speculated ECMAScript 6 Spec 11.8.6.1:
+ // and LineTerminatorSequences are normalized to for Template Values
+ if (currChar === 13 /* carriageReturn */) {
contents += text.substring(start, pos);
pos++;
- if (pos < end && text.charCodeAt(pos) === 10) {
+ if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
}
contents += "\n";
@@ -5835,47 +6591,53 @@ var ts;
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
- case 48:
+ case 48 /* _0 */:
return "\0";
- case 98:
+ case 98 /* b */:
return "\b";
- case 116:
+ case 116 /* t */:
return "\t";
- case 110:
+ case 110 /* n */:
return "\n";
- case 118:
+ case 118 /* v */:
return "\v";
- case 102:
+ case 102 /* f */:
return "\f";
- case 114:
+ case 114 /* r */:
return "\r";
- case 39:
+ case 39 /* singleQuote */:
return "\'";
- case 34:
+ case 34 /* doubleQuote */:
return "\"";
- case 117:
- if (pos < end && text.charCodeAt(pos) === 123) {
- tokenFlags |= 8;
+ case 117 /* u */:
+ // '\u{DDDDDDDD}'
+ if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
+ tokenFlags |= 8 /* ExtendedUnicodeEscape */;
pos++;
return scanExtendedUnicodeEscape();
}
- return scanHexadecimalEscape(4);
- case 120:
- return scanHexadecimalEscape(2);
- case 13:
- if (pos < end && text.charCodeAt(pos) === 10) {
+ // '\uDDDD'
+ return scanHexadecimalEscape(/*numDigits*/ 4);
+ case 120 /* x */:
+ // '\xDD'
+ return scanHexadecimalEscape(/*numDigits*/ 2);
+ // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
+ // the line terminator is interpreted to be "the empty code unit sequence".
+ case 13 /* carriageReturn */:
+ if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
}
- case 10:
- case 8232:
- case 8233:
+ // falls through
+ case 10 /* lineFeed */:
+ case 8232 /* lineSeparator */:
+ case 8233 /* paragraphSeparator */:
return "";
default:
return String.fromCharCode(ch);
}
}
function scanHexadecimalEscape(numDigits) {
- var escapedValue = scanExactNumberOfHexDigits(numDigits, false);
+ var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
if (escapedValue >= 0) {
return String.fromCharCode(escapedValue);
}
@@ -5885,8 +6647,9 @@ var ts;
}
}
function scanExtendedUnicodeEscape() {
- var escapedValue = scanMinimumNumberOfHexDigits(1, false);
+ var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
var isInvalidExtendedEscape = false;
+ // Validate the value of the digit
if (escapedValue < 0) {
error(ts.Diagnostics.Hexadecimal_digit_expected);
isInvalidExtendedEscape = true;
@@ -5899,7 +6662,8 @@ var ts;
error(ts.Diagnostics.Unexpected_end_of_text);
isInvalidExtendedEscape = true;
}
- else if (text.charCodeAt(pos) === 125) {
+ else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
+ // Only swallow the following character up if it's a '}'.
pos++;
}
else {
@@ -5911,6 +6675,7 @@ var ts;
}
return utf16EncodeAsString(escapedValue);
}
+ // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
function utf16EncodeAsString(codePoint) {
ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
if (codePoint <= 65535) {
@@ -5920,11 +6685,13 @@ var ts;
var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
return String.fromCharCode(codeUnit1, codeUnit2);
}
+ // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
+ // and return code point value if valid Unicode escape is found. Otherwise return -1.
function peekUnicodeEscape() {
- if (pos + 5 < end && text.charCodeAt(pos + 1) === 117) {
+ if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
var start_1 = pos;
pos += 2;
- var value = scanExactNumberOfHexDigits(4, false);
+ var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
pos = start_1;
return value;
}
@@ -5938,13 +6705,14 @@ var ts;
if (isIdentifierPart(ch, languageVersion)) {
pos++;
}
- else if (ch === 92) {
+ else if (ch === 92 /* backslash */) {
ch = peekUnicodeEscape();
if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
break;
}
result += text.substring(start, pos);
result += String.fromCharCode(ch);
+ // Valid Unicode escape is always six characters
pos += 6;
start = pos;
}
@@ -5956,28 +6724,32 @@ var ts;
return result;
}
function getIdentifierToken() {
+ // Reserved words are between 2 and 11 characters long and start with a lowercase letter
var len = tokenValue.length;
if (len >= 2 && len <= 11) {
var ch = tokenValue.charCodeAt(0);
- if (ch >= 97 && ch <= 122) {
+ if (ch >= 97 /* a */ && ch <= 122 /* z */) {
token = textToToken.get(tokenValue);
if (token !== undefined) {
return token;
}
}
}
- return token = 71;
+ return token = 71 /* Identifier */;
}
function scanBinaryOrOctalDigits(base) {
ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8");
var value = 0;
+ // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
+ // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
var numberOfDigits = 0;
var separatorAllowed = false;
var isPreviousTokenSeparator = false;
while (true) {
var ch = text.charCodeAt(pos);
- if (ch === 95) {
- tokenFlags |= 512;
+ // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
+ if (ch === 95 /* _ */) {
+ tokenFlags |= 512 /* ContainsSeparator */;
if (separatorAllowed) {
separatorAllowed = false;
isPreviousTokenSeparator = true;
@@ -5992,7 +6764,7 @@ var ts;
continue;
}
separatorAllowed = true;
- var valueOfCh = ch - 48;
+ var valueOfCh = ch - 48 /* _0 */;
if (!isDigit(ch) || valueOfCh >= base) {
break;
}
@@ -6001,10 +6773,12 @@ var ts;
numberOfDigits++;
isPreviousTokenSeparator = false;
}
+ // Invalid binaryIntegerLiteral or octalIntegerLiteral
if (numberOfDigits === 0) {
return -1;
}
- if (text.charCodeAt(pos - 1) === 95) {
+ if (text.charCodeAt(pos - 1) === 95 /* _ */) {
+ // Literal ends with underscore - not allowed
error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
return value;
}
@@ -6016,39 +6790,41 @@ var ts;
while (true) {
tokenPos = pos;
if (pos >= end) {
- return token = 1;
+ return token = 1 /* EndOfFileToken */;
}
var ch = text.charCodeAt(pos);
- if (ch === 35 && pos === 0 && isShebangTrivia(text, pos)) {
+ // Special handling for shebang
+ if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
if (skipTrivia) {
continue;
}
else {
- return token = 6;
+ return token = 6 /* ShebangTrivia */;
}
}
switch (ch) {
- case 10:
- case 13:
- tokenFlags |= 1;
+ case 10 /* lineFeed */:
+ case 13 /* carriageReturn */:
+ tokenFlags |= 1 /* PrecedingLineBreak */;
if (skipTrivia) {
pos++;
continue;
}
else {
- if (ch === 13 && pos + 1 < end && text.charCodeAt(pos + 1) === 10) {
+ if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
+ // consume both CR and LF
pos += 2;
}
else {
pos++;
}
- return token = 4;
+ return token = 4 /* NewLineTrivia */;
}
- case 9:
- case 11:
- case 12:
- case 32:
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
if (skipTrivia) {
pos++;
continue;
@@ -6057,89 +6833,90 @@ var ts;
while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
pos++;
}
- return token = 5;
+ return token = 5 /* WhitespaceTrivia */;
}
- case 33:
- if (text.charCodeAt(pos + 1) === 61) {
- if (text.charCodeAt(pos + 2) === 61) {
- return pos += 3, token = 35;
+ case 33 /* exclamation */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */;
}
- return pos += 2, token = 33;
+ return pos += 2, token = 33 /* ExclamationEqualsToken */;
}
pos++;
- return token = 51;
- case 34:
- case 39:
+ return token = 51 /* ExclamationToken */;
+ case 34 /* doubleQuote */:
+ case 39 /* singleQuote */:
tokenValue = scanString();
- return token = 9;
- case 96:
+ return token = 9 /* StringLiteral */;
+ case 96 /* backtick */:
return token = scanTemplateAndSetTokenValue();
- case 37:
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 64;
+ case 37 /* percent */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 64 /* PercentEqualsToken */;
}
pos++;
- return token = 42;
- case 38:
- if (text.charCodeAt(pos + 1) === 38) {
- return pos += 2, token = 53;
+ return token = 42 /* PercentToken */;
+ case 38 /* ampersand */:
+ if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
+ return pos += 2, token = 53 /* AmpersandAmpersandToken */;
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 68;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 68 /* AmpersandEqualsToken */;
}
pos++;
- return token = 48;
- case 40:
+ return token = 48 /* AmpersandToken */;
+ case 40 /* openParen */:
pos++;
- return token = 19;
- case 41:
+ return token = 19 /* OpenParenToken */;
+ case 41 /* closeParen */:
pos++;
- return token = 20;
- case 42:
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 61;
+ return token = 20 /* CloseParenToken */;
+ case 42 /* asterisk */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 61 /* AsteriskEqualsToken */;
}
- if (text.charCodeAt(pos + 1) === 42) {
- if (text.charCodeAt(pos + 2) === 61) {
- return pos += 3, token = 62;
+ if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */;
}
- return pos += 2, token = 40;
+ return pos += 2, token = 40 /* AsteriskAsteriskToken */;
}
pos++;
- return token = 39;
- case 43:
- if (text.charCodeAt(pos + 1) === 43) {
- return pos += 2, token = 43;
+ return token = 39 /* AsteriskToken */;
+ case 43 /* plus */:
+ if (text.charCodeAt(pos + 1) === 43 /* plus */) {
+ return pos += 2, token = 43 /* PlusPlusToken */;
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 59;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 59 /* PlusEqualsToken */;
}
pos++;
- return token = 37;
- case 44:
+ return token = 37 /* PlusToken */;
+ case 44 /* comma */:
pos++;
- return token = 26;
- case 45:
- if (text.charCodeAt(pos + 1) === 45) {
- return pos += 2, token = 44;
+ return token = 26 /* CommaToken */;
+ case 45 /* minus */:
+ if (text.charCodeAt(pos + 1) === 45 /* minus */) {
+ return pos += 2, token = 44 /* MinusMinusToken */;
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 60;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 60 /* MinusEqualsToken */;
}
pos++;
- return token = 38;
- case 46:
+ return token = 38 /* MinusToken */;
+ case 46 /* dot */:
if (isDigit(text.charCodeAt(pos + 1))) {
tokenValue = scanNumber();
- return token = 8;
+ return token = 8 /* NumericLiteral */;
}
- if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) {
- return pos += 3, token = 24;
+ if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
+ return pos += 3, token = 24 /* DotDotDotToken */;
}
pos++;
- return token = 23;
- case 47:
- if (text.charCodeAt(pos + 1) === 47) {
+ return token = 23 /* DotToken */;
+ case 47 /* slash */:
+ // Single-line comment
+ if (text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
while (pos < end) {
if (isLineBreak(text.charCodeAt(pos))) {
@@ -6151,24 +6928,25 @@ var ts;
continue;
}
else {
- return token = 2;
+ return token = 2 /* SingleLineCommentTrivia */;
}
}
- if (text.charCodeAt(pos + 1) === 42) {
+ // Multi-line comment
+ if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
pos += 2;
- if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) !== 47) {
- tokenFlags |= 2;
+ if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
+ tokenFlags |= 2 /* PrecedingJSDocComment */;
}
var commentClosed = false;
while (pos < end) {
var ch_1 = text.charCodeAt(pos);
- if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) {
+ if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
commentClosed = true;
break;
}
if (isLineBreak(ch_1)) {
- tokenFlags |= 1;
+ tokenFlags |= 1 /* PrecedingLineBreak */;
}
pos++;
}
@@ -6180,177 +6958,182 @@ var ts;
}
else {
if (!commentClosed) {
- tokenFlags |= 4;
+ tokenFlags |= 4 /* Unterminated */;
}
- return token = 3;
+ return token = 3 /* MultiLineCommentTrivia */;
}
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 63;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 63 /* SlashEqualsToken */;
}
pos++;
- return token = 41;
- case 48:
- if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) {
+ return token = 41 /* SlashToken */;
+ case 48 /* _0 */:
+ if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
pos += 2;
- var value = scanMinimumNumberOfHexDigits(1, true);
+ var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
if (value < 0) {
error(ts.Diagnostics.Hexadecimal_digit_expected);
value = 0;
}
tokenValue = "" + value;
- tokenFlags |= 64;
- return token = 8;
+ tokenFlags |= 64 /* HexSpecifier */;
+ return token = 8 /* NumericLiteral */;
}
- else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) {
+ else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
pos += 2;
- var value = scanBinaryOrOctalDigits(2);
+ var value = scanBinaryOrOctalDigits(/* base */ 2);
if (value < 0) {
error(ts.Diagnostics.Binary_digit_expected);
value = 0;
}
tokenValue = "" + value;
- tokenFlags |= 128;
- return token = 8;
+ tokenFlags |= 128 /* BinarySpecifier */;
+ return token = 8 /* NumericLiteral */;
}
- else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) {
+ else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
pos += 2;
- var value = scanBinaryOrOctalDigits(8);
+ var value = scanBinaryOrOctalDigits(/* base */ 8);
if (value < 0) {
error(ts.Diagnostics.Octal_digit_expected);
value = 0;
}
tokenValue = "" + value;
- tokenFlags |= 256;
- return token = 8;
+ tokenFlags |= 256 /* OctalSpecifier */;
+ return token = 8 /* NumericLiteral */;
}
+ // Try to parse as an octal
if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
tokenValue = "" + scanOctalDigits();
- tokenFlags |= 32;
- return token = 8;
+ tokenFlags |= 32 /* Octal */;
+ return token = 8 /* NumericLiteral */;
}
- case 49:
- case 50:
- case 51:
- case 52:
- case 53:
- case 54:
- case 55:
- case 56:
- case 57:
+ // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
+ // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
+ // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
+ // falls through
+ case 49 /* _1 */:
+ case 50 /* _2 */:
+ case 51 /* _3 */:
+ case 52 /* _4 */:
+ case 53 /* _5 */:
+ case 54 /* _6 */:
+ case 55 /* _7 */:
+ case 56 /* _8 */:
+ case 57 /* _9 */:
tokenValue = scanNumber();
- return token = 8;
- case 58:
+ return token = 8 /* NumericLiteral */;
+ case 58 /* colon */:
pos++;
- return token = 56;
- case 59:
+ return token = 56 /* ColonToken */;
+ case 59 /* semicolon */:
pos++;
- return token = 25;
- case 60:
+ return token = 25 /* SemicolonToken */;
+ case 60 /* lessThan */:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}
else {
- return token = 7;
+ return token = 7 /* ConflictMarkerTrivia */;
}
}
- if (text.charCodeAt(pos + 1) === 60) {
- if (text.charCodeAt(pos + 2) === 61) {
- return pos += 3, token = 65;
+ if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 65 /* LessThanLessThanEqualsToken */;
}
- return pos += 2, token = 45;
+ return pos += 2, token = 45 /* LessThanLessThanToken */;
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 30;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 30 /* LessThanEqualsToken */;
}
- if (languageVariant === 1 &&
- text.charCodeAt(pos + 1) === 47 &&
- text.charCodeAt(pos + 2) !== 42) {
- return pos += 2, token = 28;
+ if (languageVariant === 1 /* JSX */ &&
+ text.charCodeAt(pos + 1) === 47 /* slash */ &&
+ text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
+ return pos += 2, token = 28 /* LessThanSlashToken */;
}
pos++;
- return token = 27;
- case 61:
+ return token = 27 /* LessThanToken */;
+ case 61 /* equals */:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}
else {
- return token = 7;
+ return token = 7 /* ConflictMarkerTrivia */;
}
}
- if (text.charCodeAt(pos + 1) === 61) {
- if (text.charCodeAt(pos + 2) === 61) {
- return pos += 3, token = 34;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 34 /* EqualsEqualsEqualsToken */;
}
- return pos += 2, token = 32;
+ return pos += 2, token = 32 /* EqualsEqualsToken */;
}
- if (text.charCodeAt(pos + 1) === 62) {
- return pos += 2, token = 36;
+ if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
+ return pos += 2, token = 36 /* EqualsGreaterThanToken */;
}
pos++;
- return token = 58;
- case 62:
+ return token = 58 /* EqualsToken */;
+ case 62 /* greaterThan */:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}
else {
- return token = 7;
+ return token = 7 /* ConflictMarkerTrivia */;
}
}
pos++;
- return token = 29;
- case 63:
+ return token = 29 /* GreaterThanToken */;
+ case 63 /* question */:
pos++;
- return token = 55;
- case 91:
+ return token = 55 /* QuestionToken */;
+ case 91 /* openBracket */:
pos++;
- return token = 21;
- case 93:
+ return token = 21 /* OpenBracketToken */;
+ case 93 /* closeBracket */:
pos++;
- return token = 22;
- case 94:
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 70;
+ return token = 22 /* CloseBracketToken */;
+ case 94 /* caret */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 70 /* CaretEqualsToken */;
}
pos++;
- return token = 50;
- case 123:
+ return token = 50 /* CaretToken */;
+ case 123 /* openBrace */:
pos++;
- return token = 17;
- case 124:
+ return token = 17 /* OpenBraceToken */;
+ case 124 /* bar */:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}
else {
- return token = 7;
+ return token = 7 /* ConflictMarkerTrivia */;
}
}
- if (text.charCodeAt(pos + 1) === 124) {
- return pos += 2, token = 54;
+ if (text.charCodeAt(pos + 1) === 124 /* bar */) {
+ return pos += 2, token = 54 /* BarBarToken */;
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 69;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 69 /* BarEqualsToken */;
}
pos++;
- return token = 49;
- case 125:
+ return token = 49 /* BarToken */;
+ case 125 /* closeBrace */:
pos++;
- return token = 18;
- case 126:
+ return token = 18 /* CloseBraceToken */;
+ case 126 /* tilde */:
pos++;
- return token = 52;
- case 64:
+ return token = 52 /* TildeToken */;
+ case 64 /* at */:
pos++;
- return token = 57;
- case 92:
+ return token = 57 /* AtToken */;
+ case 92 /* backslash */:
var cookedChar = peekUnicodeEscape();
if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
pos += 6;
@@ -6359,14 +7142,14 @@ var ts;
}
error(ts.Diagnostics.Invalid_character);
pos++;
- return token = 0;
+ return token = 0 /* Unknown */;
default:
if (isIdentifierStart(ch, languageVersion)) {
pos++;
while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
pos++;
tokenValue = text.substring(tokenPos, pos);
- if (ch === 92) {
+ if (ch === 92 /* backslash */) {
tokenValue += scanIdentifierParts();
}
return token = getIdentifierToken();
@@ -6376,69 +7159,75 @@ var ts;
continue;
}
else if (isLineBreak(ch)) {
- tokenFlags |= 1;
+ tokenFlags |= 1 /* PrecedingLineBreak */;
pos++;
continue;
}
error(ts.Diagnostics.Invalid_character);
pos++;
- return token = 0;
+ return token = 0 /* Unknown */;
}
}
}
function reScanGreaterToken() {
- if (token === 29) {
- if (text.charCodeAt(pos) === 62) {
- if (text.charCodeAt(pos + 1) === 62) {
- if (text.charCodeAt(pos + 2) === 61) {
- return pos += 3, token = 67;
+ if (token === 29 /* GreaterThanToken */) {
+ if (text.charCodeAt(pos) === 62 /* greaterThan */) {
+ if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
}
- return pos += 2, token = 47;
+ return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */;
}
- if (text.charCodeAt(pos + 1) === 61) {
- return pos += 2, token = 66;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */;
}
pos++;
- return token = 46;
+ return token = 46 /* GreaterThanGreaterThanToken */;
}
- if (text.charCodeAt(pos) === 61) {
+ if (text.charCodeAt(pos) === 61 /* equals */) {
pos++;
- return token = 31;
+ return token = 31 /* GreaterThanEqualsToken */;
}
}
return token;
}
function reScanSlashToken() {
- if (token === 41 || token === 63) {
+ if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) {
var p = tokenPos + 1;
var inEscape = false;
var inCharacterClass = false;
while (true) {
+ // If we reach the end of a file, or hit a newline, then this is an unterminated
+ // regex. Report error and return what we have so far.
if (p >= end) {
- tokenFlags |= 4;
+ tokenFlags |= 4 /* Unterminated */;
error(ts.Diagnostics.Unterminated_regular_expression_literal);
break;
}
var ch = text.charCodeAt(p);
if (isLineBreak(ch)) {
- tokenFlags |= 4;
+ tokenFlags |= 4 /* Unterminated */;
error(ts.Diagnostics.Unterminated_regular_expression_literal);
break;
}
if (inEscape) {
+ // Parsing an escape character;
+ // reset the flag and just advance to the next char.
inEscape = false;
}
- else if (ch === 47 && !inCharacterClass) {
+ else if (ch === 47 /* slash */ && !inCharacterClass) {
+ // A slash within a character class is permissible,
+ // but in general it signals the end of the regexp literal.
p++;
break;
}
- else if (ch === 91) {
+ else if (ch === 91 /* openBracket */) {
inCharacterClass = true;
}
- else if (ch === 92) {
+ else if (ch === 92 /* backslash */) {
inEscape = true;
}
- else if (ch === 93) {
+ else if (ch === 93 /* closeBracket */) {
inCharacterClass = false;
}
p++;
@@ -6448,12 +7237,15 @@ var ts;
}
pos = p;
tokenValue = text.substring(tokenPos, pos);
- token = 12;
+ token = 12 /* RegularExpressionLiteral */;
}
return token;
}
+ /**
+ * Unconditionally back up and scan a template expression portion.
+ */
function reScanTemplateToken() {
- ts.Debug.assert(token === 18, "'reScanTemplateToken' should only be called on a '}'");
+ ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
pos = tokenPos;
return token = scanTemplateAndSetTokenValue();
}
@@ -6464,34 +7256,43 @@ var ts;
function scanJsxToken() {
startPos = tokenPos = pos;
if (pos >= end) {
- return token = 1;
+ return token = 1 /* EndOfFileToken */;
}
var char = text.charCodeAt(pos);
- if (char === 60) {
- if (text.charCodeAt(pos + 1) === 47) {
+ if (char === 60 /* lessThan */) {
+ if (text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
- return token = 28;
+ return token = 28 /* LessThanSlashToken */;
}
pos++;
- return token = 27;
+ return token = 27 /* LessThanToken */;
}
- if (char === 123) {
+ if (char === 123 /* openBrace */) {
pos++;
- return token = 17;
+ return token = 17 /* OpenBraceToken */;
}
+ // First non-whitespace character on this line.
var firstNonWhitespace = 0;
+ // These initial values are special because the first line is:
+ // firstNonWhitespace = 0 to indicate that we want leading whitspace,
while (pos < end) {
char = text.charCodeAt(pos);
- if (char === 123) {
+ if (char === 123 /* openBrace */) {
break;
}
- if (char === 60) {
+ if (char === 60 /* lessThan */) {
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
- return token = 7;
+ return token = 7 /* ConflictMarkerTrivia */;
}
break;
}
+ // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
+ // i.e (- : whitespace)
+ // ----
+ //
becomes
+ //
+ // ----
becomes ----
if (isLineBreak(char) && firstNonWhitespace === 0) {
firstNonWhitespace = -1;
}
@@ -6500,14 +7301,16 @@ var ts;
}
pos++;
}
- return firstNonWhitespace === -1 ? 11 : 10;
+ return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */;
}
+ // Scans a JSX identifier; these differ from normal identifiers in that
+ // they allow dashes
function scanJsxIdentifier() {
if (tokenIsIdentifierOrKeyword(token)) {
var firstCharPosition = pos;
while (pos < end) {
var ch = text.charCodeAt(pos);
- if (ch === 45 || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {
+ if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {
pos++;
}
else {
@@ -6521,70 +7324,71 @@ var ts;
function scanJsxAttributeValue() {
startPos = pos;
switch (text.charCodeAt(pos)) {
- case 34:
- case 39:
- tokenValue = scanString(true);
- return token = 9;
+ case 34 /* doubleQuote */:
+ case 39 /* singleQuote */:
+ tokenValue = scanString(/*jsxAttributeString*/ true);
+ return token = 9 /* StringLiteral */;
default:
+ // If this scans anything other than `{`, it's a parse error.
return scan();
}
}
function scanJSDocToken() {
startPos = tokenPos = pos;
if (pos >= end) {
- return token = 1;
+ return token = 1 /* EndOfFileToken */;
}
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
- case 9:
- case 11:
- case 12:
- case 32:
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
pos++;
}
- return token = 5;
- case 64:
- return token = 57;
- case 10:
- case 13:
- return token = 4;
- case 42:
- return token = 39;
- case 123:
- return token = 17;
- case 125:
- return token = 18;
- case 91:
- return token = 21;
- case 93:
- return token = 22;
- case 60:
- return token = 27;
- case 61:
- return token = 58;
- case 44:
- return token = 26;
- case 46:
- return token = 23;
- case 96:
- while (pos < end && text.charCodeAt(pos) !== 96) {
+ return token = 5 /* WhitespaceTrivia */;
+ case 64 /* at */:
+ return token = 57 /* AtToken */;
+ case 10 /* lineFeed */:
+ case 13 /* carriageReturn */:
+ return token = 4 /* NewLineTrivia */;
+ case 42 /* asterisk */:
+ return token = 39 /* AsteriskToken */;
+ case 123 /* openBrace */:
+ return token = 17 /* OpenBraceToken */;
+ case 125 /* closeBrace */:
+ return token = 18 /* CloseBraceToken */;
+ case 91 /* openBracket */:
+ return token = 21 /* OpenBracketToken */;
+ case 93 /* closeBracket */:
+ return token = 22 /* CloseBracketToken */;
+ case 60 /* lessThan */:
+ return token = 27 /* LessThanToken */;
+ case 61 /* equals */:
+ return token = 58 /* EqualsToken */;
+ case 44 /* comma */:
+ return token = 26 /* CommaToken */;
+ case 46 /* dot */:
+ return token = 23 /* DotToken */;
+ case 96 /* backtick */:
+ while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) {
pos++;
}
tokenValue = text.substring(tokenPos + 1, pos);
pos++;
- return token = 13;
+ return token = 13 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) {
+ if (isIdentifierStart(ch, 6 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
- return token = 71;
+ return token = 71 /* Identifier */;
}
else {
- return token = 0;
+ return token = 0 /* Unknown */;
}
}
function speculationHelper(callback, isLookahead) {
@@ -6595,6 +7399,8 @@ var ts;
var saveTokenValue = tokenValue;
var saveTokenFlags = tokenFlags;
var result = callback();
+ // If our callback returned something 'falsy' or we're just looking ahead,
+ // then unconditionally restore us to where we were.
if (!result || isLookahead) {
pos = savePos;
startPos = saveStartPos;
@@ -6625,10 +7431,10 @@ var ts;
return result;
}
function lookAhead(callback) {
- return speculationHelper(callback, true);
+ return speculationHelper(callback, /*isLookahead*/ true);
}
function tryScan(callback) {
- return speculationHelper(callback, false);
+ return speculationHelper(callback, /*isLookahead*/ false);
}
function getText() {
return text;
@@ -6652,16 +7458,20 @@ var ts;
pos = textPos;
startPos = textPos;
tokenPos = textPos;
- token = 0;
+ token = 0 /* Unknown */;
tokenValue = undefined;
tokenFlags = 0;
}
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
+/** Non-internal stuff goes here */
var ts;
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
+ // TypeScript 1.0 spec (April 2014): 11.2.1
+ // An external module name is "relative" if the first term is "." or "..".
+ // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module.
return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
@@ -6670,6 +7480,7 @@ var ts;
}
ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
ts.emptyArray = [];
ts.resolvingEmptyArray = [];
@@ -6689,6 +7500,7 @@ var ts;
return undefined;
}
ts.getDeclarationOfKind = getDeclarationOfKind;
+ /** Create a new escaped identifier map. */
function createUnderscoreEscapedMap() {
return new ts.MapCtr();
}
@@ -6731,6 +7543,8 @@ var ts;
getColumn: function () { return 0; },
getIndent: function () { return 0; },
isAtStartOfLine: function () { return false; },
+ // Completely ignore indentation for string writers. And map newlines to
+ // a single space.
writeLine: function () { return str += " "; },
increaseIndent: ts.noop,
decreaseIndent: ts.noop,
@@ -6892,23 +7706,31 @@ var ts;
return false;
}
ts.hasChangesInResolutions = hasChangesInResolutions;
+ // Returns true if this node contains a parse error anywhere underneath it.
function containsParseError(node) {
aggregateChildData(node);
- return (node.flags & 131072) !== 0;
+ return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0;
}
ts.containsParseError = containsParseError;
function aggregateChildData(node) {
- if (!(node.flags & 262144)) {
- var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) ||
+ if (!(node.flags & 262144 /* HasAggregatedChildData */)) {
+ // A node is considered to contain a parse error if:
+ // a) the parser explicitly marked that it had an error
+ // b) any of it's children reported that it had an error.
+ var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) ||
ts.forEachChild(node, containsParseError);
+ // If so, mark ourselves accordingly.
if (thisNodeOrAnySubNodesHasError) {
- node.flags |= 131072;
+ node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */;
}
- node.flags |= 262144;
+ // Also mark that we've propagated the child information to this node. This way we can
+ // always consult the bit directly on this node without needing to check its children
+ // again.
+ node.flags |= 262144 /* HasAggregatedChildData */;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 274) {
+ while (node && node.kind !== 274 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -6916,11 +7738,11 @@ var ts;
ts.getSourceFileOfNode = getSourceFileOfNode;
function isStatementWithLocals(node) {
switch (node.kind) {
- case 213:
- case 241:
- case 220:
- case 221:
- case 222:
+ case 213 /* Block */:
+ case 241 /* CaseBlock */:
+ case 220 /* ForStatement */:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
return true;
}
return false;
@@ -6931,6 +7753,7 @@ var ts;
return ts.getLineStarts(sourceFile)[line];
}
ts.getStartPositionOfLine = getStartPositionOfLine;
+ // This is a useful function for debugging purposes.
function nodePosToString(node) {
var file = getSourceFileOfNode(node);
var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
@@ -6943,12 +7766,19 @@ var ts;
var lineIndex = line;
var sourceText = sourceFile.text;
if (lineIndex + 1 === lineStarts.length) {
+ // last line - return EOF
return sourceText.length - 1;
}
else {
+ // current line start
var start = lineStarts[lineIndex];
+ // take the start position of the next line - 1 = it should be some line break
var pos = lineStarts[lineIndex + 1] - 1;
ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
+ // walk backwards skipping line breaks, stop the the beginning of current line.
+ // i.e:
+ //
+ // $ <- end of line for this position should match the start position
while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
pos--;
}
@@ -6956,21 +7786,45 @@ var ts;
}
}
ts.getEndLinePosition = getEndLinePosition;
+ /**
+ * Returns a value indicating whether a name is unique globally or within the current file.
+ * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`.
+ */
function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
}
ts.isFileLevelUniqueName = isFileLevelUniqueName;
+ // Returns true if this node is missing from the actual source code. A 'missing' node is different
+ // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
+ // in the tree), it is definitely missing. However, a node may be defined, but still be
+ // missing. This happens whenever the parser knows it needs to parse something, but can't
+ // get anything in the source code that it expects at that location. For example:
+ //
+ // let a: ;
+ //
+ // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
+ // code). So the parser will attempt to parse out a type, and will create an actual node.
+ // However, this node will be 'missing' in the sense that no actual source-code/tokens are
+ // contained within it.
function nodeIsMissing(node) {
if (node === undefined) {
return true;
}
- return node.pos === node.end && node.pos >= 0 && node.kind !== 1;
+ return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
}
ts.nodeIsMissing = nodeIsMissing;
function nodeIsPresent(node) {
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
+ /**
+ * Appends a range of value to begin of an array, returning the array.
+ *
+ * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array
+ * is created if `value` was appended.
+ * @param from The values to append to the array. If `from` is `undefined`, nothing is
+ * appended. If an element of `from` is `undefined`, that element is not appended.
+ */
function prependStatements(to, from) {
if (from === undefined || from.length === 0)
return to;
@@ -6984,10 +7838,17 @@ var ts;
return to;
}
ts.prependStatements = prependStatements;
+ /**
+ * Determine if the given comment is a triple-slash
+ *
+ * @return true if the comment is a triple-slash comment else false
+ */
function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
- if (text.charCodeAt(commentPos + 1) === 47 &&
+ // 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 (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
commentPos + 2 < commentEnd &&
- text.charCodeAt(commentPos + 2) === 47) {
+ text.charCodeAt(commentPos + 2) === 47 /* slash */) {
var textSubStr = text.substring(commentPos, commentEnd);
return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
@@ -6999,21 +7860,27 @@ var ts;
}
ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
function isPinnedComment(text, start) {
- return text.charCodeAt(start + 1) === 42 &&
- text.charCodeAt(start + 2) === 33;
+ return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(start + 2) === 33 /* exclamation */;
}
ts.isPinnedComment = isPinnedComment;
function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
+ // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
+ // want to skip trivia because this will launch us forward to the next token.
if (nodeIsMissing(node)) {
return node.pos;
}
if (ts.isJSDocNode(node)) {
- return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true);
+ return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
if (includeJsDoc && ts.hasJSDocNodes(node)) {
return getTokenPosOfNode(node.jsDoc[0]);
}
- if (node.kind === 300 && node._children.length > 0) {
+ // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
+ // the syntax list itself considers them as normal trivia. Therefore if we simply skip
+ // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
+ // first child to determine the actual position of its first token.
+ if (node.kind === 300 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -7047,38 +7914,51 @@ var ts;
function getPos(range) {
return range.pos;
}
+ /**
+ * Note: it is expected that the `nodeArray` and the `node` are within the same file.
+ * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
+ */
function indexOfNode(nodeArray, node) {
return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
}
ts.indexOfNode = indexOfNode;
+ /**
+ * Gets flags that control emit behavior of a node.
+ */
function getEmitFlags(node) {
var emitNode = node.emitNode;
return emitNode && emitNode.flags || 0;
}
ts.getEmitFlags = getEmitFlags;
function getLiteralText(node, sourceFile) {
- if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) {
+ // 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 (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) {
return getSourceTextOfNodeFromSourceFile(sourceFile, node);
}
- var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString;
+ var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString;
+ // If we can't reach the original source text, use the canonical form if it's a number,
+ // or a (possibly escaped) quoted form of the original text if it's string-like.
switch (node.kind) {
- case 9:
+ case 9 /* StringLiteral */:
if (node.singleQuote) {
- return "'" + escapeText(node.text, 39) + "'";
+ return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
}
else {
- return '"' + escapeText(node.text, 34) + '"';
+ return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
}
- case 13:
- return "`" + escapeText(node.text, 96) + "`";
- case 14:
- return "`" + escapeText(node.text, 96) + "${";
- case 15:
- return "}" + escapeText(node.text, 96) + "${";
- case 16:
- return "}" + escapeText(node.text, 96) + "`";
- case 8:
- case 12:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ return "`" + escapeText(node.text, 96 /* backtick */) + "`";
+ case 14 /* TemplateHead */:
+ // tslint:disable-next-line no-invalid-template-strings
+ return "`" + escapeText(node.text, 96 /* backtick */) + "${";
+ case 15 /* TemplateMiddle */:
+ // tslint:disable-next-line no-invalid-template-strings
+ return "}" + escapeText(node.text, 96 /* backtick */) + "${";
+ case 16 /* TemplateTail */:
+ return "}" + escapeText(node.text, 96 /* backtick */) + "`";
+ case 8 /* NumericLiteral */:
+ case 12 /* RegularExpressionLiteral */:
return node.text;
}
return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
@@ -7088,59 +7968,74 @@ var ts;
return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
}
ts.getTextOfConstantValue = getTextOfConstantValue;
+ // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__'
function escapeLeadingUnderscores(identifier) {
- return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier);
+ return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
}
ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
+ /**
+ * @deprecated Use `id.escapedText` to get the escaped text of an Identifier.
+ * @param identifier The identifier to escape
+ */
function escapeIdentifier(identifier) {
return identifier;
}
ts.escapeIdentifier = escapeIdentifier;
+ // Make an identifier from an external module name by extracting the string after the last "/" and replacing
+ // all non-alphanumeric characters with underscores
function makeIdentifierFromModuleName(moduleName) {
return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
}
ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
function isBlockOrCatchScoped(declaration) {
- return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 ||
+ return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
isCatchClauseVariableDeclarationOrBindingElement(declaration);
}
ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
var node = getRootDeclaration(declaration);
- return node.kind === 232 && node.parent.kind === 269;
+ return node.kind === 232 /* VariableDeclaration */ && node.parent.kind === 269 /* CatchClause */;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
- return ts.isModuleDeclaration(node) && node.name.kind === 9;
+ return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */;
}
ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
function isNonGlobalAmbientModule(node) {
return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
}
ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
+ /**
+ * An effective module (namespace) declaration is either
+ * 1. An actual declaration: namespace X { ... }
+ * 2. A Javascript declaration, which is:
+ * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
+ */
function isEffectiveModuleDeclaration(node) {
return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
}
ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
+ /** Given a symbol for a module, checks that it is a shorthand ambient module. */
function isShorthandAmbientModuleSymbol(moduleSymbol) {
return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
}
ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
function isShorthandAmbientModule(node) {
- return node && node.kind === 239 && (!node.body);
+ // The only kind of module that can be missing a body is a shorthand ambient module.
+ return node && node.kind === 239 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 274 ||
- node.kind === 239 ||
+ return node.kind === 274 /* SourceFile */ ||
+ node.kind === 239 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
function isGlobalScopeAugmentation(module) {
- return !!(module.flags & 512);
+ return !!(module.flags & 512 /* GlobalAugmentation */);
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
@@ -7148,10 +8043,13 @@ var ts;
}
ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
function isModuleAugmentationExternal(node) {
+ // external module augmentation is a ambient module declaration that is either:
+ // - defined in the top level scope and source file is an external module
+ // - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 274:
+ case 274 /* SourceFile */:
return ts.isExternalModule(node.parent);
- case 240:
+ case 240 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
@@ -7163,22 +8061,24 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 274:
- case 241:
- case 269:
- case 239:
- case 220:
- case 221:
- case 222:
- case 155:
- case 154:
- case 156:
- case 157:
- case 234:
- case 192:
- case 193:
+ case 274 /* SourceFile */:
+ case 241 /* CaseBlock */:
+ case 269 /* CatchClause */:
+ case 239 /* ModuleDeclaration */:
+ case 220 /* ForStatement */:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
+ case 155 /* Constructor */:
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
return true;
- case 213:
+ case 213 /* Block */:
+ // function block is not considered block-scope container
+ // see comment in binder.ts: bind(...), case for SyntaxKind.Block
return !ts.isFunctionLike(parentNode);
}
return false;
@@ -7186,28 +8086,28 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 158:
- case 159:
- case 153:
- case 160:
- case 163:
- case 164:
- case 284:
- case 235:
- case 205:
- case 236:
- case 237:
- case 297:
- case 234:
- case 154:
- case 155:
- case 156:
- case 157:
- case 192:
- case 193:
- case 292:
- case 298:
- case 288:
+ case 158 /* CallSignature */:
+ case 159 /* ConstructSignature */:
+ case 153 /* MethodSignature */:
+ case 160 /* IndexSignature */:
+ case 163 /* FunctionType */:
+ case 164 /* ConstructorType */:
+ case 284 /* JSDocFunctionType */:
+ case 235 /* ClassDeclaration */:
+ case 205 /* ClassExpression */:
+ case 236 /* InterfaceDeclaration */:
+ case 237 /* TypeAliasDeclaration */:
+ case 297 /* JSDocTemplateTag */:
+ case 234 /* FunctionDeclaration */:
+ case 154 /* MethodDeclaration */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
+ case 292 /* JSDocCallbackTag */:
+ case 298 /* JSDocTypedefTag */:
+ case 288 /* JSDocSignature */:
return true;
default:
ts.assertTypeIsNever(node);
@@ -7217,8 +8117,8 @@ var ts;
ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
function isAnyImportSyntax(node) {
switch (node.kind) {
- case 244:
- case 243:
+ case 244 /* ImportDeclaration */:
+ case 243 /* ImportEqualsDeclaration */:
return true;
default:
return false;
@@ -7227,15 +8127,15 @@ var ts;
ts.isAnyImportSyntax = isAnyImportSyntax;
function isLateVisibilityPaintedStatement(node) {
switch (node.kind) {
- case 244:
- case 243:
- case 214:
- case 235:
- case 234:
- case 239:
- case 237:
- case 236:
- case 238:
+ case 244 /* ImportDeclaration */:
+ case 243 /* ImportEqualsDeclaration */:
+ case 214 /* VariableStatement */:
+ case 235 /* ClassDeclaration */:
+ case 234 /* FunctionDeclaration */:
+ case 239 /* ModuleDeclaration */:
+ case 237 /* TypeAliasDeclaration */:
+ case 236 /* InterfaceDeclaration */:
+ case 238 /* EnumDeclaration */:
return true;
default:
return false;
@@ -7246,10 +8146,15 @@ var ts;
return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
}
ts.isAnyImportOrReExport = isAnyImportOrReExport;
+ // Gets the nearest enclosing block scope container that has the provided node
+ // as a descendant, that is not the provided node.
function getEnclosingBlockScopeContainer(node) {
return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
}
ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
+ // Return display name of an identifier
+ // Computed property names will just be emitted as "[]", where is the source
+ // text of the expression in the computed property.
function declarationNameToString(name) {
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}
@@ -7260,13 +8165,13 @@ var ts;
ts.getNameFromIndexInfo = getNameFromIndexInfo;
function getTextOfPropertyName(name) {
switch (name.kind) {
- case 71:
+ case 71 /* Identifier */:
return name.escapedText;
- case 9:
- case 8:
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
return escapeLeadingUnderscores(name.text);
- case 147:
- return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined;
+ case 147 /* ComputedPropertyName */:
+ return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined!
default:
ts.Debug.assertNever(name);
}
@@ -7274,11 +8179,11 @@ var ts;
ts.getTextOfPropertyName = getTextOfPropertyName;
function entityNameToString(name) {
switch (name.kind) {
- case 71:
+ case 71 /* Identifier */:
return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
- case 146:
+ case 146 /* QualifiedName */:
return entityNameToString(name.left) + "." + entityNameToString(name.right);
- case 185:
+ case 185 /* PropertyAccessExpression */:
return entityNameToString(name.expression) + "." + entityNameToString(name.name);
default:
throw ts.Debug.assertNever(name);
@@ -7315,7 +8220,7 @@ var ts;
}
ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
function getSpanOfTokenAtPosition(sourceFile, pos) {
- var scanner = ts.createScanner(sourceFile.languageVersion, true, sourceFile.languageVariant, sourceFile.text, undefined, pos);
+ var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
scanner.scan();
var start = scanner.getTokenPos();
return ts.createTextSpanFromBounds(start, scanner.getTextPos());
@@ -7323,10 +8228,12 @@ var ts;
ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
function getErrorSpanForArrowFunction(sourceFile, node) {
var pos = ts.skipTrivia(sourceFile.text, node.pos);
- if (node.body && node.body.kind === 213) {
+ if (node.body && node.body.kind === 213 /* Block */) {
var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
if (startLine < endLine) {
+ // The arrow function spans multiple lines,
+ // make the error span be the first line, inclusive.
return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
}
}
@@ -7335,40 +8242,46 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 274:
- var pos_1 = ts.skipTrivia(sourceFile.text, 0, false);
+ case 274 /* SourceFile */:
+ var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
+ // file is empty - return span for the beginning of the file
return ts.createTextSpan(0, 0);
}
return getSpanOfTokenAtPosition(sourceFile, pos_1);
- case 232:
- case 182:
- case 235:
- case 205:
- case 236:
- case 239:
- case 238:
- case 273:
- case 234:
- case 192:
- case 154:
- case 156:
- case 157:
- case 237:
- case 152:
- case 151:
+ // This list is a work in progress. Add missing node kinds to improve their error
+ // spans.
+ case 232 /* VariableDeclaration */:
+ case 182 /* BindingElement */:
+ case 235 /* ClassDeclaration */:
+ case 205 /* ClassExpression */:
+ case 236 /* InterfaceDeclaration */:
+ case 239 /* ModuleDeclaration */:
+ case 238 /* EnumDeclaration */:
+ case 273 /* EnumMember */:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 237 /* TypeAliasDeclaration */:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
errorNode = node.name;
break;
- case 193:
+ case 193 /* ArrowFunction */:
return getErrorSpanForArrowFunction(sourceFile, node);
}
if (errorNode === undefined) {
+ // If we don't have a better node, then just set the error on the first token of
+ // construct.
return getSpanOfTokenAtPosition(sourceFile, node.pos);
}
var isMissing = nodeIsMissing(errorNode);
var pos = isMissing
? errorNode.pos
: ts.skipTrivia(sourceFile.text, errorNode.pos);
+ // These asserts should all be satisfied for a properly constructed `errorNode`.
if (isMissing) {
ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
@@ -7385,57 +8298,58 @@ var ts;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
function isJsonSourceFile(file) {
- return file.scriptKind === 6;
+ return file.scriptKind === 6 /* JSON */;
}
ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
- return node.kind === 238 && isConst(node);
+ return node.kind === 238 /* EnumDeclaration */ && isConst(node);
}
ts.isConstEnumDeclaration = isConstEnumDeclaration;
function isConst(node) {
- return !!(ts.getCombinedNodeFlags(node) & 2)
- || !!(ts.getCombinedModifierFlags(node) & 2048);
+ return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */)
+ || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
}
ts.isConst = isConst;
function isLet(node) {
- return !!(ts.getCombinedNodeFlags(node) & 1);
+ return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
}
ts.isLet = isLet;
function isSuperCall(n) {
- return n.kind === 187 && n.expression.kind === 97;
+ return n.kind === 187 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */;
}
ts.isSuperCall = isSuperCall;
function isImportCall(n) {
- return n.kind === 187 && n.expression.kind === 91;
+ return n.kind === 187 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */;
}
ts.isImportCall = isImportCall;
function isLiteralImportTypeNode(n) {
- return n.kind === 179 &&
- n.argument.kind === 178 &&
+ return n.kind === 179 /* ImportType */ &&
+ n.argument.kind === 178 /* LiteralType */ &&
ts.isStringLiteral(n.argument.literal);
}
ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
function isPrologueDirective(node) {
- return node.kind === 216
- && node.expression.kind === 9;
+ return node.kind === 216 /* ExpressionStatement */
+ && node.expression.kind === 9 /* StringLiteral */;
}
ts.isPrologueDirective = isPrologueDirective;
function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
- return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
+ return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
}
ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
function getJSDocCommentRanges(node, text) {
- var commentRanges = (node.kind === 149 ||
- node.kind === 148 ||
- node.kind === 192 ||
- node.kind === 193 ||
- node.kind === 191) ?
+ var commentRanges = (node.kind === 149 /* Parameter */ ||
+ node.kind === 148 /* TypeParameter */ ||
+ node.kind === 192 /* FunctionExpression */ ||
+ node.kind === 193 /* ArrowFunction */ ||
+ node.kind === 191 /* ParenthesizedExpression */) ?
ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
ts.getLeadingCommentRanges(text, node.pos);
+ // True if the comment starts with '/**' but not if it is '/**/'
return ts.filter(commentRanges, function (comment) {
- return text.charCodeAt(comment.pos + 1) === 42 &&
- text.charCodeAt(comment.pos + 2) === 42 &&
- text.charCodeAt(comment.pos + 3) !== 47;
+ return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
});
}
ts.getJSDocCommentRanges = getJSDocCommentRanges;
@@ -7444,75 +8358,87 @@ var ts;
ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
var defaultLibReferenceRegEx = /^(\/\/\/\s*/;
function isPartOfTypeNode(node) {
- if (161 <= node.kind && node.kind <= 179) {
+ if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 179 /* LastTypeNode */) {
return true;
}
switch (node.kind) {
- case 119:
- case 142:
- case 134:
- case 137:
- case 122:
- case 138:
- case 140:
- case 131:
+ case 119 /* AnyKeyword */:
+ case 142 /* UnknownKeyword */:
+ case 134 /* NumberKeyword */:
+ case 137 /* StringKeyword */:
+ case 122 /* BooleanKeyword */:
+ case 138 /* SymbolKeyword */:
+ case 140 /* UndefinedKeyword */:
+ case 131 /* NeverKeyword */:
return true;
- case 105:
- return node.parent.kind !== 196;
- case 207:
+ case 105 /* VoidKeyword */:
+ return node.parent.kind !== 196 /* VoidExpression */;
+ case 207 /* ExpressionWithTypeArguments */:
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
- case 148:
- return node.parent.kind === 177 || node.parent.kind === 172;
- case 71:
- if (node.parent.kind === 146 && node.parent.right === node) {
+ case 148 /* TypeParameter */:
+ return node.parent.kind === 177 /* MappedType */ || node.parent.kind === 172 /* InferType */;
+ // Identifiers and qualified names may be type nodes, depending on their context. Climb
+ // above them to find the lowest container
+ case 71 /* Identifier */:
+ // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
+ if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) {
node = node.parent;
}
- else if (node.parent.kind === 185 && node.parent.name === node) {
+ else if (node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.name === node) {
node = node.parent;
}
- ts.Debug.assert(node.kind === 71 || node.kind === 146 || node.kind === 185, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
- case 146:
- case 185:
- case 99: {
+ // At this point, node is either a qualified name or an identifier
+ ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 185 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
+ // falls through
+ case 146 /* QualifiedName */:
+ case 185 /* PropertyAccessExpression */:
+ case 99 /* ThisKeyword */: {
var parent = node.parent;
- if (parent.kind === 165) {
+ if (parent.kind === 165 /* TypeQuery */) {
return false;
}
- if (parent.kind === 179) {
+ if (parent.kind === 179 /* ImportType */) {
return !parent.isTypeOf;
}
- if (161 <= parent.kind && parent.kind <= 179) {
+ // Do not recursively call isPartOfTypeNode on the parent. In the example:
+ //
+ // let a: A.B.C;
+ //
+ // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
+ // Only C and A.B.C are type nodes.
+ if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 179 /* LastTypeNode */) {
return true;
}
switch (parent.kind) {
- case 207:
+ case 207 /* ExpressionWithTypeArguments */:
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
- case 148:
+ case 148 /* TypeParameter */:
return node === parent.constraint;
- case 152:
- case 151:
- case 149:
- case 232:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
+ case 149 /* Parameter */:
+ case 232 /* VariableDeclaration */:
return node === parent.type;
- case 234:
- case 192:
- case 193:
- case 155:
- case 154:
- case 153:
- case 156:
- case 157:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
+ case 155 /* Constructor */:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
return node === parent.type;
- case 158:
- case 159:
- case 160:
+ case 158 /* CallSignature */:
+ case 159 /* ConstructSignature */:
+ case 160 /* IndexSignature */:
return node === parent.type;
- case 190:
+ case 190 /* TypeAssertionExpression */:
return node === parent.type;
- case 187:
- case 188:
+ case 187 /* CallExpression */:
+ case 188 /* NewExpression */:
return ts.contains(parent.typeArguments, node);
- case 189:
+ case 189 /* TaggedTemplateExpression */:
+ // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
return false;
}
}
@@ -7530,27 +8456,29 @@ var ts;
return false;
}
ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
+ // Warning: This has the same semantics as the forEach family of functions,
+ // in that traversal terminates in the event that 'visitor' supplies a truthy value.
function forEachReturnStatement(body, visitor) {
return traverse(body);
function traverse(node) {
switch (node.kind) {
- case 225:
+ case 225 /* ReturnStatement */:
return visitor(node);
- case 241:
- case 213:
- case 217:
- case 218:
- case 219:
- case 220:
- case 221:
- case 222:
- case 226:
- case 227:
- case 266:
- case 267:
- case 228:
- case 230:
- case 269:
+ case 241 /* CaseBlock */:
+ case 213 /* Block */:
+ case 217 /* IfStatement */:
+ case 218 /* DoStatement */:
+ case 219 /* WhileStatement */:
+ case 220 /* ForStatement */:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
+ case 226 /* WithStatement */:
+ case 227 /* SwitchStatement */:
+ case 266 /* CaseClause */:
+ case 267 /* DefaultClause */:
+ case 228 /* LabeledStatement */:
+ case 230 /* TryStatement */:
+ case 269 /* CatchClause */:
return ts.forEachChild(node, traverse);
}
}
@@ -7560,39 +8488,52 @@ var ts;
return traverse(body);
function traverse(node) {
switch (node.kind) {
- case 203:
+ case 203 /* YieldExpression */:
visitor(node);
var operand = node.expression;
if (operand) {
traverse(operand);
}
return;
- case 238:
- case 236:
- case 239:
- case 237:
- case 235:
- case 205:
+ case 238 /* EnumDeclaration */:
+ case 236 /* InterfaceDeclaration */:
+ case 239 /* ModuleDeclaration */:
+ case 237 /* TypeAliasDeclaration */:
+ case 235 /* ClassDeclaration */:
+ case 205 /* ClassExpression */:
+ // These are not allowed inside a generator now, but eventually they may be allowed
+ // as local types. Regardless, any yield statements contained within them should be
+ // skipped in this traversal.
return;
default:
if (ts.isFunctionLike(node)) {
- if (node.name && node.name.kind === 147) {
+ if (node.name && node.name.kind === 147 /* ComputedPropertyName */) {
+ // Note that we will not include methods/accessors of a class because they would require
+ // first descending into the class. This is by design.
traverse(node.name.expression);
return;
}
}
else if (!isPartOfTypeNode(node)) {
+ // This is the general case, which should include mostly expressions and statements.
+ // Also includes NodeArrays.
ts.forEachChild(node, traverse);
}
}
}
}
ts.forEachYieldExpression = forEachYieldExpression;
+ /**
+ * Gets the most likely element type for a TypeNode. This is not an exhaustive test
+ * as it assumes a rest argument can only be an array type (either T[], or Array).
+ *
+ * @param node The type node.
+ */
function getRestParameterElementType(node) {
- if (node && node.kind === 167) {
+ if (node && node.kind === 167 /* ArrayType */) {
return node.elementType;
}
- else if (node && node.kind === 162) {
+ else if (node && node.kind === 162 /* TypeReference */) {
return ts.singleOrUndefined(node.typeArguments);
}
else {
@@ -7602,12 +8543,12 @@ var ts;
ts.getRestParameterElementType = getRestParameterElementType;
function getMembersOfDeclaration(node) {
switch (node.kind) {
- case 236:
- case 235:
- case 205:
- case 166:
+ case 236 /* InterfaceDeclaration */:
+ case 235 /* ClassDeclaration */:
+ case 205 /* ClassExpression */:
+ case 166 /* TypeLiteral */:
return node.members;
- case 184:
+ case 184 /* ObjectLiteralExpression */:
return node.properties;
}
}
@@ -7615,14 +8556,14 @@ var ts;
function isVariableLike(node) {
if (node) {
switch (node.kind) {
- case 182:
- case 273:
- case 149:
- case 270:
- case 152:
- case 151:
- case 271:
- case 232:
+ case 182 /* BindingElement */:
+ case 273 /* EnumMember */:
+ case 149 /* Parameter */:
+ case 270 /* PropertyAssignment */:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
+ case 271 /* ShorthandPropertyAssignment */:
+ case 232 /* VariableDeclaration */:
return true;
}
}
@@ -7634,8 +8575,8 @@ var ts;
}
ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
function isVariableDeclarationInVariableStatement(node) {
- return node.parent.kind === 233
- && node.parent.parent.kind === 214;
+ return node.parent.kind === 233 /* VariableDeclarationList */
+ && node.parent.parent.kind === 214 /* VariableStatement */;
}
ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
function isValidESSymbolDeclaration(node) {
@@ -7646,13 +8587,13 @@ var ts;
ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
function introducesArgumentsExoticObject(node) {
switch (node.kind) {
- case 154:
- case 153:
- case 155:
- case 156:
- case 157:
- case 234:
- case 192:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
return true;
}
return false;
@@ -7663,7 +8604,7 @@ var ts;
if (beforeUnwrapLabelCallback) {
beforeUnwrapLabelCallback(node);
}
- if (node.statement.kind !== 228) {
+ if (node.statement.kind !== 228 /* LabeledStatement */) {
return node.statement;
}
node = node.statement;
@@ -7671,30 +8612,30 @@ var ts;
}
ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
function isFunctionBlock(node) {
- return node && node.kind === 213 && ts.isFunctionLike(node.parent);
+ return node && node.kind === 213 /* Block */ && ts.isFunctionLike(node.parent);
}
ts.isFunctionBlock = isFunctionBlock;
function isObjectLiteralMethod(node) {
- return node && node.kind === 154 && node.parent.kind === 184;
+ return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 184 /* ObjectLiteralExpression */;
}
ts.isObjectLiteralMethod = isObjectLiteralMethod;
function isObjectLiteralOrClassExpressionMethod(node) {
- return node.kind === 154 &&
- (node.parent.kind === 184 ||
- node.parent.kind === 205);
+ return node.kind === 154 /* MethodDeclaration */ &&
+ (node.parent.kind === 184 /* ObjectLiteralExpression */ ||
+ node.parent.kind === 205 /* ClassExpression */);
}
ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
function isIdentifierTypePredicate(predicate) {
- return predicate && predicate.kind === 1;
+ return predicate && predicate.kind === 1 /* Identifier */;
}
ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
function isThisTypePredicate(predicate) {
- return predicate && predicate.kind === 0;
+ return predicate && predicate.kind === 0 /* This */;
}
ts.isThisTypePredicate = isThisTypePredicate;
function getPropertyAssignment(objectLiteral, key, key2) {
return objectLiteral.properties.filter(function (property) {
- if (property.kind === 270) {
+ if (property.kind === 270 /* PropertyAssignment */) {
var propName = getTextOfPropertyName(property.name);
return key === propName || (!!key2 && key2 === propName);
}
@@ -7731,64 +8672,87 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 274);
+ ts.Debug.assert(node.kind !== 274 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
- return ts.Debug.fail();
+ return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
}
switch (node.kind) {
- case 147:
+ case 147 /* ComputedPropertyName */:
+ // If the grandparent node is an object literal (as opposed to a class),
+ // then the computed property is not a 'this' container.
+ // A computed property name in a class needs to be a this container
+ // so that we can error on it.
if (ts.isClassLike(node.parent.parent)) {
return node;
}
+ // If this is a computed property, then the parent should not
+ // make it a this container. The parent might be a property
+ // in an object literal, like a method or accessor. But in order for
+ // such a parent to be a this container, the reference must be in
+ // the *body* of the container.
node = node.parent;
break;
- case 150:
- if (node.parent.kind === 149 && ts.isClassElement(node.parent.parent)) {
+ case 150 /* Decorator */:
+ // Decorators are always applied outside of the body of a class or method.
+ if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
+ // If the decorator's parent is a Parameter, we resolve the this container from
+ // the grandparent class declaration.
node = node.parent.parent;
}
else if (ts.isClassElement(node.parent)) {
+ // If the decorator's parent is a class element, we resolve the 'this' container
+ // from the parent class declaration.
node = node.parent;
}
break;
- case 193:
+ case 193 /* ArrowFunction */:
if (!includeArrowFunctions) {
continue;
}
- case 234:
- case 192:
- case 239:
- case 152:
- case 151:
- case 154:
- case 153:
- case 155:
- case 156:
- case 157:
- case 158:
- case 159:
- case 160:
- case 238:
- case 274:
+ // falls through
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 239 /* ModuleDeclaration */:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 158 /* CallSignature */:
+ case 159 /* ConstructSignature */:
+ case 160 /* IndexSignature */:
+ case 238 /* EnumDeclaration */:
+ case 274 /* SourceFile */:
return node;
}
}
}
ts.getThisContainer = getThisContainer;
function getNewTargetContainer(node) {
- var container = getThisContainer(node, false);
+ var container = getThisContainer(node, /*includeArrowFunctions*/ false);
if (container) {
switch (container.kind) {
- case 155:
- case 234:
- case 192:
+ case 155 /* Constructor */:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
return container;
}
}
return undefined;
}
ts.getNewTargetContainer = getNewTargetContainer;
+ /**
+ * Given an super call/property node, returns the closest node where
+ * - a super call/property access is legal in the node and not legal in the parent node the node.
+ * i.e. super call is legal in constructor but not legal in the class body.
+ * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
+ * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
+ * i.e. super property access is illegal in function declaration but can be legal in the statement list
+ */
function getSuperContainer(node, stopOnFunctions) {
while (true) {
node = node.parent;
@@ -7796,28 +8760,34 @@ var ts;
return node;
}
switch (node.kind) {
- case 147:
+ case 147 /* ComputedPropertyName */:
node = node.parent;
break;
- case 234:
- case 192:
- case 193:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
if (!stopOnFunctions) {
continue;
}
- case 152:
- case 151:
- case 154:
- case 153:
- case 155:
- case 156:
- case 157:
+ // falls through
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
return node;
- case 150:
- if (node.parent.kind === 149 && ts.isClassElement(node.parent.parent)) {
+ case 150 /* Decorator */:
+ // Decorators are always applied outside of the body of a class or method.
+ if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
+ // If the decorator's parent is a Parameter, we resolve the this container from
+ // the grandparent class declaration.
node = node.parent.parent;
}
else if (ts.isClassElement(node.parent)) {
+ // If the decorator's parent is a class element, we resolve the 'this' container
+ // from the parent class declaration.
node = node.parent;
}
break;
@@ -7826,41 +8796,47 @@ var ts;
}
ts.getSuperContainer = getSuperContainer;
function getImmediatelyInvokedFunctionExpression(func) {
- if (func.kind === 192 || func.kind === 193) {
+ if (func.kind === 192 /* FunctionExpression */ || func.kind === 193 /* ArrowFunction */) {
var prev = func;
var parent = func.parent;
- while (parent.kind === 191) {
+ while (parent.kind === 191 /* ParenthesizedExpression */) {
prev = parent;
parent = parent.parent;
}
- if (parent.kind === 187 && parent.expression === prev) {
+ if (parent.kind === 187 /* CallExpression */ && parent.expression === prev) {
return parent;
}
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ /**
+ * Determines whether a node is a property or element access expression for `super`.
+ */
function isSuperProperty(node) {
var kind = node.kind;
- return (kind === 185 || kind === 186)
- && node.expression.kind === 97;
+ return (kind === 185 /* PropertyAccessExpression */ || kind === 186 /* ElementAccessExpression */)
+ && node.expression.kind === 97 /* SuperKeyword */;
}
ts.isSuperProperty = isSuperProperty;
+ /**
+ * Determines whether a node is a property or element access expression for `this`.
+ */
function isThisProperty(node) {
var kind = node.kind;
- return (kind === 185 || kind === 186)
- && node.expression.kind === 99;
+ return (kind === 185 /* PropertyAccessExpression */ || kind === 186 /* ElementAccessExpression */)
+ && node.expression.kind === 99 /* ThisKeyword */;
}
ts.isThisProperty = isThisProperty;
function getEntityNameFromTypeNode(node) {
switch (node.kind) {
- case 162:
+ case 162 /* TypeReference */:
return node.typeName;
- case 207:
+ case 207 /* ExpressionWithTypeArguments */:
return isEntityNameExpression(node.expression)
? node.expression
: undefined;
- case 71:
- case 146:
+ case 71 /* Identifier */:
+ case 146 /* QualifiedName */:
return node;
}
return undefined;
@@ -7868,10 +8844,10 @@ var ts;
ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
function getInvokedExpression(node) {
switch (node.kind) {
- case 189:
+ case 189 /* TaggedTemplateExpression */:
return node.tag;
- case 257:
- case 256:
+ case 257 /* JsxOpeningElement */:
+ case 256 /* JsxSelfClosingElement */:
return node.tagName;
default:
return node.expression;
@@ -7880,41 +8856,45 @@ var ts;
ts.getInvokedExpression = getInvokedExpression;
function nodeCanBeDecorated(node, parent, grandparent) {
switch (node.kind) {
- case 235:
+ case 235 /* ClassDeclaration */:
+ // classes are valid targets
return true;
- case 152:
- return parent.kind === 235;
- case 156:
- case 157:
- case 154:
+ case 152 /* PropertyDeclaration */:
+ // property declarations are valid if their parent is a class declaration.
+ return parent.kind === 235 /* ClassDeclaration */;
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 154 /* MethodDeclaration */:
+ // if this method has a body and its parent is a class declaration, this is a valid target.
return node.body !== undefined
- && parent.kind === 235;
- case 149:
+ && parent.kind === 235 /* ClassDeclaration */;
+ case 149 /* Parameter */:
+ // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
return parent.body !== undefined
- && (parent.kind === 155
- || parent.kind === 154
- || parent.kind === 157)
- && grandparent.kind === 235;
+ && (parent.kind === 155 /* Constructor */
+ || parent.kind === 154 /* MethodDeclaration */
+ || parent.kind === 157 /* SetAccessor */)
+ && grandparent.kind === 235 /* ClassDeclaration */;
}
return false;
}
ts.nodeCanBeDecorated = nodeCanBeDecorated;
function nodeIsDecorated(node, parent, grandparent) {
return node.decorators !== undefined
- && nodeCanBeDecorated(node, parent, grandparent);
+ && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
}
ts.nodeIsDecorated = nodeIsDecorated;
function nodeOrChildIsDecorated(node, parent, grandparent) {
- return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent);
+ return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
}
ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
function childIsDecorated(node, parent) {
switch (node.kind) {
- case 235:
- return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); });
- case 154:
- case 157:
- return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); });
+ case 235 /* ClassDeclaration */:
+ return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
+ case 154 /* MethodDeclaration */:
+ case 157 /* SetAccessor */:
+ return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
default:
return false;
}
@@ -7922,9 +8902,9 @@ var ts;
ts.childIsDecorated = childIsDecorated;
function isJSXTagName(node) {
var parent = node.parent;
- if (parent.kind === 257 ||
- parent.kind === 256 ||
- parent.kind === 258) {
+ if (parent.kind === 257 /* JsxOpeningElement */ ||
+ parent.kind === 256 /* JsxSelfClosingElement */ ||
+ parent.kind === 258 /* JsxClosingElement */) {
return parent.tagName === node;
}
return false;
@@ -7932,55 +8912,56 @@ var ts;
ts.isJSXTagName = isJSXTagName;
function isExpressionNode(node) {
switch (node.kind) {
- case 97:
- case 95:
- case 101:
- case 86:
- case 12:
- case 183:
- case 184:
- case 185:
- case 186:
- case 187:
- case 188:
- case 189:
- case 208:
- case 190:
- case 209:
- case 191:
- case 192:
- case 205:
- case 193:
- case 196:
- case 194:
- case 195:
- case 198:
- case 199:
- case 200:
- case 201:
- case 204:
- case 202:
- case 13:
- case 206:
- case 255:
- case 256:
- case 259:
- case 203:
- case 197:
- case 210:
+ case 97 /* SuperKeyword */:
+ case 95 /* NullKeyword */:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 12 /* RegularExpressionLiteral */:
+ case 183 /* ArrayLiteralExpression */:
+ case 184 /* ObjectLiteralExpression */:
+ case 185 /* PropertyAccessExpression */:
+ case 186 /* ElementAccessExpression */:
+ case 187 /* CallExpression */:
+ case 188 /* NewExpression */:
+ case 189 /* TaggedTemplateExpression */:
+ case 208 /* AsExpression */:
+ case 190 /* TypeAssertionExpression */:
+ case 209 /* NonNullExpression */:
+ case 191 /* ParenthesizedExpression */:
+ case 192 /* FunctionExpression */:
+ case 205 /* ClassExpression */:
+ case 193 /* ArrowFunction */:
+ case 196 /* VoidExpression */:
+ case 194 /* DeleteExpression */:
+ case 195 /* TypeOfExpression */:
+ case 198 /* PrefixUnaryExpression */:
+ case 199 /* PostfixUnaryExpression */:
+ case 200 /* BinaryExpression */:
+ case 201 /* ConditionalExpression */:
+ case 204 /* SpreadElement */:
+ case 202 /* TemplateExpression */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ case 206 /* OmittedExpression */:
+ case 255 /* JsxElement */:
+ case 256 /* JsxSelfClosingElement */:
+ case 259 /* JsxFragment */:
+ case 203 /* YieldExpression */:
+ case 197 /* AwaitExpression */:
+ case 210 /* MetaProperty */:
return true;
- case 146:
- while (node.parent.kind === 146) {
+ case 146 /* QualifiedName */:
+ while (node.parent.kind === 146 /* QualifiedName */) {
node = node.parent;
}
- return node.parent.kind === 165 || isJSXTagName(node);
- case 71:
- if (node.parent.kind === 165 || isJSXTagName(node)) {
+ return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node);
+ case 71 /* Identifier */:
+ if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) {
return true;
}
- case 8:
- case 9:
- case 99:
+ // falls through
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ case 99 /* ThisKeyword */:
return isInExpressionContext(node);
default:
return false;
@@ -7990,47 +8971,47 @@ var ts;
function isInExpressionContext(node) {
var parent = node.parent;
switch (parent.kind) {
- case 232:
- case 149:
- case 152:
- case 151:
- case 273:
- case 270:
- case 182:
+ case 232 /* VariableDeclaration */:
+ case 149 /* Parameter */:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
+ case 273 /* EnumMember */:
+ case 270 /* PropertyAssignment */:
+ case 182 /* BindingElement */:
return parent.initializer === node;
- case 216:
- case 217:
- case 218:
- case 219:
- case 225:
- case 226:
- case 227:
- case 266:
- case 229:
+ case 216 /* ExpressionStatement */:
+ case 217 /* IfStatement */:
+ case 218 /* DoStatement */:
+ case 219 /* WhileStatement */:
+ case 225 /* ReturnStatement */:
+ case 226 /* WithStatement */:
+ case 227 /* SwitchStatement */:
+ case 266 /* CaseClause */:
+ case 229 /* ThrowStatement */:
return parent.expression === node;
- case 220:
+ case 220 /* ForStatement */:
var forStatement = parent;
- return (forStatement.initializer === node && forStatement.initializer.kind !== 233) ||
+ return (forStatement.initializer === node && forStatement.initializer.kind !== 233 /* VariableDeclarationList */) ||
forStatement.condition === node ||
forStatement.incrementor === node;
- case 221:
- case 222:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
var forInStatement = parent;
- return (forInStatement.initializer === node && forInStatement.initializer.kind !== 233) ||
+ return (forInStatement.initializer === node && forInStatement.initializer.kind !== 233 /* VariableDeclarationList */) ||
forInStatement.expression === node;
- case 190:
- case 208:
+ case 190 /* TypeAssertionExpression */:
+ case 208 /* AsExpression */:
return node === parent.expression;
- case 211:
+ case 211 /* TemplateSpan */:
return node === parent.expression;
- case 147:
+ case 147 /* ComputedPropertyName */:
return node === parent.expression;
- case 150:
- case 265:
- case 264:
- case 272:
+ case 150 /* Decorator */:
+ case 265 /* JsxExpression */:
+ case 264 /* JsxSpreadAttribute */:
+ case 272 /* SpreadAssignment */:
return true;
- case 207:
+ case 207 /* ExpressionWithTypeArguments */:
return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
default:
return isExpressionNode(parent);
@@ -8038,7 +9019,7 @@ var ts;
}
ts.isInExpressionContext = isInExpressionContext;
function isExternalModuleImportEqualsDeclaration(node) {
- return node.kind === 243 && node.moduleReference.kind === 254;
+ return node.kind === 243 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 254 /* ExternalModuleReference */;
}
ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
function getExternalModuleImportEqualsDeclarationExpression(node) {
@@ -8047,7 +9028,7 @@ var ts;
}
ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
function isInternalModuleImportEqualsDeclaration(node) {
- return node.kind === 243 && node.moduleReference.kind !== 254;
+ return node.kind === 243 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 254 /* ExternalModuleReference */;
}
ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
function isSourceFileJavaScript(file) {
@@ -8059,15 +9040,15 @@ var ts;
}
ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript;
function isInJavaScriptFile(node) {
- return !!node && !!(node.flags & 65536);
+ return !!node && !!(node.flags & 65536 /* JavaScriptFile */);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
function isInJsonFile(node) {
- return !!node && !!(node.flags & 16777216);
+ return !!node && !!(node.flags & 16777216 /* JsonFile */);
}
ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
- return !!node && !!(node.flags & 2097152);
+ return !!node && !!(node.flags & 2097152 /* JSDoc */);
}
ts.isInJSDoc = isInJSDoc;
function isJSDocIndexSignature(node) {
@@ -8075,15 +9056,15 @@ var ts;
ts.isIdentifier(node.typeName) &&
node.typeName.escapedText === "Object" &&
node.typeArguments && node.typeArguments.length === 2 &&
- (node.typeArguments[0].kind === 137 || node.typeArguments[0].kind === 134);
+ (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */);
}
ts.isJSDocIndexSignature = isJSDocIndexSignature;
function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) {
- if (callExpression.kind !== 187) {
+ if (callExpression.kind !== 187 /* CallExpression */) {
return false;
}
var _a = callExpression, expression = _a.expression, args = _a.arguments;
- if (expression.kind !== 71 || expression.escapedText !== "require") {
+ if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") {
return false;
}
if (args.length !== 1) {
@@ -8094,11 +9075,11 @@ var ts;
}
ts.isRequireCall = isRequireCall;
function isSingleOrDoubleQuote(charCode) {
- return charCode === 39 || charCode === 34;
+ return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
}
ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
function isStringDoubleQuoted(str, sourceFile) {
- return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34;
+ return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
}
ts.isStringDoubleQuoted = isStringDoubleQuoted;
function getDeclarationOfJSInitializer(node) {
@@ -8111,16 +9092,16 @@ var ts;
name = node.parent.name;
decl = node.parent;
}
- else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 && node.parent.right === node) {
+ else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) {
name = node.parent.left;
decl = name;
}
- else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54) {
+ else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) {
if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) {
name = node.parent.parent.name;
decl = node.parent.parent;
}
- else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 && node.parent.parent.right === node.parent) {
+ else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) {
name = node.parent.parent.left;
decl = name;
}
@@ -8134,36 +9115,52 @@ var ts;
return decl;
}
ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer;
+ /** Get the initializer, taking into account defaulted Javascript initializers */
function getEffectiveInitializer(node) {
if (isInJavaScriptFile(node) && node.initializer &&
- ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 &&
+ ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ &&
node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
return node.initializer.right;
}
return node.initializer;
}
ts.getEffectiveInitializer = getEffectiveInitializer;
+ /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */
function getDeclaredJavascriptInitializer(node) {
var init = getEffectiveInitializer(node);
return init && getJavascriptInitializer(init, isPrototypeAccess(node.name));
}
ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer;
+ /**
+ * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer).
+ * We treat the right hand side of assignments with container-like initalizers as declarations.
+ */
function getAssignedJavascriptInitializer(node) {
- if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) {
+ if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) {
var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) ||
getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
}
}
ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer;
+ /**
+ * Recognized Javascript container-like initializers are:
+ * 1. (function() {})() -- IIFEs
+ * 2. function() { } -- Function expressions
+ * 3. class { } -- Class expressions
+ * 4. {} -- Empty object literals
+ * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
+ *
+ * This function returns the provided initializer, or undefined if it is not valid.
+ */
function getJavascriptInitializer(initializer, isPrototypeAssignment) {
if (ts.isCallExpression(initializer)) {
var e = skipParentheses(initializer.expression);
- return e.kind === 192 || e.kind === 193 ? initializer : undefined;
+ return e.kind === 192 /* FunctionExpression */ || e.kind === 193 /* ArrowFunction */ ? initializer : undefined;
}
- if (initializer.kind === 192 ||
- initializer.kind === 205 ||
- initializer.kind === 193) {
+ if (initializer.kind === 192 /* FunctionExpression */ ||
+ initializer.kind === 205 /* ClassExpression */ ||
+ initializer.kind === 193 /* ArrowFunction */) {
return initializer;
}
if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
@@ -8171,23 +9168,32 @@ var ts;
}
}
ts.getJavascriptInitializer = getJavascriptInitializer;
+ /**
+ * A defaulted Javascript initializer matches the pattern
+ * `Lhs = Lhs || JavascriptInitializer`
+ * or `var Lhs = Lhs || JavascriptInitializer`
+ *
+ * The second Lhs is required to be the same as the first except that it may be prefixed with
+ * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
+ */
function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) {
- var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment);
+ var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment);
if (e && isSameEntityName(name, initializer.left)) {
return e;
}
}
function isDefaultedJavascriptInitializer(node) {
var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
- ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 ? node.parent.left :
+ ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left :
undefined;
return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
}
ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer;
+ /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */
function getOuterNameOfJsInitializer(node) {
if (ts.isBinaryExpression(node.parent)) {
- var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
- if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) {
+ var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
+ if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
return parent.left;
}
}
@@ -8196,12 +9202,21 @@ var ts;
}
}
ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer;
+ /**
+ * Is the 'declared' name the same as the one in the initializer?
+ * @return true for identical entity names, as well as ones where the initializer is prefixed with
+ * 'window', 'self' or 'global'. For example:
+ *
+ * var my = my || {}
+ * var min = window.min || {}
+ * my.app = self.my.app || class { }
+ */
function isSameEntityName(name, initializer) {
if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) {
return name.escapedText === initializer.escapedText;
}
if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) {
- return (initializer.expression.kind === 99 ||
+ return (initializer.expression.kind === 99 /* ThisKeyword */ ||
ts.isIdentifier(initializer.expression) &&
(initializer.expression.escapedText === "window" ||
initializer.expression.escapedText === "self" ||
@@ -8214,7 +9229,7 @@ var ts;
return false;
}
function getRightMostAssignedExpression(node) {
- while (isAssignmentExpression(node, true)) {
+ while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) {
node = node.right;
}
return node;
@@ -8228,25 +9243,30 @@ var ts;
return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports";
}
ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression;
+ /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
+ /// assignments we treat as special in the binder
function getSpecialPropertyAssignmentKind(expr) {
if (!isInJavaScriptFile(expr) ||
- expr.operatorToken.kind !== 58 ||
+ expr.operatorToken.kind !== 58 /* EqualsToken */ ||
!ts.isPropertyAccessExpression(expr.left)) {
- return 0;
+ return 0 /* None */;
}
var lhs = expr.left;
- if (lhs.expression.kind === 99) {
- return 4;
+ if (lhs.expression.kind === 99 /* ThisKeyword */) {
+ return 4 /* ThisProperty */;
}
else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") {
- return 2;
+ // module.exports = expr
+ return 2 /* ModuleExports */;
}
else if (isEntityNameExpression(lhs.expression)) {
if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
- return 6;
+ // F.prototype = { ... }
+ return 6 /* Prototype */;
}
else if (isPrototypeAccess(lhs.expression)) {
- return 3;
+ // F.G....prototype.x = expr
+ return 3 /* PrototypeProperty */;
}
var nextToLast = lhs;
while (ts.isPropertyAccessExpression(nextToLast.expression)) {
@@ -8256,11 +9276,13 @@ var ts;
var id = nextToLast.expression;
if (id.escapedText === "exports" ||
id.escapedText === "module" && nextToLast.name.escapedText === "exports") {
- return 1;
+ // exports.name = expr OR module.exports.name = expr
+ return 1 /* ExportsProperty */;
}
- return 5;
+ // F.G...x = expr
+ return 5 /* Property */;
}
- return 0;
+ return 0 /* None */;
}
ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind;
function getInitializerOfBinaryExpression(expr) {
@@ -8271,12 +9293,12 @@ var ts;
}
ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
function isPrototypePropertyAssignment(node) {
- return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3;
+ return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */;
}
ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
function isSpecialPropertyDeclaration(expr) {
return isInJavaScriptFile(expr) &&
- expr.parent && expr.parent.kind === 216 &&
+ expr.parent && expr.parent.kind === 216 /* ExpressionStatement */ &&
!!ts.getJSDocTypeTag(expr.parent);
}
ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
@@ -8286,14 +9308,14 @@ var ts;
ts.importFromModuleSpecifier = importFromModuleSpecifier;
function tryGetImportFromModuleSpecifier(node) {
switch (node.parent.kind) {
- case 244:
- case 250:
+ case 244 /* ImportDeclaration */:
+ case 250 /* ExportDeclaration */:
return node.parent;
- case 254:
+ case 254 /* ExternalModuleReference */:
return node.parent.parent;
- case 187:
+ case 187 /* CallExpression */:
return node.parent;
- case 178:
+ case 178 /* LiteralType */:
ts.Debug.assert(ts.isStringLiteral(node));
return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
default:
@@ -8303,12 +9325,12 @@ var ts;
ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
function getExternalModuleName(node) {
switch (node.kind) {
- case 244:
- case 250:
+ case 244 /* ImportDeclaration */:
+ case 250 /* ExportDeclaration */:
return node.moduleSpecifier;
- case 243:
- return node.moduleReference.kind === 254 ? node.moduleReference.expression : undefined;
- case 179:
+ case 243 /* ImportEqualsDeclaration */:
+ return node.moduleReference.kind === 254 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
+ case 179 /* ImportType */:
return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
default:
return ts.Debug.assertNever(node);
@@ -8317,11 +9339,11 @@ var ts;
ts.getExternalModuleName = getExternalModuleName;
function getNamespaceDeclarationNode(node) {
switch (node.kind) {
- case 244:
+ case 244 /* ImportDeclaration */:
return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
- case 243:
+ case 243 /* ImportEqualsDeclaration */:
return node;
- case 250:
+ case 250 /* ExportDeclaration */:
return undefined;
default:
return ts.Debug.assertNever(node);
@@ -8329,19 +9351,19 @@ var ts;
}
ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
function isDefaultImport(node) {
- return node.kind === 244 && !!node.importClause && !!node.importClause.name;
+ return node.kind === 244 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
}
ts.isDefaultImport = isDefaultImport;
function hasQuestionToken(node) {
if (node) {
switch (node.kind) {
- case 149:
- case 154:
- case 153:
- case 271:
- case 270:
- case 152:
- case 151:
+ case 149 /* Parameter */:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 271 /* ShorthandPropertyAssignment */:
+ case 270 /* PropertyAssignment */:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
return node.questionToken !== undefined;
}
}
@@ -8349,14 +9371,14 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 284 &&
+ return node.kind === 284 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 298 || node.kind === 292;
+ return node.kind === 298 /* JSDocTypedefTag */ || node.kind === 292 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -8366,27 +9388,27 @@ var ts;
function getSourceOfAssignment(node) {
return ts.isExpressionStatement(node) &&
node.expression && ts.isBinaryExpression(node.expression) &&
- node.expression.operatorToken.kind === 58
+ node.expression.operatorToken.kind === 58 /* EqualsToken */
? node.expression.right
: undefined;
}
function getSourceOfDefaultedAssignment(node) {
return ts.isExpressionStatement(node) &&
ts.isBinaryExpression(node.expression) &&
- getSpecialPropertyAssignmentKind(node.expression) !== 0 &&
+ getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ &&
ts.isBinaryExpression(node.expression.right) &&
- node.expression.right.operatorToken.kind === 54
+ node.expression.right.operatorToken.kind === 54 /* BarBarToken */
? node.expression.right.right
: undefined;
}
function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
switch (node.kind) {
- case 214:
+ case 214 /* VariableStatement */:
var v = getSingleVariableOfVariableStatement(node);
return v && v.initializer;
- case 152:
+ case 152 /* PropertyDeclaration */:
return node.initializer;
- case 270:
+ case 270 /* PropertyAssignment */:
return node.initializer;
}
}
@@ -8396,7 +9418,7 @@ var ts;
function getNestedModuleDeclaration(node) {
return ts.isModuleDeclaration(node) &&
node.body &&
- node.body.kind === 239
+ node.body.kind === 239 /* ModuleDeclaration */
? node.body
: undefined;
}
@@ -8408,9 +9430,15 @@ var ts;
var parent = node.parent;
if (!parent)
return;
- if (parent.kind === 270 || parent.kind === 152 || getNestedModuleDeclaration(parent)) {
+ if (parent.kind === 270 /* PropertyAssignment */ || parent.kind === 152 /* PropertyDeclaration */ || getNestedModuleDeclaration(parent)) {
getJSDocCommentsAndTagsWorker(parent);
}
+ // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
+ // /**
+ // * @param {number} name
+ // * @returns {number}
+ // */
+ // var x = function(name) { return name.length; }
if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) {
getJSDocCommentsAndTagsWorker(parent.parent);
}
@@ -8420,9 +9448,9 @@ var ts;
getSourceOfDefaultedAssignment(parent.parent.parent))) {
getJSDocCommentsAndTagsWorker(parent.parent.parent);
}
- if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 ||
- ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 ||
- node.kind === 185 && node.parent && node.parent.kind === 216) {
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ ||
+ ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ ||
+ node.kind === 185 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 216 /* ExpressionStatement */) {
if (ts.isBinaryExpression(parent)) {
getJSDocCommentsAndTagsWorker(parent.parent);
}
@@ -8430,7 +9458,8 @@ var ts;
getJSDocCommentsAndTagsWorker(parent);
}
}
- if (node.kind === 149) {
+ // Pull parameter comments from declaring function as well
+ if (node.kind === 149 /* Parameter */) {
result = ts.addRange(result, ts.getJSDocParameterTags(node));
}
if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) {
@@ -8442,6 +9471,7 @@ var ts;
}
}
ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
+ /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
function getParameterSymbolFromJSDoc(node) {
if (node.symbol) {
return node.symbol;
@@ -8454,7 +9484,7 @@ var ts;
if (!decl) {
return undefined;
}
- var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 && p.name.escapedText === name; });
+ var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; });
return parameter && parameter.symbol;
}
ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
@@ -8489,7 +9519,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 285;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 285 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -8502,65 +9532,73 @@ var ts;
var parent = node.parent;
while (true) {
switch (parent.kind) {
- case 200:
+ case 200 /* BinaryExpression */:
var binaryOperator = parent.operatorToken.kind;
return isAssignmentOperator(binaryOperator) && parent.left === node ?
- binaryOperator === 58 ? 1 : 2 :
- 0;
- case 198:
- case 199:
+ binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
+ 0 /* None */;
+ case 198 /* PrefixUnaryExpression */:
+ case 199 /* PostfixUnaryExpression */:
var unaryOperator = parent.operator;
- return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0;
- case 221:
- case 222:
- return parent.initializer === node ? 1 : 0;
- case 191:
- case 183:
- case 204:
- case 209:
+ return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
+ return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
+ case 191 /* ParenthesizedExpression */:
+ case 183 /* ArrayLiteralExpression */:
+ case 204 /* SpreadElement */:
+ case 209 /* NonNullExpression */:
node = parent;
break;
- case 271:
+ case 271 /* ShorthandPropertyAssignment */:
if (parent.name !== node) {
- return 0;
+ return 0 /* None */;
}
node = parent.parent;
break;
- case 270:
+ case 270 /* PropertyAssignment */:
if (parent.name === node) {
- return 0;
+ return 0 /* None */;
}
node = parent.parent;
break;
default:
- return 0;
+ return 0 /* None */;
}
parent = node.parent;
}
}
ts.getAssignmentTargetKind = getAssignmentTargetKind;
+ // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
+ // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
+ // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
+ // (Note that `p` is not a target in the above examples, only `a`.)
function isAssignmentTarget(node) {
- return getAssignmentTargetKind(node) !== 0;
+ return getAssignmentTargetKind(node) !== 0 /* None */;
}
ts.isAssignmentTarget = isAssignmentTarget;
+ /**
+ * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
+ * the same `var` declaration scope as the node's parent.
+ */
function isNodeWithPossibleHoistedDeclaration(node) {
switch (node.kind) {
- case 213:
- case 214:
- case 226:
- case 217:
- case 227:
- case 241:
- case 266:
- case 267:
- case 228:
- case 220:
- case 221:
- case 222:
- case 218:
- case 219:
- case 230:
- case 269:
+ case 213 /* Block */:
+ case 214 /* VariableStatement */:
+ case 226 /* WithStatement */:
+ case 217 /* IfStatement */:
+ case 227 /* SwitchStatement */:
+ case 241 /* CaseBlock */:
+ case 266 /* CaseClause */:
+ case 267 /* DefaultClause */:
+ case 228 /* LabeledStatement */:
+ case 220 /* ForStatement */:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
+ case 218 /* DoStatement */:
+ case 219 /* WhileStatement */:
+ case 230 /* TryStatement */:
+ case 269 /* CatchClause */:
return true;
}
return false;
@@ -8577,26 +9615,27 @@ var ts;
return node;
}
function walkUpParenthesizedTypes(node) {
- return walkUp(node, 173);
+ return walkUp(node, 173 /* ParenthesizedType */);
}
ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
function walkUpParenthesizedExpressions(node) {
- return walkUp(node, 191);
+ return walkUp(node, 191 /* ParenthesizedExpression */);
}
ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
function skipParentheses(node) {
- while (node.kind === 191) {
+ while (node.kind === 191 /* ParenthesizedExpression */) {
node = node.expression;
}
return node;
}
ts.skipParentheses = skipParentheses;
+ // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
function isDeleteTarget(node) {
- if (node.kind !== 185 && node.kind !== 186) {
+ if (node.kind !== 185 /* PropertyAccessExpression */ && node.kind !== 186 /* ElementAccessExpression */) {
return false;
}
node = walkUpParenthesizedExpressions(node.parent);
- return node && node.kind === 194;
+ return node && node.kind === 194 /* DeleteExpression */;
}
ts.isDeleteTarget = isDeleteTarget;
function isNodeDescendantOf(node, ancestor) {
@@ -8608,15 +9647,17 @@ var ts;
return false;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
+ // True if `name` is the name of a declaration node
function isDeclarationName(name) {
return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
+ // See GH#16030
function isAnyDeclarationName(name) {
switch (name.kind) {
- case 71:
- case 9:
- case 8: {
+ case 71 /* Identifier */:
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */: {
var parent = name.parent;
if (ts.isDeclaration(parent)) {
return parent.name === name;
@@ -8627,7 +9668,7 @@ var ts;
}
else {
var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
}
}
default:
@@ -8636,51 +9677,64 @@ var ts;
}
ts.isAnyDeclarationName = isAnyDeclarationName;
function isLiteralComputedPropertyDeclarationName(node) {
- return (node.kind === 9 || node.kind === 8) &&
- node.parent.kind === 147 &&
+ return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) &&
+ node.parent.kind === 147 /* ComputedPropertyName */ &&
ts.isDeclaration(node.parent.parent);
}
ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
+ // Return true if the given identifier is classified as an IdentifierName
function isIdentifierName(node) {
var parent = node.parent;
switch (parent.kind) {
- case 152:
- case 151:
- case 154:
- case 153:
- case 156:
- case 157:
- case 273:
- case 270:
- case 185:
+ case 152 /* PropertyDeclaration */:
+ case 151 /* PropertySignature */:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 273 /* EnumMember */:
+ case 270 /* PropertyAssignment */:
+ case 185 /* PropertyAccessExpression */:
+ // Name in member declaration or property name in property access
return parent.name === node;
- case 146:
+ case 146 /* QualifiedName */:
+ // Name on right hand side of dot in a type query or type reference
if (parent.right === node) {
- while (parent.kind === 146) {
+ while (parent.kind === 146 /* QualifiedName */) {
parent = parent.parent;
}
- return parent.kind === 165 || parent.kind === 162;
+ return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */;
}
return false;
- case 182:
- case 248:
+ case 182 /* BindingElement */:
+ case 248 /* ImportSpecifier */:
+ // Property name in binding element or import specifier
return parent.propertyName === node;
- case 252:
- case 262:
+ case 252 /* ExportSpecifier */:
+ case 262 /* JsxAttribute */:
+ // Any name in an export specifier or JSX Attribute
return true;
}
return false;
}
ts.isIdentifierName = isIdentifierName;
+ // An alias symbol is created by one of the following declarations:
+ // import = ...
+ // import from ...
+ // import * as from ...
+ // import { x as } from ...
+ // export { x as } from ...
+ // export =
+ // export default
function isAliasSymbolDeclaration(node) {
- return node.kind === 243 ||
- node.kind === 242 ||
- node.kind === 245 && !!node.name ||
- node.kind === 246 ||
- node.kind === 248 ||
- node.kind === 252 ||
- node.kind === 249 && exportAssignmentIsAlias(node) ||
- ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2;
+ return node.kind === 243 /* ImportEqualsDeclaration */ ||
+ node.kind === 242 /* NamespaceExportDeclaration */ ||
+ node.kind === 245 /* ImportClause */ && !!node.name ||
+ node.kind === 246 /* NamespaceImport */ ||
+ node.kind === 248 /* ImportSpecifier */ ||
+ node.kind === 252 /* ExportSpecifier */ ||
+ node.kind === 249 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
+ ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */;
}
ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
function exportAssignmentIsAlias(node) {
@@ -8689,15 +9743,16 @@ var ts;
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getClassExtendsHeritageClauseElement(node) {
- var heritageClause = getHeritageClause(node.heritageClauses, 85);
+ var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */);
return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
}
ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement;
function getClassImplementsHeritageClauseElements(node) {
- var heritageClause = getHeritageClause(node.heritageClauses, 108);
+ var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */);
return heritageClause ? heritageClause.types : undefined;
}
ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements;
+ /** Returns the node in an `extends` or `implements` clause of a class or interface. */
function getAllSuperTypeNodes(node) {
return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray
: ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray
@@ -8705,7 +9760,7 @@ var ts;
}
ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
function getInterfaceBaseTypeNodes(node) {
- var heritageClause = getHeritageClause(node.heritageClauses, 85);
+ var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */);
return heritageClause ? heritageClause.types : undefined;
}
ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
@@ -8739,11 +9794,11 @@ var ts;
}
ts.getAncestor = getAncestor;
function isKeyword(token) {
- return 72 <= token && token <= 145;
+ return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */;
}
ts.isKeyword = isKeyword;
function isContextualKeyword(token) {
- return 117 <= token && token <= 145;
+ return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */;
}
ts.isContextualKeyword = isContextualKeyword;
function isNonContextualKeyword(token) {
@@ -8756,7 +9811,7 @@ var ts;
}
ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
function isTrivia(token) {
- return 2 <= token && token <= 7;
+ return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
}
ts.isTrivia = isTrivia;
var FunctionFlags;
@@ -8769,75 +9824,88 @@ var ts;
})(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
function getFunctionFlags(node) {
if (!node) {
- return 4;
+ return 4 /* Invalid */;
}
- var flags = 0;
+ var flags = 0 /* Normal */;
switch (node.kind) {
- case 234:
- case 192:
- case 154:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 154 /* MethodDeclaration */:
if (node.asteriskToken) {
- flags |= 1;
+ flags |= 1 /* Generator */;
}
- case 193:
- if (hasModifier(node, 256)) {
- flags |= 2;
+ // falls through
+ case 193 /* ArrowFunction */:
+ if (hasModifier(node, 256 /* Async */)) {
+ flags |= 2 /* Async */;
}
break;
}
if (!node.body) {
- flags |= 4;
+ flags |= 4 /* Invalid */;
}
return flags;
}
ts.getFunctionFlags = getFunctionFlags;
function isAsyncFunction(node) {
switch (node.kind) {
- case 234:
- case 192:
- case 193:
- case 154:
+ case 234 /* FunctionDeclaration */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
+ case 154 /* MethodDeclaration */:
return node.body !== undefined
&& node.asteriskToken === undefined
- && hasModifier(node, 256);
+ && hasModifier(node, 256 /* Async */);
}
return false;
}
ts.isAsyncFunction = isAsyncFunction;
function isStringOrNumericLiteral(node) {
var kind = node.kind;
- return kind === 9
- || kind === 8;
+ 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
+ * 2. The computed name is *not* expressed as Symbol., where name
+ * is a property of the Symbol constructor that denotes a built in
+ * Symbol.
+ */
function hasDynamicName(declaration) {
var name = ts.getNameOfDeclaration(declaration);
return !!name && isDynamicName(name);
}
ts.hasDynamicName = hasDynamicName;
function isDynamicName(name) {
- return name.kind === 147 &&
+ return name.kind === 147 /* ComputedPropertyName */ &&
!isStringOrNumericLiteral(name.expression) &&
!isWellKnownSymbolSyntactically(name.expression);
}
ts.isDynamicName = isDynamicName;
+ /**
+ * Checks if the expression is of the form:
+ * Symbol.name
+ * where Symbol is literally the word "Symbol", and name is any identifierName
+ */
function isWellKnownSymbolSyntactically(node) {
return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
}
ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
function getPropertyNameForPropertyNameNode(name) {
- if (name.kind === 71) {
+ if (name.kind === 71 /* Identifier */) {
return name.escapedText;
}
- if (name.kind === 9 || name.kind === 8) {
+ if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) {
return escapeLeadingUnderscores(name.text);
}
- if (name.kind === 147) {
+ if (name.kind === 147 /* ComputedPropertyName */) {
var nameExpression = name.expression;
if (isWellKnownSymbolSyntactically(nameExpression)) {
return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
}
- else if (nameExpression.kind === 9 || nameExpression.kind === 8) {
+ else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) {
return escapeLeadingUnderscores(nameExpression.text);
}
}
@@ -8846,10 +9914,10 @@ var ts;
ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
function isPropertyNameLiteral(node) {
switch (node.kind) {
- case 71:
- case 9:
- case 13:
- case 8:
+ case 71 /* Identifier */:
+ case 9 /* StringLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
return true;
default:
return false;
@@ -8857,11 +9925,11 @@ var ts;
}
ts.isPropertyNameLiteral = isPropertyNameLiteral;
function getTextOfIdentifierOrLiteral(node) {
- return node.kind === 71 ? ts.idText(node) : node.text;
+ return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text;
}
ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
function getEscapedTextOfIdentifierOrLiteral(node) {
- return node.kind === 71 ? node.escapedText : escapeLeadingUnderscores(node.text);
+ return node.kind === 71 /* Identifier */ ? node.escapedText : escapeLeadingUnderscores(node.text);
}
ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
function getPropertyNameForKnownSymbolName(symbolName) {
@@ -8872,8 +9940,11 @@ var ts;
return ts.startsWith(symbol.escapedName, "__@");
}
ts.isKnownSymbol = isKnownSymbol;
+ /**
+ * Includes the word "Symbol" with unicode escapes
+ */
function isESSymbolIdentifier(node) {
- return node.kind === 71 && node.escapedText === "Symbol";
+ return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol";
}
ts.isESSymbolIdentifier = isESSymbolIdentifier;
function isPushOrUnshiftIdentifier(node) {
@@ -8882,11 +9953,11 @@ var ts;
ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
function isParameterDeclaration(node) {
var root = getRootDeclaration(node);
- return root.kind === 149;
+ return root.kind === 149 /* Parameter */;
}
ts.isParameterDeclaration = isParameterDeclaration;
function getRootDeclaration(node) {
- while (node.kind === 182) {
+ while (node.kind === 182 /* BindingElement */) {
node = node.parent.parent;
}
return node;
@@ -8894,15 +9965,15 @@ var ts;
ts.getRootDeclaration = getRootDeclaration;
function nodeStartsNewLexicalEnvironment(node) {
var kind = node.kind;
- return kind === 155
- || kind === 192
- || kind === 234
- || kind === 193
- || kind === 154
- || kind === 156
- || kind === 157
- || kind === 239
- || kind === 274;
+ return kind === 155 /* Constructor */
+ || kind === 192 /* FunctionExpression */
+ || kind === 234 /* FunctionDeclaration */
+ || kind === 193 /* ArrowFunction */
+ || kind === 154 /* MethodDeclaration */
+ || kind === 156 /* GetAccessor */
+ || kind === 157 /* SetAccessor */
+ || kind === 239 /* ModuleDeclaration */
+ || kind === 274 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -8921,55 +9992,55 @@ var ts;
})(Associativity = ts.Associativity || (ts.Associativity = {}));
function getExpressionAssociativity(expression) {
var operator = getOperator(expression);
- var hasArguments = expression.kind === 188 && expression.arguments !== undefined;
+ var hasArguments = expression.kind === 188 /* NewExpression */ && expression.arguments !== undefined;
return getOperatorAssociativity(expression.kind, operator, hasArguments);
}
ts.getExpressionAssociativity = getExpressionAssociativity;
function getOperatorAssociativity(kind, operator, hasArguments) {
switch (kind) {
- case 188:
- return hasArguments ? 0 : 1;
- case 198:
- case 195:
- case 196:
- case 194:
- case 197:
- case 201:
- case 203:
- return 1;
- case 200:
+ case 188 /* NewExpression */:
+ return hasArguments ? 0 /* Left */ : 1 /* Right */;
+ case 198 /* PrefixUnaryExpression */:
+ case 195 /* TypeOfExpression */:
+ case 196 /* VoidExpression */:
+ case 194 /* DeleteExpression */:
+ case 197 /* AwaitExpression */:
+ case 201 /* ConditionalExpression */:
+ case 203 /* YieldExpression */:
+ return 1 /* Right */;
+ case 200 /* BinaryExpression */:
switch (operator) {
- case 40:
- case 58:
- case 59:
- case 60:
- case 62:
- case 61:
- case 63:
- case 64:
- case 65:
- case 66:
- case 67:
- case 68:
- case 70:
- case 69:
- return 1;
+ case 40 /* AsteriskAsteriskToken */:
+ case 58 /* EqualsToken */:
+ case 59 /* PlusEqualsToken */:
+ case 60 /* MinusEqualsToken */:
+ case 62 /* AsteriskAsteriskEqualsToken */:
+ case 61 /* AsteriskEqualsToken */:
+ case 63 /* SlashEqualsToken */:
+ case 64 /* PercentEqualsToken */:
+ case 65 /* LessThanLessThanEqualsToken */:
+ case 66 /* GreaterThanGreaterThanEqualsToken */:
+ case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
+ case 68 /* AmpersandEqualsToken */:
+ case 70 /* CaretEqualsToken */:
+ case 69 /* BarEqualsToken */:
+ return 1 /* Right */;
}
}
- return 0;
+ return 0 /* Left */;
}
ts.getOperatorAssociativity = getOperatorAssociativity;
function getExpressionPrecedence(expression) {
var operator = getOperator(expression);
- var hasArguments = expression.kind === 188 && expression.arguments !== undefined;
+ var hasArguments = expression.kind === 188 /* NewExpression */ && expression.arguments !== undefined;
return getOperatorPrecedence(expression.kind, operator, hasArguments);
}
ts.getExpressionPrecedence = getExpressionPrecedence;
function getOperator(expression) {
- if (expression.kind === 200) {
+ if (expression.kind === 200 /* BinaryExpression */) {
return expression.operatorToken.kind;
}
- else if (expression.kind === 198 || expression.kind === 199) {
+ else if (expression.kind === 198 /* PrefixUnaryExpression */ || expression.kind === 199 /* PostfixUnaryExpression */) {
return expression.operator;
}
else {
@@ -8979,122 +10050,125 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 303:
+ case 303 /* CommaListExpression */:
return 0;
- case 204:
+ case 204 /* SpreadElement */:
return 1;
- case 203:
+ case 203 /* YieldExpression */:
return 2;
- case 201:
+ case 201 /* ConditionalExpression */:
return 4;
- case 200:
+ case 200 /* BinaryExpression */:
switch (operatorKind) {
- case 26:
+ case 26 /* CommaToken */:
return 0;
- case 58:
- case 59:
- case 60:
- case 62:
- case 61:
- case 63:
- case 64:
- case 65:
- case 66:
- case 67:
- case 68:
- case 70:
- case 69:
+ case 58 /* EqualsToken */:
+ case 59 /* PlusEqualsToken */:
+ case 60 /* MinusEqualsToken */:
+ case 62 /* AsteriskAsteriskEqualsToken */:
+ case 61 /* AsteriskEqualsToken */:
+ case 63 /* SlashEqualsToken */:
+ case 64 /* PercentEqualsToken */:
+ case 65 /* LessThanLessThanEqualsToken */:
+ case 66 /* GreaterThanGreaterThanEqualsToken */:
+ case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
+ case 68 /* AmpersandEqualsToken */:
+ case 70 /* CaretEqualsToken */:
+ case 69 /* BarEqualsToken */:
return 3;
default:
return getBinaryOperatorPrecedence(operatorKind);
}
- case 198:
- case 195:
- case 196:
- case 194:
- case 197:
+ case 198 /* PrefixUnaryExpression */:
+ case 195 /* TypeOfExpression */:
+ case 196 /* VoidExpression */:
+ case 194 /* DeleteExpression */:
+ case 197 /* AwaitExpression */:
return 16;
- case 199:
+ case 199 /* PostfixUnaryExpression */:
return 17;
- case 187:
+ case 187 /* CallExpression */:
return 18;
- case 188:
+ case 188 /* NewExpression */:
return hasArguments ? 19 : 18;
- case 189:
- case 185:
- case 186:
+ case 189 /* TaggedTemplateExpression */:
+ case 185 /* PropertyAccessExpression */:
+ case 186 /* ElementAccessExpression */:
return 19;
- case 99:
- case 97:
- case 71:
- case 95:
- case 101:
- case 86:
- case 8:
- case 9:
- case 183:
- case 184:
- case 192:
- case 193:
- case 205:
- case 255:
- case 256:
- case 259:
- case 12:
- case 13:
- case 202:
- case 191:
- case 206:
+ case 99 /* ThisKeyword */:
+ case 97 /* SuperKeyword */:
+ case 71 /* Identifier */:
+ case 95 /* NullKeyword */:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ case 183 /* ArrayLiteralExpression */:
+ case 184 /* ObjectLiteralExpression */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
+ case 205 /* ClassExpression */:
+ case 255 /* JsxElement */:
+ case 256 /* JsxSelfClosingElement */:
+ case 259 /* JsxFragment */:
+ case 12 /* RegularExpressionLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ case 202 /* TemplateExpression */:
+ case 191 /* ParenthesizedExpression */:
+ case 206 /* OmittedExpression */:
return 20;
default:
return -1;
}
}
ts.getOperatorPrecedence = getOperatorPrecedence;
+ /* @internal */
function getBinaryOperatorPrecedence(kind) {
switch (kind) {
- case 54:
+ case 54 /* BarBarToken */:
return 5;
- case 53:
+ case 53 /* AmpersandAmpersandToken */:
return 6;
- case 49:
+ case 49 /* BarToken */:
return 7;
- case 50:
+ case 50 /* CaretToken */:
return 8;
- case 48:
+ case 48 /* AmpersandToken */:
return 9;
- case 32:
- case 33:
- case 34:
- case 35:
+ case 32 /* EqualsEqualsToken */:
+ case 33 /* ExclamationEqualsToken */:
+ case 34 /* EqualsEqualsEqualsToken */:
+ case 35 /* ExclamationEqualsEqualsToken */:
return 10;
- case 27:
- case 29:
- case 30:
- case 31:
- case 93:
- case 92:
- case 118:
+ case 27 /* LessThanToken */:
+ case 29 /* GreaterThanToken */:
+ case 30 /* LessThanEqualsToken */:
+ case 31 /* GreaterThanEqualsToken */:
+ case 93 /* InstanceOfKeyword */:
+ case 92 /* InKeyword */:
+ case 118 /* AsKeyword */:
return 11;
- case 45:
- case 46:
- case 47:
+ case 45 /* LessThanLessThanToken */:
+ case 46 /* GreaterThanGreaterThanToken */:
+ case 47 /* GreaterThanGreaterThanGreaterThanToken */:
return 12;
- case 37:
- case 38:
+ case 37 /* PlusToken */:
+ case 38 /* MinusToken */:
return 13;
- case 39:
- case 41:
- case 42:
+ case 39 /* AsteriskToken */:
+ case 41 /* SlashToken */:
+ case 42 /* PercentToken */:
return 14;
- case 40:
+ case 40 /* AsteriskAsteriskToken */:
return 15;
}
+ // -1 is lower than all other precedences. Returning it will cause binary expression
+ // parsing to stop.
return -1;
}
ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
function createDiagnosticCollection() {
- var nonFileDiagnostics = [];
+ var nonFileDiagnostics = []; // See GH#19873
var filesWithDiagnostics = [];
var fileDiagnostics = ts.createMap();
var hasReadNonFileDiagnostics = false;
@@ -9112,12 +10186,13 @@ var ts;
if (diagnostic.file) {
diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
if (!diagnostics) {
- diagnostics = [];
+ diagnostics = []; // See GH#19873
fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
}
}
else {
+ // If we've already read the non-file diagnostics, do not modify the existing array.
if (hasReadNonFileDiagnostics) {
hasReadNonFileDiagnostics = false;
nonFileDiagnostics = nonFileDiagnostics.slice();
@@ -9143,6 +10218,11 @@ var ts;
}
}
ts.createDiagnosticCollection = createDiagnosticCollection;
+ // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
+ // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
+ // the language service. These characters should be escaped when printing, and if any characters are added,
+ // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
+ // There is no reason for this other than that JSON.stringify does not handle it either.
var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
@@ -9159,28 +10239,35 @@ var ts;
"\`": "\\\`",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
- "\u0085": "\\u0085"
+ "\u0085": "\\u0085" // nextLine
});
+ /**
+ * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
+ * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
+ * Note that this doesn't actually wrap the input in double quotes.
+ */
function escapeString(s, quoteChar) {
- var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp :
- quoteChar === 39 ? singleQuoteEscapedCharsRegExp :
+ var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
+ quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
doubleQuoteEscapedCharsRegExp;
return s.replace(escapedCharsRegExp, getReplacement);
}
ts.escapeString = escapeString;
function getReplacement(c, offset, input) {
- if (c.charCodeAt(0) === 0) {
+ if (c.charCodeAt(0) === 0 /* nullCharacter */) {
var lookAhead = input.charCodeAt(offset + c.length);
- if (lookAhead >= 48 && lookAhead <= 57) {
+ if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
+ // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode)
return "\\x00";
}
+ // Otherwise, keep printing a literal \0 for the null character
return "\\0";
}
return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
}
function isIntrinsicJsxName(name) {
var ch = name.charCodeAt(0);
- return (ch >= 97 && ch <= 122) || name.indexOf("-") > -1;
+ return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1;
}
ts.isIntrinsicJsxName = isIntrinsicJsxName;
function get16BitUnicodeEscapeSequence(charCode) {
@@ -9191,6 +10278,8 @@ var ts;
var nonAsciiCharacters = /[^\u0000-\u007F]/g;
function escapeNonAsciiString(s, quoteChar) {
s = escapeString(s, quoteChar);
+ // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
+ // Otherwise just return the original string.
return nonAsciiCharacters.test(s) ?
s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) :
s;
@@ -9309,11 +10398,14 @@ var ts;
return getResolvedExternalModuleName(host, file);
}
ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
+ /**
+ * Resolves a local path to a path which is absolute to the base of the emit
+ */
function getExternalModuleNameFromPath(host, fileName, referencePath) {
var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
- var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false);
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
var extensionless = ts.removeFileExtension(relativePath);
return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
}
@@ -9332,19 +10424,29 @@ var ts;
ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
function getDeclarationEmitOutputFilePath(sourceFile, host) {
var options = host.getCompilerOptions();
- var outputDir = options.declarationDir || options.outDir;
+ var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
var path = outputDir
? getSourceFilePathInNewDir(sourceFile, host, outputDir)
: sourceFile.fileName;
- return ts.removeFileExtension(path) + ".d.ts";
+ return ts.removeFileExtension(path) + ".d.ts" /* Dts */;
}
ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ /**
+ * Gets the source files that are expected to have an emit output.
+ *
+ * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
+ * transformations.
+ *
+ * @param host An EmitHost.
+ * @param targetSourceFile An optional target source file to emit.
+ */
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
+ // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
});
@@ -9355,6 +10457,7 @@ var ts;
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
+ /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
}
@@ -9391,12 +10494,14 @@ var ts;
return accessor.parameters[hasThis ? 1 : 0];
}
}
+ /** Get the type annotation for the value parameter. */
function getSetAccessorTypeAnnotationNode(accessor) {
var parameter = getSetAccessorValueParameter(accessor);
return parameter && parameter.type;
}
ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
function getThisParameter(signature) {
+ // callback tags do not currently support this parameters
if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
var thisParameter = signature.parameters[0];
if (parameterIsThisKeyword(thisParameter)) {
@@ -9410,24 +10515,25 @@ var ts;
}
ts.parameterIsThisKeyword = parameterIsThisKeyword;
function isThisIdentifier(node) {
- return !!node && node.kind === 71 && identifierIsThisKeyword(node);
+ return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node);
}
ts.isThisIdentifier = isThisIdentifier;
function identifierIsThisKeyword(id) {
- return id.originalKeywordKind === 99;
+ return id.originalKeywordKind === 99 /* ThisKeyword */;
}
ts.identifierIsThisKeyword = identifierIsThisKeyword;
function getAllAccessorDeclarations(declarations, accessor) {
+ // TODO: GH#18217
var firstAccessor;
var secondAccessor;
var getAccessor;
var setAccessor;
if (hasDynamicName(accessor)) {
firstAccessor = accessor;
- if (accessor.kind === 156) {
+ if (accessor.kind === 156 /* GetAccessor */) {
getAccessor = accessor;
}
- else if (accessor.kind === 157) {
+ else if (accessor.kind === 157 /* SetAccessor */) {
setAccessor = accessor;
}
else {
@@ -9436,8 +10542,8 @@ var ts;
}
else {
ts.forEach(declarations, function (member) {
- if ((member.kind === 156 || member.kind === 157)
- && hasModifier(member, 32) === hasModifier(accessor, 32)) {
+ if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */)
+ && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
var memberName = getPropertyNameForPropertyNameNode(member.name);
var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
if (memberName === accessorName) {
@@ -9447,10 +10553,10 @@ var ts;
else if (!secondAccessor) {
secondAccessor = member;
}
- if (member.kind === 156 && !getAccessor) {
+ if (member.kind === 156 /* GetAccessor */ && !getAccessor) {
getAccessor = member;
}
- if (member.kind === 157 && !setAccessor) {
+ if (member.kind === 157 /* SetAccessor */ && !setAccessor) {
setAccessor = member;
}
}
@@ -9465,6 +10571,10 @@ var ts;
};
}
ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
+ /**
+ * Gets the effective type annotation of a variable, parameter, or property. If the node was
+ * parsed in a JavaScript file, gets the type annotation from JSDoc.
+ */
function getEffectiveTypeAnnotationNode(node) {
return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined);
}
@@ -9473,6 +10583,10 @@ var ts;
return node.type;
}
ts.getTypeAnnotationNode = getTypeAnnotationNode;
+ /**
+ * Gets the effective return type annotation of a signature. If the node was parsed in a
+ * JavaScript file, gets the return type annotation from JSDoc.
+ */
function getEffectiveReturnTypeNode(node) {
if (ts.isJSDocSignature(node)) {
return node.type && node.type.typeExpression && node.type.typeExpression.type;
@@ -9480,12 +10594,16 @@ var ts;
return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined);
}
ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
+ /**
+ * Gets the effective type parameters. If the node was parsed in a
+ * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
+ */
function getEffectiveTypeParameterDeclarations(node) {
if (ts.isJSDocSignature(node)) {
return ts.emptyArray;
}
if (isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 286);
+ ts.Debug.assert(node.parent.kind === 286 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray);
@@ -9495,9 +10613,14 @@ var ts;
return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
+ /** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 286 && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 286 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
+ /**
+ * Gets the effective type annotation of the value parameter of a set accessor. If the node
+ * was parsed in a JavaScript file, gets the type annotation from JSDoc.
+ */
function getEffectiveSetAccessorTypeAnnotationNode(node) {
var parameter = getSetAccessorValueParameter(node);
return parameter && getEffectiveTypeAnnotationNode(parameter);
@@ -9508,6 +10631,7 @@ var ts;
}
ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
+ // If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
@@ -9515,6 +10639,7 @@ var ts;
}
ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
+ // If the leading comments start on different line than the start of node, write new line
if (pos !== commentPos &&
getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
writer.writeLine();
@@ -9547,15 +10672,25 @@ var ts;
}
}
ts.emitComments = emitComments;
+ /**
+ * Detached comment is a comment at the top of file or function body that is separated from
+ * the next statement by space.
+ */
function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
var leadingComments;
var currentDetachedCommentInfo;
if (removeComments) {
+ // removeComments is true, only reserve pinned comment at the top of file
+ // For example:
+ // /*! Pinned Comment */
+ //
+ // var x = 10;
if (node.pos === 0) {
leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
}
}
else {
+ // removeComments is false, just get detached as normal and bypass the process to filter comment
leadingComments = ts.getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
@@ -9567,6 +10702,9 @@ var ts;
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
+ // far.
break;
}
}
@@ -9574,11 +10712,15 @@ var ts;
lastComment = comment;
}
if (detachedComments.length) {
+ // 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 = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
+ // Valid detachedComments
emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
- emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment);
+ emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
}
}
@@ -9590,7 +10732,7 @@ var ts;
}
ts.emitDetachedComments = emitDetachedComments;
function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
- if (text.charCodeAt(commentPos + 1) === 42) {
+ if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
var lineCount = lineMap.length;
var firstCommentLineIndent = void 0;
@@ -9599,29 +10741,50 @@ var ts;
? text.length + 1
: lineMap[currentLine + 1];
if (pos !== commentPos) {
+ // If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
}
+ // These are number of spaces writer is going to write at current indent
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
+ // Number of spaces we want to be writing
+ // eg: Assume writer indent
+ // module m {
+ // /* starts at character 9 this is line 1
+ // * starts at character pos 4 line --1 = 8 - 8 + 3
+ // More left indented comment */ --2 = 8 - 8 + 2
+ // class c { }
+ // }
+ // module m {
+ // /* this is line 1 -- Assume current writer indent 8
+ // * line --3 = 8 - 4 + 5
+ // More right indented comment */ --4 = 8 - 4 + 11
+ // class c { }
+ // }
var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
+ // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
writer.rawWrite(indentSizeSpaceString);
+ // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
while (numberOfSingleSpacesToEmit) {
writer.rawWrite(" ");
numberOfSingleSpacesToEmit--;
}
}
else {
+ // No spaces to emit write empty string
writer.rawWrite("");
}
}
+ // Write the comment line text
writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
+ // Single line comment of style //....
writer.write(text.substring(commentPos, commentEnd));
}
}
@@ -9630,29 +10793,33 @@ var ts;
var end = Math.min(commentEnd, 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 !== commentEnd) {
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.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
- if (text.charCodeAt(pos) === 9) {
+ 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 hasModifiers(node) {
- return getModifierFlags(node) !== 0;
+ return getModifierFlags(node) !== 0 /* None */;
}
ts.hasModifiers = hasModifiers;
function hasModifier(node, flags) {
@@ -9660,11 +10827,11 @@ var ts;
}
ts.hasModifier = hasModifier;
function hasStaticModifier(node) {
- return hasModifier(node, 32);
+ return hasModifier(node, 32 /* Static */);
}
ts.hasStaticModifier = hasStaticModifier;
function hasReadonlyModifier(node) {
- return hasModifier(node, 64);
+ return hasModifier(node, 64 /* Readonly */);
}
ts.hasReadonlyModifier = hasReadonlyModifier;
function getSelectedModifierFlags(node, flags) {
@@ -9672,58 +10839,59 @@ var ts;
}
ts.getSelectedModifierFlags = getSelectedModifierFlags;
function getModifierFlags(node) {
- if (node.modifierFlagsCache & 536870912) {
- return node.modifierFlagsCache & ~536870912;
+ if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
+ return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
}
var flags = getModifierFlagsNoCache(node);
- node.modifierFlagsCache = flags | 536870912;
+ node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
return flags;
}
ts.getModifierFlags = getModifierFlags;
function getModifierFlagsNoCache(node) {
- var flags = 0;
+ var flags = 0 /* None */;
if (node.modifiers) {
for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
var modifier = _a[_i];
flags |= modifierToFlag(modifier.kind);
}
}
- if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) {
- flags |= 1;
+ if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) {
+ flags |= 1 /* Export */;
}
return flags;
}
ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
function modifierToFlag(token) {
switch (token) {
- case 115: return 32;
- case 114: return 4;
- case 113: return 16;
- case 112: return 8;
- case 117: return 128;
- case 84: return 1;
- case 124: return 2;
- case 76: return 2048;
- case 79: return 512;
- case 120: return 256;
- case 132: return 64;
+ case 115 /* StaticKeyword */: return 32 /* Static */;
+ case 114 /* PublicKeyword */: return 4 /* Public */;
+ case 113 /* ProtectedKeyword */: return 16 /* Protected */;
+ case 112 /* PrivateKeyword */: return 8 /* Private */;
+ case 117 /* AbstractKeyword */: return 128 /* Abstract */;
+ case 84 /* ExportKeyword */: return 1 /* Export */;
+ case 124 /* DeclareKeyword */: return 2 /* Ambient */;
+ case 76 /* ConstKeyword */: return 2048 /* Const */;
+ case 79 /* DefaultKeyword */: return 512 /* Default */;
+ case 120 /* AsyncKeyword */: return 256 /* Async */;
+ case 132 /* ReadonlyKeyword */: return 64 /* Readonly */;
}
- return 0;
+ return 0 /* None */;
}
ts.modifierToFlag = modifierToFlag;
function isLogicalOperator(token) {
- return token === 54
- || token === 53
- || token === 51;
+ return token === 54 /* BarBarToken */
+ || token === 53 /* AmpersandAmpersandToken */
+ || token === 51 /* ExclamationToken */;
}
ts.isLogicalOperator = isLogicalOperator;
function isAssignmentOperator(token) {
- return token >= 58 && token <= 70;
+ return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */;
}
ts.isAssignmentOperator = isAssignmentOperator;
+ /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
function tryGetClassExtendingExpressionWithTypeArguments(node) {
if (ts.isExpressionWithTypeArguments(node) &&
- node.parent.token === 85 &&
+ node.parent.token === 85 /* ExtendsKeyword */ &&
ts.isClassLike(node.parent.parent)) {
return node.parent.parent;
}
@@ -9732,16 +10900,16 @@ var ts;
function isAssignmentExpression(node, excludeCompoundAssignment) {
return ts.isBinaryExpression(node)
&& (excludeCompoundAssignment
- ? node.operatorToken.kind === 58
+ ? node.operatorToken.kind === 58 /* EqualsToken */
: isAssignmentOperator(node.operatorToken.kind))
&& ts.isLeftHandSideExpression(node.left);
}
ts.isAssignmentExpression = isAssignmentExpression;
function isDestructuringAssignment(node) {
- if (isAssignmentExpression(node, true)) {
+ if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
var kind = node.left.kind;
- return kind === 184
- || kind === 183;
+ return kind === 184 /* ObjectLiteralExpression */
+ || kind === 183 /* ArrayLiteralExpression */;
}
return false;
}
@@ -9751,16 +10919,16 @@ var ts;
}
ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
function isExpressionWithTypeArgumentsInClassImplementsClause(node) {
- return node.kind === 207
+ return node.kind === 207 /* ExpressionWithTypeArguments */
&& isEntityNameExpression(node.expression)
&& node.parent
- && node.parent.token === 108
+ && node.parent.token === 108 /* ImplementsKeyword */
&& node.parent.parent
&& ts.isClassLike(node.parent.parent);
}
ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause;
function isEntityNameExpression(node) {
- return node.kind === 71 || isPropertyAccessEntityNameExpression(node);
+ return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
}
ts.isEntityNameExpression = isEntityNameExpression;
function isPropertyAccessEntityNameExpression(node) {
@@ -9772,17 +10940,17 @@ var ts;
}
ts.isPrototypeAccess = isPrototypeAccess;
function isRightSideOfQualifiedNameOrPropertyAccess(node) {
- return (node.parent.kind === 146 && node.parent.right === node) ||
- (node.parent.kind === 185 && node.parent.name === node);
+ return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) ||
+ (node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.name === node);
}
ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
function isEmptyObjectLiteral(expression) {
- return expression.kind === 184 &&
+ return expression.kind === 184 /* ObjectLiteralExpression */ &&
expression.properties.length === 0;
}
ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
function isEmptyArrayLiteral(expression) {
- return expression.kind === 183 &&
+ return expression.kind === 183 /* ArrayLiteralExpression */ &&
expression.elements.length === 0;
}
ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
@@ -9791,17 +10959,23 @@ var ts;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
function isExportDefaultSymbol(symbol) {
- return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512);
+ return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
}
+ /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
}
ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension;
+ /**
+ * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
+ * representing the UTF-8 encoding of the character, and return the expanded char code list.
+ */
function getExpandedCharCodes(input) {
var output = [];
var length = input.length;
for (var i = 0; i < length; i++) {
var charCode = input.charCodeAt(i);
+ // handle utf8
if (charCode < 0x80) {
output.push(charCode);
}
@@ -9827,6 +11001,9 @@ var ts;
return output;
}
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+ /**
+ * Converts a string to a base-64 encoded ASCII string.
+ */
function convertToBase64(input) {
var result = "";
var charCodes = getExpandedCharCodes(input);
@@ -9834,16 +11011,21 @@ var ts;
var length = charCodes.length;
var byte1, byte2, byte3, byte4;
while (i < length) {
+ // Convert every 6-bits in the input 3 character points
+ // into a base64 digit
byte1 = charCodes[i] >> 2;
byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
byte4 = charCodes[i + 2] & 63;
+ // We are out of characters in the input, set the extra
+ // digits to 64 (padding character).
if (i + 1 >= length) {
byte3 = byte4 = 64;
}
else if (i + 2 >= length) {
byte4 = 64;
}
+ // Write to the output
result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
i += 3;
}
@@ -9869,9 +11051,12 @@ var ts;
i++;
nextCode = codes[i];
}
+ // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
output += String.fromCharCode(value);
}
else {
+ // We don't want to kill the process when decoding fails (due to a following char byte not
+ // following a leading char), so we just print the (bad) value
output += String.fromCharCode(charCode);
i++;
}
@@ -9893,9 +11078,11 @@ var ts;
var expandedCharCodes = [];
var i = 0;
while (i < length) {
+ // Stop decoding once padding characters are present
if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
break;
}
+ // convert 4 input digits into three characters, ignoring padding characters at the end
var ch1 = base64Digits.indexOf(input[i]);
var ch2 = base64Digits.indexOf(input[i + 1]);
var ch3 = base64Digits.indexOf(input[i + 2]);
@@ -9903,10 +11090,10 @@ var ts;
var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
- if (code2 === 0 && ch3 !== 0) {
+ if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
expandedCharCodes.push(code1);
}
- else if (code3 === 0 && ch4 !== 0) {
+ else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
expandedCharCodes.push(code1, code2);
}
else {
@@ -9921,14 +11108,17 @@ var ts;
var lineFeed = "\n";
function getNewLineCharacter(options, getNewLine) {
switch (options.newLine) {
- case 0:
+ case 0 /* CarriageReturnLineFeed */:
return carriageReturnLineFeed;
- case 1:
+ case 1 /* LineFeed */:
return lineFeed;
}
return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
}
ts.getNewLineCharacter = getNewLineCharacter;
+ /**
+ * Formats an enum value as a string for debugging and debug assertions.
+ */
function formatEnum(value, enumObject, isFlags) {
if (value === void 0) { value = 0; }
var members = getEnumMembers(enumObject);
@@ -9970,61 +11160,96 @@ var ts;
return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
}
function formatSyntaxKind(kind) {
- return formatEnum(kind, ts.SyntaxKind, false);
+ return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
}
ts.formatSyntaxKind = formatSyntaxKind;
function formatModifierFlags(flags) {
- return formatEnum(flags, ts.ModifierFlags, true);
+ return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
}
ts.formatModifierFlags = formatModifierFlags;
function formatTransformFlags(flags) {
- return formatEnum(flags, ts.TransformFlags, true);
+ return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
}
ts.formatTransformFlags = formatTransformFlags;
function formatEmitFlags(flags) {
- return formatEnum(flags, ts.EmitFlags, true);
+ return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
}
ts.formatEmitFlags = formatEmitFlags;
function formatSymbolFlags(flags) {
- return formatEnum(flags, ts.SymbolFlags, true);
+ return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
}
ts.formatSymbolFlags = formatSymbolFlags;
function formatTypeFlags(flags) {
- return formatEnum(flags, ts.TypeFlags, true);
+ return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
}
ts.formatTypeFlags = formatTypeFlags;
function formatObjectFlags(flags) {
- return formatEnum(flags, ts.ObjectFlags, true);
+ return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
}
ts.formatObjectFlags = formatObjectFlags;
+ /**
+ * Creates a new TextRange from the provided pos and end.
+ *
+ * @param pos The start position.
+ * @param end The end position.
+ */
function createRange(pos, end) {
return { pos: pos, end: end };
}
ts.createRange = createRange;
+ /**
+ * Creates a new TextRange from a provided range with a new end position.
+ *
+ * @param range A TextRange.
+ * @param end The new end position.
+ */
function moveRangeEnd(range, end) {
return createRange(range.pos, end);
}
ts.moveRangeEnd = moveRangeEnd;
+ /**
+ * Creates a new TextRange from a provided range with a new start position.
+ *
+ * @param range A TextRange.
+ * @param pos The new Start position.
+ */
function moveRangePos(range, pos) {
return createRange(pos, range.end);
}
ts.moveRangePos = moveRangePos;
+ /**
+ * Moves the start position of a range past any decorators.
+ */
function moveRangePastDecorators(node) {
return node.decorators && node.decorators.length > 0
? moveRangePos(node, node.decorators.end)
: node;
}
ts.moveRangePastDecorators = moveRangePastDecorators;
+ /**
+ * Moves the start position of a range past any decorators or modifiers.
+ */
function moveRangePastModifiers(node) {
return node.modifiers && node.modifiers.length > 0
? moveRangePos(node, node.modifiers.end)
: moveRangePastDecorators(node);
}
ts.moveRangePastModifiers = moveRangePastModifiers;
+ /**
+ * Determines whether a TextRange has the same start and end positions.
+ *
+ * @param range A TextRange.
+ */
function isCollapsedRange(range) {
return range.pos === range.end;
}
ts.isCollapsedRange = isCollapsedRange;
+ /**
+ * Creates a new TextRange for a token at the provides start position.
+ *
+ * @param pos The start position.
+ * @param token The token.
+ */
function createTokenRange(pos, token) {
return createRange(pos, pos + ts.tokenToString(token).length);
}
@@ -10058,12 +11283,16 @@ var ts;
return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
}
ts.getStartPositionOfRange = getStartPositionOfRange;
+ /**
+ * Determines whether a name was originally the declaration name of an enum or namespace
+ * declaration.
+ */
function isDeclarationNameOfEnumOrNamespace(node) {
var parseNode = ts.getParseTreeNode(node);
if (parseNode) {
switch (parseNode.parent.kind) {
- case 238:
- case 239:
+ case 238 /* EnumDeclaration */:
+ case 239 /* ModuleDeclaration */:
return parseNode === parseNode.parent.name;
}
}
@@ -10078,6 +11307,7 @@ var ts;
return node.initializer !== undefined;
}
function isWatchSet(options) {
+ // Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}
ts.isWatchSet = isWatchSet;
@@ -10086,69 +11316,74 @@ var ts;
}
ts.closeFileWatcher = closeFileWatcher;
function getCheckFlags(symbol) {
- return symbol.flags & 33554432 ? symbol.checkFlags : 0;
+ return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
}
ts.getCheckFlags = getCheckFlags;
function getDeclarationModifierFlagsFromSymbol(s) {
if (s.valueDeclaration) {
var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
- return s.parent && s.parent.flags & 32 ? flags : flags & ~28;
+ return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
}
- if (getCheckFlags(s) & 6) {
+ if (getCheckFlags(s) & 6 /* Synthetic */) {
var checkFlags = s.checkFlags;
- var accessModifier = checkFlags & 256 ? 8 :
- checkFlags & 64 ? 4 :
- 16;
- var staticModifier = checkFlags & 512 ? 32 : 0;
+ var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ :
+ checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ :
+ 16 /* Protected */;
+ var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0;
return accessModifier | staticModifier;
}
- if (s.flags & 4194304) {
- return 4 | 32;
+ if (s.flags & 4194304 /* Prototype */) {
+ return 4 /* Public */ | 32 /* Static */;
}
return 0;
}
ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
function skipAlias(symbol, checker) {
- return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol;
+ return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
}
ts.skipAlias = skipAlias;
+ /** See comment on `declareModuleMember` in `binder.ts`. */
function getCombinedLocalAndExportSymbolFlags(symbol) {
return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
}
ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
function isWriteOnlyAccess(node) {
- return accessKind(node) === 1;
+ return accessKind(node) === 1 /* Write */;
}
ts.isWriteOnlyAccess = isWriteOnlyAccess;
function isWriteAccess(node) {
- return accessKind(node) !== 0;
+ return accessKind(node) !== 0 /* Read */;
}
ts.isWriteAccess = isWriteAccess;
var AccessKind;
(function (AccessKind) {
+ /** Only reads from a variable. */
AccessKind[AccessKind["Read"] = 0] = "Read";
+ /** Only writes to a variable without using the result. E.g.: `x++;`. */
AccessKind[AccessKind["Write"] = 1] = "Write";
+ /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
})(AccessKind || (AccessKind = {}));
function accessKind(node) {
var parent = node.parent;
if (!parent)
- return 0;
+ return 0 /* Read */;
switch (parent.kind) {
- case 199:
- case 198:
+ case 199 /* PostfixUnaryExpression */:
+ case 198 /* PrefixUnaryExpression */:
var operator = parent.operator;
- return operator === 43 || operator === 44 ? writeOrReadWrite() : 0;
- case 200:
+ return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
+ case 200 /* BinaryExpression */:
var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
- return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0;
- case 185:
- return parent.name !== node ? 0 : accessKind(parent);
+ return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */;
+ case 185 /* PropertyAccessExpression */:
+ return parent.name !== node ? 0 /* Read */ : accessKind(parent);
default:
- return 0;
+ return 0 /* Read */;
}
function writeOrReadWrite() {
- return parent.parent && parent.parent.kind === 216 ? 1 : 2;
+ // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
+ return parent.parent && parent.parent.kind === 216 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
}
}
function compareDataObjects(dst, src) {
@@ -10170,30 +11405,43 @@ var ts;
return true;
}
ts.compareDataObjects = compareDataObjects;
+ /**
+ * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
+ */
function clearMap(map, onDeleteValue) {
+ // Remove all
map.forEach(onDeleteValue);
map.clear();
}
ts.clearMap = clearMap;
+ /**
+ * Mutates the map with newMap such that keys in map will be same as newMap.
+ */
function mutateMap(map, newMap, options) {
var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
+ // Needs update
map.forEach(function (existingValue, key) {
var valueInNewMap = newMap.get(key);
+ // Not present any more in new map, remove it
if (valueInNewMap === undefined) {
map.delete(key);
onDeleteValue(existingValue, key);
}
+ // If present notify about existing values
else if (onExistingValue) {
onExistingValue(existingValue, valueInNewMap, key);
}
});
+ // Add new values that are not already present
newMap.forEach(function (valueInNewMap, key) {
if (!map.has(key)) {
+ // New values
map.set(key, createNewValue(key, valueInNewMap));
}
});
}
ts.mutateMap = mutateMap;
+ /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
function forEachAncestorDirectory(directory, callback) {
while (true) {
var result = callback(directory);
@@ -10208,14 +11456,15 @@ var ts;
}
}
ts.forEachAncestorDirectory = forEachAncestorDirectory;
+ // Return true if the given type is the constructor type for an abstract class
function isAbstractConstructorType(type) {
- return !!(getObjectFlags(type) & 16) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
+ return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
}
ts.isAbstractConstructorType = isAbstractConstructorType;
function isAbstractConstructorSymbol(symbol) {
- if (symbol.flags & 32) {
+ if (symbol.flags & 32 /* Class */) {
var declaration = getClassLikeDeclarationOfSymbol(symbol);
- return !!declaration && hasModifier(declaration, 128);
+ return !!declaration && hasModifier(declaration, 128 /* Abstract */);
}
return false;
}
@@ -10225,11 +11474,11 @@ var ts;
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 131072 ? type.objectFlags : 0;
+ return type.flags & 131072 /* Object */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
- return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0;
+ return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
}
ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
function forSomeAncestorDirectory(directory, callback) {
@@ -10251,6 +11500,7 @@ var ts;
if (nodeIsPresent(child))
lastChild = child;
}, function (children) {
+ // As an optimization, jump straight to the end of the list.
for (var i = children.length - 1; i >= 0; i--) {
if (nodeIsPresent(children[i])) {
lastChild = children[i];
@@ -10279,16 +11529,16 @@ var ts;
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6:
+ case 6 /* ESNext */:
return "lib.esnext.full.d.ts";
- case 5:
+ case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
- case 4:
+ case 4 /* ES2017 */:
return "lib.es2017.full.d.ts";
- case 3:
+ case 3 /* ES2016 */:
return "lib.es2016.full.d.ts";
- case 2:
- return "lib.es6.d.ts";
+ case 2 /* ES2015 */:
+ return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
default:
return "lib.d.ts";
}
@@ -10306,6 +11556,7 @@ var ts;
return position >= span.start && position < textSpanEnd(span);
}
ts.textSpanContainsPosition = textSpanContainsPosition;
+ // Returns true if 'span' contains 'other'.
function textSpanContainsTextSpan(span, other) {
return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
}
@@ -10353,6 +11604,7 @@ var ts;
return { start: start, length: length };
}
ts.createTextSpan = createTextSpan;
+ /* @internal */
function createTextRange(pos, end) {
if (end === void 0) { end = pos; }
ts.Debug.assert(end >= pos);
@@ -10379,6 +11631,14 @@ var ts;
}
ts.createTextChangeRange = createTextChangeRange;
ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0);
+ /**
+ * Called to merge all the changes that occurred across several versions of a script snapshot
+ * into a single change. i.e. if a user keeps making successive edits to a script we will
+ * have a text change from V1 to V2, V2 to V3, ..., Vn.
+ *
+ * This function will then merge those changes into a single change range valid between V1 and
+ * Vn.
+ */
function collapseTextChangeRangesAcrossMultipleVersions(changes) {
if (changes.length === 0) {
return ts.unchangedTextChangeRange;
@@ -10386,12 +11646,93 @@ var ts;
if (changes.length === 1) {
return changes[0];
}
+ // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
+ // as it makes things much easier to reason about.
var change0 = changes[0];
var oldStartN = change0.span.start;
var oldEndN = textSpanEnd(change0.span);
var newEndN = oldStartN + change0.newLength;
for (var i = 1; i < changes.length; i++) {
var nextChange = changes[i];
+ // Consider the following case:
+ // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
+ // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
+ // i.e. the span starting at 30 with length 30 is increased to length 40.
+ //
+ // 0 10 20 30 40 50 60 70 80 90 100
+ // -------------------------------------------------------------------------------------------------------
+ // | /
+ // | /----
+ // T1 | /----
+ // | /----
+ // | /----
+ // -------------------------------------------------------------------------------------------------------
+ // | \
+ // | \
+ // T2 | \
+ // | \
+ // | \
+ // -------------------------------------------------------------------------------------------------------
+ //
+ // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
+ // it's just the min of the old and new starts. i.e.:
+ //
+ // 0 10 20 30 40 50 60 70 80 90 100
+ // ------------------------------------------------------------*------------------------------------------
+ // | /
+ // | /----
+ // T1 | /----
+ // | /----
+ // | /----
+ // ----------------------------------------$-------------------$------------------------------------------
+ // . | \
+ // . | \
+ // T2 . | \
+ // . | \
+ // . | \
+ // ----------------------------------------------------------------------*--------------------------------
+ //
+ // (Note the dots represent the newly inferred start.
+ // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
+ // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
+ // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
+ // means:
+ //
+ // 0 10 20 30 40 50 60 70 80 90 100
+ // --------------------------------------------------------------------------------*----------------------
+ // | /
+ // | /----
+ // T1 | /----
+ // | /----
+ // | /----
+ // ------------------------------------------------------------$------------------------------------------
+ // . | \
+ // . | \
+ // T2 . | \
+ // . | \
+ // . | \
+ // ----------------------------------------------------------------------*--------------------------------
+ //
+ // In other words (in this case), we're recognizing that the second edit happened after where the first edit
+ // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
+ // that's the same as if we started at char 80 instead of 60.
+ //
+ // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather
+ // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
+ // first.
+ //
+ // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
+ // semantics: { { start: 10, length: 70 }, newLength: 60 }
+ //
+ // The math then works out as follows.
+ // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
+ // final result like so:
+ //
+ // {
+ // oldStart3: Min(oldStart1, oldStart2),
+ // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
+ // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
+ // }
var oldStart1 = oldStartN;
var oldEnd1 = oldEndN;
var newEnd1 = newEndN;
@@ -10402,13 +11743,13 @@ var ts;
oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
}
- return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN);
+ return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
}
ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
function getTypeParameterOwner(d) {
- if (d && d.kind === 148) {
+ if (d && d.kind === 148 /* TypeParameter */) {
for (var current = d; current; current = current.parent) {
- if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 236) {
+ if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 236 /* InterfaceDeclaration */) {
return current;
}
}
@@ -10416,7 +11757,7 @@ var ts;
}
ts.getTypeParameterOwner = getTypeParameterOwner;
function isParameterPropertyDeclaration(node) {
- return ts.hasModifier(node, 92) && node.parent.kind === 155;
+ return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */;
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function isEmptyBindingPattern(node) {
@@ -10434,7 +11775,7 @@ var ts;
}
ts.isEmptyBindingElement = isEmptyBindingElement;
function walkUpBindingElementsAndPatterns(node) {
- while (node && (node.kind === 182 || ts.isBindingPattern(node))) {
+ while (node && (node.kind === 182 /* BindingElement */ || ts.isBindingPattern(node))) {
node = node.parent;
}
return node;
@@ -10442,35 +11783,46 @@ var ts;
function getCombinedModifierFlags(node) {
node = walkUpBindingElementsAndPatterns(node);
var flags = ts.getModifierFlags(node);
- if (node.kind === 232) {
+ if (node.kind === 232 /* VariableDeclaration */) {
node = node.parent;
}
- if (node && node.kind === 233) {
+ if (node && node.kind === 233 /* VariableDeclarationList */) {
flags |= ts.getModifierFlags(node);
node = node.parent;
}
- if (node && node.kind === 214) {
+ if (node && node.kind === 214 /* VariableStatement */) {
flags |= ts.getModifierFlags(node);
}
return flags;
}
ts.getCombinedModifierFlags = getCombinedModifierFlags;
+ // Returns the node flags for this node and all relevant parent nodes. This is done so that
+ // nodes like variable declarations and binding elements can returned a view of their flags
+ // that includes the modifiers from their container. i.e. flags like export/declare aren't
+ // stored on the variable declaration directly, but on the containing variable statement
+ // (if it has one). Similarly, flags for let/const are store on the variable declaration
+ // list. By calling this function, all those flags are combined so that the client can treat
+ // the node as if it actually had those flags.
function getCombinedNodeFlags(node) {
node = walkUpBindingElementsAndPatterns(node);
var flags = node.flags;
- if (node.kind === 232) {
+ if (node.kind === 232 /* VariableDeclaration */) {
node = node.parent;
}
- if (node && node.kind === 233) {
+ if (node && node.kind === 233 /* VariableDeclarationList */) {
flags |= node.flags;
node = node.parent;
}
- if (node && node.kind === 214) {
+ if (node && node.kind === 214 /* VariableStatement */) {
flags |= node.flags;
}
return flags;
}
ts.getCombinedNodeFlags = getCombinedNodeFlags;
+ /**
+ * Checks to see if the locale is in the appropriate format,
+ * and if it is, attempts to set the appropriate language.
+ */
function validateLocaleAndSetLanguage(locale, sys, errors) {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
@@ -10481,9 +11833,12 @@ var ts;
}
var language = matchResult[1];
var territory = matchResult[3];
+ // First try the entire locale, then fall back to just language if that's all we have.
+ // Either ways do not fail, and fallback to the English diagnostic strings.
if (!trySetLanguageAndTerritory(language, territory, errors)) {
- trySetLanguageAndTerritory(language, undefined, errors);
+ trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
}
+ // Set the UI locale for string collation
ts.setUILocale(locale);
function trySetLanguageAndTerritory(language, territory, errors) {
var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
@@ -10496,6 +11851,7 @@ var ts;
if (!sys.fileExists(filePath)) {
return false;
}
+ // TODO: Add codePage support for readFile?
var fileContents = "";
try {
fileContents = sys.readFile(filePath);
@@ -10507,6 +11863,7 @@ var ts;
return false;
}
try {
+ // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!)
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (_a) {
@@ -10528,8 +11885,13 @@ var ts;
return !nodeTest || nodeTest(node) ? node : undefined;
}
ts.getOriginalNode = getOriginalNode;
+ /**
+ * Gets a value indicating whether a node originated in the parse tree.
+ *
+ * @param node The node to test.
+ */
function isParseTreeNode(node) {
- return (node.flags & 8) === 0;
+ return (node.flags & 8 /* Synthesized */) === 0;
}
ts.isParseTreeNode = isParseTreeNode;
function getParseTreeNode(node, nodeTest) {
@@ -10543,9 +11905,15 @@ var ts;
return undefined;
}
ts.getParseTreeNode = getParseTreeNode;
+ /**
+ * Remove extra underscore from escaped identifier text content.
+ *
+ * @param identifier The escaped identifier text.
+ * @returns The unescaped identifier text.
+ */
function unescapeLeadingUnderscores(identifier) {
var id = identifier;
- return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id;
+ return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
}
ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
function idText(identifier) {
@@ -10556,42 +11924,55 @@ var ts;
return unescapeLeadingUnderscores(symbol.escapedName);
}
ts.symbolName = symbolName;
+ /**
+ * Remove extra underscore from escaped identifier text content.
+ * @deprecated Use `id.text` for the unescaped text.
+ * @param identifier The escaped identifier text.
+ * @returns The unescaped identifier text.
+ */
function unescapeIdentifier(id) {
return id;
}
ts.unescapeIdentifier = unescapeIdentifier;
+ /**
+ * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
+ * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
+ * will be merged with)
+ */
function nameForNamelessJSDocTypedef(declaration) {
var hostNode = declaration.parent.parent;
if (!hostNode) {
return undefined;
}
+ // Covers classes, functions - any named declaration host node
if (ts.isDeclaration(hostNode)) {
return getDeclarationIdentifier(hostNode);
}
+ // Covers remaining cases
switch (hostNode.kind) {
- case 214:
+ case 214 /* VariableStatement */:
if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
}
return undefined;
- case 216:
+ case 216 /* ExpressionStatement */:
var expr = hostNode.expression;
switch (expr.kind) {
- case 185:
+ case 185 /* PropertyAccessExpression */:
return expr.name;
- case 186:
+ case 186 /* ElementAccessExpression */:
var arg = expr.argumentExpression;
if (ts.isIdentifier(arg)) {
return arg;
}
}
return undefined;
- case 1:
+ case 1 /* EndOfFileToken */:
return undefined;
- case 191: {
+ case 191 /* ParenthesizedExpression */: {
return getDeclarationIdentifier(hostNode.expression);
}
- case 228: {
+ case 228 /* LabeledStatement */: {
if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) {
return getDeclarationIdentifier(hostNode.statement);
}
@@ -10609,48 +11990,50 @@ var ts;
return declaration.name || nameForNamelessJSDocTypedef(declaration);
}
ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
+ /** @internal */
function isNamedDeclaration(node) {
- return !!node.name;
+ return !!node.name; // A 'name' property should always be a DeclarationName.
}
ts.isNamedDeclaration = isNamedDeclaration;
+ // TODO: GH#18217 This is often used as if it returns a defined result
function getNameOfDeclaration(declaration) {
if (!declaration) {
return undefined;
}
switch (declaration.kind) {
- case 205:
- case 192:
+ case 205 /* ClassExpression */:
+ case 192 /* FunctionExpression */:
if (!declaration.name) {
return getAssignedName(declaration);
}
break;
- case 71:
+ case 71 /* Identifier */:
return declaration;
- case 299:
- case 293: {
+ case 299 /* JSDocPropertyTag */:
+ case 293 /* JSDocParameterTag */: {
var name = declaration.name;
- if (name.kind === 146) {
+ if (name.kind === 146 /* QualifiedName */) {
return name.right;
}
break;
}
- case 200: {
+ case 200 /* BinaryExpression */: {
var expr = declaration;
switch (ts.getSpecialPropertyAssignmentKind(expr)) {
- case 1:
- case 4:
- case 5:
- case 3:
+ case 1 /* ExportsProperty */:
+ case 4 /* ThisProperty */:
+ case 5 /* Property */:
+ case 3 /* PrototypeProperty */:
return expr.left.name;
default:
return undefined;
}
}
- case 292:
+ case 292 /* JSDocCallbackTag */:
return declaration.name;
- case 298:
+ case 298 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
- case 249: {
+ case 249 /* ExportAssignment */: {
var expression = declaration.expression;
return ts.isIdentifier(expression) ? expression : undefined;
}
@@ -10674,6 +12057,19 @@ var ts;
}
}
}
+ /**
+ * Gets the JSDoc parameter tags for the node if present.
+ *
+ * @remarks Returns any JSDoc param tag that matches the provided
+ * parameter, whether a param tag on a containing function
+ * expression, or a param tag on a variable declaration whose
+ * initializer is the containing function. The tags closest to the
+ * node are returned first, so in the previous example, the param
+ * tag on the containing function expression would be first.
+ *
+ * Does not return tags for binding patterns, because JSDoc matches
+ * parameters by name and binding patterns do not have a name.
+ */
function getJSDocParameterTags(param) {
if (param.name) {
if (ts.isIdentifier(param.name)) {
@@ -10689,34 +12085,48 @@ var ts;
}
}
}
+ // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
return ts.emptyArray;
}
ts.getJSDocParameterTags = getJSDocParameterTags;
+ /**
+ * Return true if the node has JSDoc parameter tags.
+ *
+ * @remarks Includes parameter tags that are not directly on the node,
+ * for example on a variable declaration whose initializer is a function expression.
+ */
function hasJSDocParameterTags(node) {
return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
}
ts.hasJSDocParameterTags = hasJSDocParameterTags;
+ /** Gets the JSDoc augments tag for the node if present */
function getJSDocAugmentsTag(node) {
return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
}
ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
+ /** Gets the JSDoc class tag for the node if present */
function getJSDocClassTag(node) {
return getFirstJSDocTag(node, ts.isJSDocClassTag);
}
ts.getJSDocClassTag = getJSDocClassTag;
+ /** Gets the JSDoc this tag for the node if present */
function getJSDocThisTag(node) {
return getFirstJSDocTag(node, ts.isJSDocThisTag);
}
ts.getJSDocThisTag = getJSDocThisTag;
+ /** Gets the JSDoc return tag for the node if present */
function getJSDocReturnTag(node) {
return getFirstJSDocTag(node, ts.isJSDocReturnTag);
}
ts.getJSDocReturnTag = getJSDocReturnTag;
+ /** Gets the JSDoc template tag for the node if present */
function getJSDocTemplateTag(node) {
return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
}
ts.getJSDocTemplateTag = getJSDocTemplateTag;
+ /** Gets the JSDoc type tag for the node if present and valid */
function getJSDocTypeTag(node) {
+ // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
if (tag && tag.typeExpression && tag.typeExpression.type) {
return tag;
@@ -10724,6 +12134,17 @@ var ts;
return undefined;
}
ts.getJSDocTypeTag = getJSDocTypeTag;
+ /**
+ * Gets the type node for the node if provided via JSDoc.
+ *
+ * @remarks The search includes any JSDoc param tag that relates
+ * to the provided parameter, for example a type tag on the
+ * parameter itself, or a param tag on a containing function
+ * expression, or a param tag on a variable declaration whose
+ * initializer is the containing function. The tags closest to the
+ * node are examined first, so in the previous example, the type
+ * tag directly on the node would be returned.
+ */
function getJSDocType(node) {
var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
if (!tag && ts.isParameter(node)) {
@@ -10732,13 +12153,21 @@ var ts;
return tag && tag.typeExpression && tag.typeExpression.type;
}
ts.getJSDocType = getJSDocType;
+ /**
+ * Gets the return type node for the node if provided via JSDoc's return tag.
+ *
+ * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
+ * gets the type from inside the braces.
+ */
function getJSDocReturnType(node) {
var returnTag = getJSDocReturnTag(node);
return returnTag && returnTag.typeExpression && returnTag.typeExpression.type;
}
ts.getJSDocReturnType = getJSDocReturnType;
+ /** Get all JSDoc tags related to a node, including those on parent nodes. */
function getJSDocTags(node) {
var tags = node.jsDocCache;
+ // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
if (tags === undefined) {
var comments = ts.getJSDocCommentsAndTags(node);
ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
@@ -10747,710 +12176,749 @@ var ts;
return tags;
}
ts.getJSDocTags = getJSDocTags;
+ /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
function getFirstJSDocTag(node, predicate) {
return ts.find(getJSDocTags(node), predicate);
}
+ /** Gets all JSDoc tags of a specified kind, or undefined if not present. */
function getAllJSDocTagsOfKind(node, kind) {
return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
}
ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
})(ts || (ts = {}));
+// Simple node tests of the form `node.kind === SyntaxKind.Foo`.
(function (ts) {
+ // Literals
function isNumericLiteral(node) {
- return node.kind === 8;
+ return node.kind === 8 /* NumericLiteral */;
}
ts.isNumericLiteral = isNumericLiteral;
function isStringLiteral(node) {
- return node.kind === 9;
+ return node.kind === 9 /* StringLiteral */;
}
ts.isStringLiteral = isStringLiteral;
function isJsxText(node) {
- return node.kind === 10;
+ return node.kind === 10 /* JsxText */;
}
ts.isJsxText = isJsxText;
function isRegularExpressionLiteral(node) {
- return node.kind === 12;
+ return node.kind === 12 /* RegularExpressionLiteral */;
}
ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
function isNoSubstitutionTemplateLiteral(node) {
- return node.kind === 13;
+ return node.kind === 13 /* NoSubstitutionTemplateLiteral */;
}
ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
+ // Pseudo-literals
function isTemplateHead(node) {
- return node.kind === 14;
+ return node.kind === 14 /* TemplateHead */;
}
ts.isTemplateHead = isTemplateHead;
function isTemplateMiddle(node) {
- return node.kind === 15;
+ return node.kind === 15 /* TemplateMiddle */;
}
ts.isTemplateMiddle = isTemplateMiddle;
function isTemplateTail(node) {
- return node.kind === 16;
+ return node.kind === 16 /* TemplateTail */;
}
ts.isTemplateTail = isTemplateTail;
function isIdentifier(node) {
- return node.kind === 71;
+ return node.kind === 71 /* Identifier */;
}
ts.isIdentifier = isIdentifier;
+ // Names
function isQualifiedName(node) {
- return node.kind === 146;
+ return node.kind === 146 /* QualifiedName */;
}
ts.isQualifiedName = isQualifiedName;
function isComputedPropertyName(node) {
- return node.kind === 147;
+ return node.kind === 147 /* ComputedPropertyName */;
}
ts.isComputedPropertyName = isComputedPropertyName;
+ // Signature elements
function isTypeParameterDeclaration(node) {
- return node.kind === 148;
+ return node.kind === 148 /* TypeParameter */;
}
ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
function isParameter(node) {
- return node.kind === 149;
+ return node.kind === 149 /* Parameter */;
}
ts.isParameter = isParameter;
function isDecorator(node) {
- return node.kind === 150;
+ return node.kind === 150 /* Decorator */;
}
ts.isDecorator = isDecorator;
+ // TypeMember
function isPropertySignature(node) {
- return node.kind === 151;
+ return node.kind === 151 /* PropertySignature */;
}
ts.isPropertySignature = isPropertySignature;
function isPropertyDeclaration(node) {
- return node.kind === 152;
+ return node.kind === 152 /* PropertyDeclaration */;
}
ts.isPropertyDeclaration = isPropertyDeclaration;
function isMethodSignature(node) {
- return node.kind === 153;
+ return node.kind === 153 /* MethodSignature */;
}
ts.isMethodSignature = isMethodSignature;
function isMethodDeclaration(node) {
- return node.kind === 154;
+ return node.kind === 154 /* MethodDeclaration */;
}
ts.isMethodDeclaration = isMethodDeclaration;
function isConstructorDeclaration(node) {
- return node.kind === 155;
+ return node.kind === 155 /* Constructor */;
}
ts.isConstructorDeclaration = isConstructorDeclaration;
function isGetAccessorDeclaration(node) {
- return node.kind === 156;
+ return node.kind === 156 /* GetAccessor */;
}
ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
function isSetAccessorDeclaration(node) {
- return node.kind === 157;
+ return node.kind === 157 /* SetAccessor */;
}
ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
function isCallSignatureDeclaration(node) {
- return node.kind === 158;
+ return node.kind === 158 /* CallSignature */;
}
ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
function isConstructSignatureDeclaration(node) {
- return node.kind === 159;
+ return node.kind === 159 /* ConstructSignature */;
}
ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
function isIndexSignatureDeclaration(node) {
- return node.kind === 160;
+ return node.kind === 160 /* IndexSignature */;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ /* @internal */
function isGetOrSetAccessorDeclaration(node) {
- return node.kind === 157 || node.kind === 156;
+ return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */;
}
ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
+ // Type
function isTypePredicateNode(node) {
- return node.kind === 161;
+ return node.kind === 161 /* TypePredicate */;
}
ts.isTypePredicateNode = isTypePredicateNode;
function isTypeReferenceNode(node) {
- return node.kind === 162;
+ return node.kind === 162 /* TypeReference */;
}
ts.isTypeReferenceNode = isTypeReferenceNode;
function isFunctionTypeNode(node) {
- return node.kind === 163;
+ return node.kind === 163 /* FunctionType */;
}
ts.isFunctionTypeNode = isFunctionTypeNode;
function isConstructorTypeNode(node) {
- return node.kind === 164;
+ return node.kind === 164 /* ConstructorType */;
}
ts.isConstructorTypeNode = isConstructorTypeNode;
function isTypeQueryNode(node) {
- return node.kind === 165;
+ return node.kind === 165 /* TypeQuery */;
}
ts.isTypeQueryNode = isTypeQueryNode;
function isTypeLiteralNode(node) {
- return node.kind === 166;
+ return node.kind === 166 /* TypeLiteral */;
}
ts.isTypeLiteralNode = isTypeLiteralNode;
function isArrayTypeNode(node) {
- return node.kind === 167;
+ return node.kind === 167 /* ArrayType */;
}
ts.isArrayTypeNode = isArrayTypeNode;
function isTupleTypeNode(node) {
- return node.kind === 168;
+ return node.kind === 168 /* TupleType */;
}
ts.isTupleTypeNode = isTupleTypeNode;
function isUnionTypeNode(node) {
- return node.kind === 169;
+ return node.kind === 169 /* UnionType */;
}
ts.isUnionTypeNode = isUnionTypeNode;
function isIntersectionTypeNode(node) {
- return node.kind === 170;
+ return node.kind === 170 /* IntersectionType */;
}
ts.isIntersectionTypeNode = isIntersectionTypeNode;
function isConditionalTypeNode(node) {
- return node.kind === 171;
+ return node.kind === 171 /* ConditionalType */;
}
ts.isConditionalTypeNode = isConditionalTypeNode;
function isInferTypeNode(node) {
- return node.kind === 172;
+ return node.kind === 172 /* InferType */;
}
ts.isInferTypeNode = isInferTypeNode;
function isParenthesizedTypeNode(node) {
- return node.kind === 173;
+ return node.kind === 173 /* ParenthesizedType */;
}
ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
function isThisTypeNode(node) {
- return node.kind === 174;
+ return node.kind === 174 /* ThisType */;
}
ts.isThisTypeNode = isThisTypeNode;
function isTypeOperatorNode(node) {
- return node.kind === 175;
+ return node.kind === 175 /* TypeOperator */;
}
ts.isTypeOperatorNode = isTypeOperatorNode;
function isIndexedAccessTypeNode(node) {
- return node.kind === 176;
+ return node.kind === 176 /* IndexedAccessType */;
}
ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
function isMappedTypeNode(node) {
- return node.kind === 177;
+ return node.kind === 177 /* MappedType */;
}
ts.isMappedTypeNode = isMappedTypeNode;
function isLiteralTypeNode(node) {
- return node.kind === 178;
+ return node.kind === 178 /* LiteralType */;
}
ts.isLiteralTypeNode = isLiteralTypeNode;
function isImportTypeNode(node) {
- return node.kind === 179;
+ return node.kind === 179 /* ImportType */;
}
ts.isImportTypeNode = isImportTypeNode;
+ // Binding patterns
function isObjectBindingPattern(node) {
- return node.kind === 180;
+ return node.kind === 180 /* ObjectBindingPattern */;
}
ts.isObjectBindingPattern = isObjectBindingPattern;
function isArrayBindingPattern(node) {
- return node.kind === 181;
+ return node.kind === 181 /* ArrayBindingPattern */;
}
ts.isArrayBindingPattern = isArrayBindingPattern;
function isBindingElement(node) {
- return node.kind === 182;
+ return node.kind === 182 /* BindingElement */;
}
ts.isBindingElement = isBindingElement;
+ // Expression
function isArrayLiteralExpression(node) {
- return node.kind === 183;
+ return node.kind === 183 /* ArrayLiteralExpression */;
}
ts.isArrayLiteralExpression = isArrayLiteralExpression;
function isObjectLiteralExpression(node) {
- return node.kind === 184;
+ return node.kind === 184 /* ObjectLiteralExpression */;
}
ts.isObjectLiteralExpression = isObjectLiteralExpression;
function isPropertyAccessExpression(node) {
- return node.kind === 185;
+ return node.kind === 185 /* PropertyAccessExpression */;
}
ts.isPropertyAccessExpression = isPropertyAccessExpression;
function isElementAccessExpression(node) {
- return node.kind === 186;
+ return node.kind === 186 /* ElementAccessExpression */;
}
ts.isElementAccessExpression = isElementAccessExpression;
function isCallExpression(node) {
- return node.kind === 187;
+ return node.kind === 187 /* CallExpression */;
}
ts.isCallExpression = isCallExpression;
function isNewExpression(node) {
- return node.kind === 188;
+ return node.kind === 188 /* NewExpression */;
}
ts.isNewExpression = isNewExpression;
function isTaggedTemplateExpression(node) {
- return node.kind === 189;
+ return node.kind === 189 /* TaggedTemplateExpression */;
}
ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
function isTypeAssertion(node) {
- return node.kind === 190;
+ return node.kind === 190 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
function isParenthesizedExpression(node) {
- return node.kind === 191;
+ return node.kind === 191 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 302) {
+ while (node.kind === 302 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
}
ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
function isFunctionExpression(node) {
- return node.kind === 192;
+ return node.kind === 192 /* FunctionExpression */;
}
ts.isFunctionExpression = isFunctionExpression;
function isArrowFunction(node) {
- return node.kind === 193;
+ return node.kind === 193 /* ArrowFunction */;
}
ts.isArrowFunction = isArrowFunction;
function isDeleteExpression(node) {
- return node.kind === 194;
+ return node.kind === 194 /* DeleteExpression */;
}
ts.isDeleteExpression = isDeleteExpression;
function isTypeOfExpression(node) {
- return node.kind === 195;
+ return node.kind === 195 /* TypeOfExpression */;
}
ts.isTypeOfExpression = isTypeOfExpression;
function isVoidExpression(node) {
- return node.kind === 196;
+ return node.kind === 196 /* VoidExpression */;
}
ts.isVoidExpression = isVoidExpression;
function isAwaitExpression(node) {
- return node.kind === 197;
+ return node.kind === 197 /* AwaitExpression */;
}
ts.isAwaitExpression = isAwaitExpression;
function isPrefixUnaryExpression(node) {
- return node.kind === 198;
+ return node.kind === 198 /* PrefixUnaryExpression */;
}
ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
function isPostfixUnaryExpression(node) {
- return node.kind === 199;
+ return node.kind === 199 /* PostfixUnaryExpression */;
}
ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
function isBinaryExpression(node) {
- return node.kind === 200;
+ return node.kind === 200 /* BinaryExpression */;
}
ts.isBinaryExpression = isBinaryExpression;
function isConditionalExpression(node) {
- return node.kind === 201;
+ return node.kind === 201 /* ConditionalExpression */;
}
ts.isConditionalExpression = isConditionalExpression;
function isTemplateExpression(node) {
- return node.kind === 202;
+ return node.kind === 202 /* TemplateExpression */;
}
ts.isTemplateExpression = isTemplateExpression;
function isYieldExpression(node) {
- return node.kind === 203;
+ return node.kind === 203 /* YieldExpression */;
}
ts.isYieldExpression = isYieldExpression;
function isSpreadElement(node) {
- return node.kind === 204;
+ return node.kind === 204 /* SpreadElement */;
}
ts.isSpreadElement = isSpreadElement;
function isClassExpression(node) {
- return node.kind === 205;
+ return node.kind === 205 /* ClassExpression */;
}
ts.isClassExpression = isClassExpression;
function isOmittedExpression(node) {
- return node.kind === 206;
+ return node.kind === 206 /* OmittedExpression */;
}
ts.isOmittedExpression = isOmittedExpression;
function isExpressionWithTypeArguments(node) {
- return node.kind === 207;
+ return node.kind === 207 /* ExpressionWithTypeArguments */;
}
ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
function isAsExpression(node) {
- return node.kind === 208;
+ return node.kind === 208 /* AsExpression */;
}
ts.isAsExpression = isAsExpression;
function isNonNullExpression(node) {
- return node.kind === 209;
+ return node.kind === 209 /* NonNullExpression */;
}
ts.isNonNullExpression = isNonNullExpression;
function isMetaProperty(node) {
- return node.kind === 210;
+ return node.kind === 210 /* MetaProperty */;
}
ts.isMetaProperty = isMetaProperty;
+ // Misc
function isTemplateSpan(node) {
- return node.kind === 211;
+ return node.kind === 211 /* TemplateSpan */;
}
ts.isTemplateSpan = isTemplateSpan;
function isSemicolonClassElement(node) {
- return node.kind === 212;
+ return node.kind === 212 /* SemicolonClassElement */;
}
ts.isSemicolonClassElement = isSemicolonClassElement;
+ // Block
function isBlock(node) {
- return node.kind === 213;
+ return node.kind === 213 /* Block */;
}
ts.isBlock = isBlock;
function isVariableStatement(node) {
- return node.kind === 214;
+ return node.kind === 214 /* VariableStatement */;
}
ts.isVariableStatement = isVariableStatement;
function isEmptyStatement(node) {
- return node.kind === 215;
+ return node.kind === 215 /* EmptyStatement */;
}
ts.isEmptyStatement = isEmptyStatement;
function isExpressionStatement(node) {
- return node.kind === 216;
+ return node.kind === 216 /* ExpressionStatement */;
}
ts.isExpressionStatement = isExpressionStatement;
function isIfStatement(node) {
- return node.kind === 217;
+ return node.kind === 217 /* IfStatement */;
}
ts.isIfStatement = isIfStatement;
function isDoStatement(node) {
- return node.kind === 218;
+ return node.kind === 218 /* DoStatement */;
}
ts.isDoStatement = isDoStatement;
function isWhileStatement(node) {
- return node.kind === 219;
+ return node.kind === 219 /* WhileStatement */;
}
ts.isWhileStatement = isWhileStatement;
function isForStatement(node) {
- return node.kind === 220;
+ return node.kind === 220 /* ForStatement */;
}
ts.isForStatement = isForStatement;
function isForInStatement(node) {
- return node.kind === 221;
+ return node.kind === 221 /* ForInStatement */;
}
ts.isForInStatement = isForInStatement;
function isForOfStatement(node) {
- return node.kind === 222;
+ return node.kind === 222 /* ForOfStatement */;
}
ts.isForOfStatement = isForOfStatement;
function isContinueStatement(node) {
- return node.kind === 223;
+ return node.kind === 223 /* ContinueStatement */;
}
ts.isContinueStatement = isContinueStatement;
function isBreakStatement(node) {
- return node.kind === 224;
+ return node.kind === 224 /* BreakStatement */;
}
ts.isBreakStatement = isBreakStatement;
function isBreakOrContinueStatement(node) {
- return node.kind === 224 || node.kind === 223;
+ return node.kind === 224 /* BreakStatement */ || node.kind === 223 /* ContinueStatement */;
}
ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
function isReturnStatement(node) {
- return node.kind === 225;
+ return node.kind === 225 /* ReturnStatement */;
}
ts.isReturnStatement = isReturnStatement;
function isWithStatement(node) {
- return node.kind === 226;
+ return node.kind === 226 /* WithStatement */;
}
ts.isWithStatement = isWithStatement;
function isSwitchStatement(node) {
- return node.kind === 227;
+ return node.kind === 227 /* SwitchStatement */;
}
ts.isSwitchStatement = isSwitchStatement;
function isLabeledStatement(node) {
- return node.kind === 228;
+ return node.kind === 228 /* LabeledStatement */;
}
ts.isLabeledStatement = isLabeledStatement;
function isThrowStatement(node) {
- return node.kind === 229;
+ return node.kind === 229 /* ThrowStatement */;
}
ts.isThrowStatement = isThrowStatement;
function isTryStatement(node) {
- return node.kind === 230;
+ return node.kind === 230 /* TryStatement */;
}
ts.isTryStatement = isTryStatement;
function isDebuggerStatement(node) {
- return node.kind === 231;
+ return node.kind === 231 /* DebuggerStatement */;
}
ts.isDebuggerStatement = isDebuggerStatement;
function isVariableDeclaration(node) {
- return node.kind === 232;
+ return node.kind === 232 /* VariableDeclaration */;
}
ts.isVariableDeclaration = isVariableDeclaration;
function isVariableDeclarationList(node) {
- return node.kind === 233;
+ return node.kind === 233 /* VariableDeclarationList */;
}
ts.isVariableDeclarationList = isVariableDeclarationList;
function isFunctionDeclaration(node) {
- return node.kind === 234;
+ return node.kind === 234 /* FunctionDeclaration */;
}
ts.isFunctionDeclaration = isFunctionDeclaration;
function isClassDeclaration(node) {
- return node.kind === 235;
+ return node.kind === 235 /* ClassDeclaration */;
}
ts.isClassDeclaration = isClassDeclaration;
function isInterfaceDeclaration(node) {
- return node.kind === 236;
+ return node.kind === 236 /* InterfaceDeclaration */;
}
ts.isInterfaceDeclaration = isInterfaceDeclaration;
function isTypeAliasDeclaration(node) {
- return node.kind === 237;
+ return node.kind === 237 /* TypeAliasDeclaration */;
}
ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
function isEnumDeclaration(node) {
- return node.kind === 238;
+ return node.kind === 238 /* EnumDeclaration */;
}
ts.isEnumDeclaration = isEnumDeclaration;
function isModuleDeclaration(node) {
- return node.kind === 239;
+ return node.kind === 239 /* ModuleDeclaration */;
}
ts.isModuleDeclaration = isModuleDeclaration;
function isModuleBlock(node) {
- return node.kind === 240;
+ return node.kind === 240 /* ModuleBlock */;
}
ts.isModuleBlock = isModuleBlock;
function isCaseBlock(node) {
- return node.kind === 241;
+ return node.kind === 241 /* CaseBlock */;
}
ts.isCaseBlock = isCaseBlock;
function isNamespaceExportDeclaration(node) {
- return node.kind === 242;
+ return node.kind === 242 /* NamespaceExportDeclaration */;
}
ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
function isImportEqualsDeclaration(node) {
- return node.kind === 243;
+ return node.kind === 243 /* ImportEqualsDeclaration */;
}
ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
function isImportDeclaration(node) {
- return node.kind === 244;
+ return node.kind === 244 /* ImportDeclaration */;
}
ts.isImportDeclaration = isImportDeclaration;
function isImportClause(node) {
- return node.kind === 245;
+ return node.kind === 245 /* ImportClause */;
}
ts.isImportClause = isImportClause;
function isNamespaceImport(node) {
- return node.kind === 246;
+ return node.kind === 246 /* NamespaceImport */;
}
ts.isNamespaceImport = isNamespaceImport;
function isNamedImports(node) {
- return node.kind === 247;
+ return node.kind === 247 /* NamedImports */;
}
ts.isNamedImports = isNamedImports;
function isImportSpecifier(node) {
- return node.kind === 248;
+ return node.kind === 248 /* ImportSpecifier */;
}
ts.isImportSpecifier = isImportSpecifier;
function isExportAssignment(node) {
- return node.kind === 249;
+ return node.kind === 249 /* ExportAssignment */;
}
ts.isExportAssignment = isExportAssignment;
function isExportDeclaration(node) {
- return node.kind === 250;
+ return node.kind === 250 /* ExportDeclaration */;
}
ts.isExportDeclaration = isExportDeclaration;
function isNamedExports(node) {
- return node.kind === 251;
+ return node.kind === 251 /* NamedExports */;
}
ts.isNamedExports = isNamedExports;
function isExportSpecifier(node) {
- return node.kind === 252;
+ return node.kind === 252 /* ExportSpecifier */;
}
ts.isExportSpecifier = isExportSpecifier;
function isMissingDeclaration(node) {
- return node.kind === 253;
+ return node.kind === 253 /* MissingDeclaration */;
}
ts.isMissingDeclaration = isMissingDeclaration;
+ // Module References
function isExternalModuleReference(node) {
- return node.kind === 254;
+ return node.kind === 254 /* ExternalModuleReference */;
}
ts.isExternalModuleReference = isExternalModuleReference;
+ // JSX
function isJsxElement(node) {
- return node.kind === 255;
+ return node.kind === 255 /* JsxElement */;
}
ts.isJsxElement = isJsxElement;
function isJsxSelfClosingElement(node) {
- return node.kind === 256;
+ return node.kind === 256 /* JsxSelfClosingElement */;
}
ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
function isJsxOpeningElement(node) {
- return node.kind === 257;
+ return node.kind === 257 /* JsxOpeningElement */;
}
ts.isJsxOpeningElement = isJsxOpeningElement;
function isJsxClosingElement(node) {
- return node.kind === 258;
+ return node.kind === 258 /* JsxClosingElement */;
}
ts.isJsxClosingElement = isJsxClosingElement;
function isJsxFragment(node) {
- return node.kind === 259;
+ return node.kind === 259 /* JsxFragment */;
}
ts.isJsxFragment = isJsxFragment;
function isJsxOpeningFragment(node) {
- return node.kind === 260;
+ return node.kind === 260 /* JsxOpeningFragment */;
}
ts.isJsxOpeningFragment = isJsxOpeningFragment;
function isJsxClosingFragment(node) {
- return node.kind === 261;
+ return node.kind === 261 /* JsxClosingFragment */;
}
ts.isJsxClosingFragment = isJsxClosingFragment;
function isJsxAttribute(node) {
- return node.kind === 262;
+ return node.kind === 262 /* JsxAttribute */;
}
ts.isJsxAttribute = isJsxAttribute;
function isJsxAttributes(node) {
- return node.kind === 263;
+ return node.kind === 263 /* JsxAttributes */;
}
ts.isJsxAttributes = isJsxAttributes;
function isJsxSpreadAttribute(node) {
- return node.kind === 264;
+ return node.kind === 264 /* JsxSpreadAttribute */;
}
ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
function isJsxExpression(node) {
- return node.kind === 265;
+ return node.kind === 265 /* JsxExpression */;
}
ts.isJsxExpression = isJsxExpression;
+ // Clauses
function isCaseClause(node) {
- return node.kind === 266;
+ return node.kind === 266 /* CaseClause */;
}
ts.isCaseClause = isCaseClause;
function isDefaultClause(node) {
- return node.kind === 267;
+ return node.kind === 267 /* DefaultClause */;
}
ts.isDefaultClause = isDefaultClause;
function isHeritageClause(node) {
- return node.kind === 268;
+ return node.kind === 268 /* HeritageClause */;
}
ts.isHeritageClause = isHeritageClause;
function isCatchClause(node) {
- return node.kind === 269;
+ return node.kind === 269 /* CatchClause */;
}
ts.isCatchClause = isCatchClause;
+ // Property assignments
function isPropertyAssignment(node) {
- return node.kind === 270;
+ return node.kind === 270 /* PropertyAssignment */;
}
ts.isPropertyAssignment = isPropertyAssignment;
function isShorthandPropertyAssignment(node) {
- return node.kind === 271;
+ return node.kind === 271 /* ShorthandPropertyAssignment */;
}
ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
function isSpreadAssignment(node) {
- return node.kind === 272;
+ return node.kind === 272 /* SpreadAssignment */;
}
ts.isSpreadAssignment = isSpreadAssignment;
+ // Enum
function isEnumMember(node) {
- return node.kind === 273;
+ return node.kind === 273 /* EnumMember */;
}
ts.isEnumMember = isEnumMember;
+ // Top-level nodes
function isSourceFile(node) {
- return node.kind === 274;
+ return node.kind === 274 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 275;
+ return node.kind === 275 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 276;
+ return node.kind === 276 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ // JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 278;
+ return node.kind === 278 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 279;
+ return node.kind === 279 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 280;
+ return node.kind === 280 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 281;
+ return node.kind === 281 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 282;
+ return node.kind === 282 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 283;
+ return node.kind === 283 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 284;
+ return node.kind === 284 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 285;
+ return node.kind === 285 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 286;
+ return node.kind === 286 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 290;
+ return node.kind === 290 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 291;
+ return node.kind === 291 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocThisTag(node) {
- return node.kind === 295;
+ return node.kind === 295 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 293;
+ return node.kind === 293 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 294;
+ return node.kind === 294 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 296;
+ return node.kind === 296 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 297;
+ return node.kind === 297 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 298;
+ return node.kind === 298 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 299;
+ return node.kind === 299 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 299 || node.kind === 293;
+ return node.kind === 299 /* JSDocPropertyTag */ || node.kind === 293 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 287;
+ return node.kind === 287 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 292;
+ return node.kind === 292 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 288;
+ return node.kind === 288 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
+// Node tests
+//
+// All node tests in the following list should *not* reference parent pointers so that
+// they may be used with transformations.
(function (ts) {
+ /* @internal */
function isSyntaxList(n) {
- return n.kind === 300;
+ return n.kind === 300 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
+ /* @internal */
function isNode(node) {
return isNodeKind(node.kind);
}
ts.isNode = isNode;
+ /* @internal */
function isNodeKind(kind) {
- return kind >= 146;
+ return kind >= 146 /* FirstNode */;
}
ts.isNodeKind = isNodeKind;
+ /**
+ * True if node is of some token syntax kind.
+ * For example, this is true for an IfKeyword but not for an IfStatement.
+ * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
+ */
function isToken(n) {
- return n.kind >= 0 && n.kind <= 145;
+ return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */;
}
ts.isToken = isToken;
+ // Node Arrays
+ /* @internal */
function isNodeArray(array) {
return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
}
ts.isNodeArray = isNodeArray;
+ // Literals
+ /* @internal */
function isLiteralKind(kind) {
- return 8 <= kind && kind <= 13;
+ return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */;
}
ts.isLiteralKind = isLiteralKind;
function isLiteralExpression(node) {
return isLiteralKind(node.kind);
}
ts.isLiteralExpression = isLiteralExpression;
+ // Pseudo-literals
+ /* @internal */
function isTemplateLiteralKind(kind) {
- return 13 <= kind && kind <= 16;
+ return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */;
}
ts.isTemplateLiteralKind = isTemplateLiteralKind;
function isTemplateLiteralToken(node) {
@@ -11459,42 +12927,48 @@ var ts;
ts.isTemplateLiteralToken = isTemplateLiteralToken;
function isTemplateMiddleOrTemplateTail(node) {
var kind = node.kind;
- return kind === 15
- || kind === 16;
+ return kind === 15 /* TemplateMiddle */
+ || kind === 16 /* TemplateTail */;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
function isStringTextContainingNode(node) {
- return node.kind === 9 || isTemplateLiteralKind(node.kind);
+ return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
}
ts.isStringTextContainingNode = isStringTextContainingNode;
+ // Identifiers
+ /* @internal */
function isGeneratedIdentifier(node) {
- return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0;
+ return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
}
ts.isGeneratedIdentifier = isGeneratedIdentifier;
+ // Keywords
+ /* @internal */
function isModifierKind(token) {
switch (token) {
- case 117:
- case 120:
- case 76:
- case 124:
- case 79:
- case 84:
- case 114:
- case 112:
- case 113:
- case 132:
- case 115:
+ case 117 /* AbstractKeyword */:
+ case 120 /* AsyncKeyword */:
+ case 76 /* ConstKeyword */:
+ case 124 /* DeclareKeyword */:
+ case 79 /* DefaultKeyword */:
+ case 84 /* ExportKeyword */:
+ case 114 /* PublicKeyword */:
+ case 112 /* PrivateKeyword */:
+ case 113 /* ProtectedKeyword */:
+ case 132 /* ReadonlyKeyword */:
+ case 115 /* StaticKeyword */:
return true;
}
return false;
}
ts.isModifierKind = isModifierKind;
+ /* @internal */
function isParameterPropertyModifier(kind) {
- return !!(ts.modifierToFlag(kind) & 92);
+ return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
}
ts.isParameterPropertyModifier = isParameterPropertyModifier;
+ /* @internal */
function isClassMemberModifier(idToken) {
- return isParameterPropertyModifier(idToken) || idToken === 115;
+ return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */;
}
ts.isClassMemberModifier = isClassMemberModifier;
function isModifier(node) {
@@ -11503,104 +12977,111 @@ var ts;
ts.isModifier = isModifier;
function isEntityName(node) {
var kind = node.kind;
- return kind === 146
- || kind === 71;
+ return kind === 146 /* QualifiedName */
+ || kind === 71 /* Identifier */;
}
ts.isEntityName = isEntityName;
function isPropertyName(node) {
var kind = node.kind;
- return kind === 71
- || kind === 9
- || kind === 8
- || kind === 147;
+ return kind === 71 /* Identifier */
+ || kind === 9 /* StringLiteral */
+ || kind === 8 /* NumericLiteral */
+ || kind === 147 /* ComputedPropertyName */;
}
ts.isPropertyName = isPropertyName;
function isBindingName(node) {
var kind = node.kind;
- return kind === 71
- || kind === 180
- || kind === 181;
+ return kind === 71 /* Identifier */
+ || kind === 180 /* ObjectBindingPattern */
+ || kind === 181 /* ArrayBindingPattern */;
}
ts.isBindingName = isBindingName;
+ // Functions
function isFunctionLike(node) {
return node && isFunctionLikeKind(node.kind);
}
ts.isFunctionLike = isFunctionLike;
+ /* @internal */
function isFunctionLikeDeclaration(node) {
return node && isFunctionLikeDeclarationKind(node.kind);
}
ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
function isFunctionLikeDeclarationKind(kind) {
switch (kind) {
- case 234:
- case 154:
- case 155:
- case 156:
- case 157:
- case 192:
- case 193:
+ case 234 /* FunctionDeclaration */:
+ case 154 /* MethodDeclaration */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
return true;
default:
return false;
}
}
+ /* @internal */
function isFunctionLikeKind(kind) {
switch (kind) {
- case 153:
- case 158:
- case 288:
- case 159:
- case 160:
- case 163:
- case 284:
- case 164:
+ case 153 /* MethodSignature */:
+ case 158 /* CallSignature */:
+ case 288 /* JSDocSignature */:
+ case 159 /* ConstructSignature */:
+ case 160 /* IndexSignature */:
+ case 163 /* FunctionType */:
+ case 284 /* JSDocFunctionType */:
+ case 164 /* ConstructorType */:
return true;
default:
return isFunctionLikeDeclarationKind(kind);
}
}
ts.isFunctionLikeKind = isFunctionLikeKind;
+ /* @internal */
function isFunctionOrModuleBlock(node) {
return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
}
ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
+ // Classes
function isClassElement(node) {
var kind = node.kind;
- return kind === 155
- || kind === 152
- || kind === 154
- || kind === 156
- || kind === 157
- || kind === 160
- || kind === 212;
+ return kind === 155 /* Constructor */
+ || kind === 152 /* PropertyDeclaration */
+ || kind === 154 /* MethodDeclaration */
+ || kind === 156 /* GetAccessor */
+ || kind === 157 /* SetAccessor */
+ || kind === 160 /* IndexSignature */
+ || kind === 212 /* SemicolonClassElement */;
}
ts.isClassElement = isClassElement;
function isClassLike(node) {
- return node && (node.kind === 235 || node.kind === 205);
+ return node && (node.kind === 235 /* ClassDeclaration */ || node.kind === 205 /* ClassExpression */);
}
ts.isClassLike = isClassLike;
function isAccessor(node) {
- return node && (node.kind === 156 || node.kind === 157);
+ return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */);
}
ts.isAccessor = isAccessor;
+ /* @internal */
function isMethodOrAccessor(node) {
switch (node.kind) {
- case 154:
- case 156:
- case 157:
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
return true;
default:
return false;
}
}
ts.isMethodOrAccessor = isMethodOrAccessor;
+ // Type members
function isTypeElement(node) {
var kind = node.kind;
- return kind === 159
- || kind === 158
- || kind === 151
- || kind === 153
- || kind === 160;
+ return kind === 159 /* ConstructSignature */
+ || kind === 158 /* CallSignature */
+ || kind === 151 /* PropertySignature */
+ || kind === 153 /* MethodSignature */
+ || kind === 160 /* IndexSignature */;
}
ts.isTypeElement = isTypeElement;
function isClassOrTypeElement(node) {
@@ -11609,125 +13090,153 @@ var ts;
ts.isClassOrTypeElement = isClassOrTypeElement;
function isObjectLiteralElementLike(node) {
var kind = node.kind;
- return kind === 270
- || kind === 271
- || kind === 272
- || kind === 154
- || kind === 156
- || kind === 157;
+ return kind === 270 /* PropertyAssignment */
+ || kind === 271 /* ShorthandPropertyAssignment */
+ || kind === 272 /* SpreadAssignment */
+ || kind === 154 /* MethodDeclaration */
+ || kind === 156 /* GetAccessor */
+ || kind === 157 /* SetAccessor */;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
+ // Type
function isTypeNodeKind(kind) {
- return (kind >= 161 && kind <= 179)
- || kind === 119
- || kind === 142
- || kind === 134
- || kind === 135
- || kind === 122
- || kind === 137
- || kind === 138
- || kind === 99
- || kind === 105
- || kind === 140
- || kind === 95
- || kind === 131
- || kind === 207
- || kind === 279
- || kind === 280
- || kind === 281
- || kind === 282
- || kind === 283
- || kind === 284
- || kind === 285;
+ return (kind >= 161 /* FirstTypeNode */ && kind <= 179 /* LastTypeNode */)
+ || kind === 119 /* AnyKeyword */
+ || kind === 142 /* UnknownKeyword */
+ || kind === 134 /* NumberKeyword */
+ || kind === 135 /* ObjectKeyword */
+ || kind === 122 /* BooleanKeyword */
+ || kind === 137 /* StringKeyword */
+ || kind === 138 /* SymbolKeyword */
+ || kind === 99 /* ThisKeyword */
+ || kind === 105 /* VoidKeyword */
+ || kind === 140 /* UndefinedKeyword */
+ || kind === 95 /* NullKeyword */
+ || kind === 131 /* NeverKeyword */
+ || kind === 207 /* ExpressionWithTypeArguments */
+ || kind === 279 /* JSDocAllType */
+ || kind === 280 /* JSDocUnknownType */
+ || kind === 281 /* JSDocNullableType */
+ || kind === 282 /* JSDocNonNullableType */
+ || kind === 283 /* JSDocOptionalType */
+ || kind === 284 /* JSDocFunctionType */
+ || kind === 285 /* JSDocVariadicType */;
}
+ /**
+ * Node test that determines whether a node is a valid type node.
+ * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
+ * of a TypeNode.
+ */
function isTypeNode(node) {
return isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
switch (node.kind) {
- case 163:
- case 164:
+ case 163 /* FunctionType */:
+ case 164 /* ConstructorType */:
return true;
}
return false;
}
ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
+ // Binding patterns
+ /* @internal */
function isBindingPattern(node) {
if (node) {
var kind = node.kind;
- return kind === 181
- || kind === 180;
+ return kind === 181 /* ArrayBindingPattern */
+ || kind === 180 /* ObjectBindingPattern */;
}
return false;
}
ts.isBindingPattern = isBindingPattern;
+ /* @internal */
function isAssignmentPattern(node) {
var kind = node.kind;
- return kind === 183
- || kind === 184;
+ return kind === 183 /* ArrayLiteralExpression */
+ || kind === 184 /* ObjectLiteralExpression */;
}
ts.isAssignmentPattern = isAssignmentPattern;
+ /* @internal */
function isArrayBindingElement(node) {
var kind = node.kind;
- return kind === 182
- || kind === 206;
+ return kind === 182 /* BindingElement */
+ || kind === 206 /* OmittedExpression */;
}
ts.isArrayBindingElement = isArrayBindingElement;
+ /**
+ * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
+ */
+ /* @internal */
function isDeclarationBindingElement(bindingElement) {
switch (bindingElement.kind) {
- case 232:
- case 149:
- case 182:
+ case 232 /* VariableDeclaration */:
+ case 149 /* Parameter */:
+ case 182 /* BindingElement */:
return true;
}
return false;
}
ts.isDeclarationBindingElement = isDeclarationBindingElement;
+ /**
+ * Determines whether a node is a BindingOrAssignmentPattern
+ */
+ /* @internal */
function isBindingOrAssignmentPattern(node) {
return isObjectBindingOrAssignmentPattern(node)
|| isArrayBindingOrAssignmentPattern(node);
}
ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
+ /**
+ * Determines whether a node is an ObjectBindingOrAssignmentPattern
+ */
+ /* @internal */
function isObjectBindingOrAssignmentPattern(node) {
switch (node.kind) {
- case 180:
- case 184:
+ case 180 /* ObjectBindingPattern */:
+ case 184 /* ObjectLiteralExpression */:
return true;
}
return false;
}
ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
+ /**
+ * Determines whether a node is an ArrayBindingOrAssignmentPattern
+ */
+ /* @internal */
function isArrayBindingOrAssignmentPattern(node) {
switch (node.kind) {
- case 181:
- case 183:
+ case 181 /* ArrayBindingPattern */:
+ case 183 /* ArrayLiteralExpression */:
return true;
}
return false;
}
ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
+ /* @internal */
function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
var kind = node.kind;
- return kind === 185
- || kind === 146
- || kind === 179;
+ return kind === 185 /* PropertyAccessExpression */
+ || kind === 146 /* QualifiedName */
+ || kind === 179 /* ImportType */;
}
ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
+ // Expression
function isPropertyAccessOrQualifiedName(node) {
var kind = node.kind;
- return kind === 185
- || kind === 146;
+ return kind === 185 /* PropertyAccessExpression */
+ || kind === 146 /* QualifiedName */;
}
ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
function isCallLikeExpression(node) {
switch (node.kind) {
- case 257:
- case 256:
- case 187:
- case 188:
- case 189:
- case 150:
+ case 257 /* JsxOpeningElement */:
+ case 256 /* JsxSelfClosingElement */:
+ case 187 /* CallExpression */:
+ case 188 /* NewExpression */:
+ case 189 /* TaggedTemplateExpression */:
+ case 150 /* Decorator */:
return true;
default:
return false;
@@ -11735,98 +13244,106 @@ var ts;
}
ts.isCallLikeExpression = isCallLikeExpression;
function isCallOrNewExpression(node) {
- return node.kind === 187 || node.kind === 188;
+ return node.kind === 187 /* CallExpression */ || node.kind === 188 /* NewExpression */;
}
ts.isCallOrNewExpression = isCallOrNewExpression;
function isTemplateLiteral(node) {
var kind = node.kind;
- return kind === 202
- || kind === 13;
+ return kind === 202 /* TemplateExpression */
+ || kind === 13 /* NoSubstitutionTemplateLiteral */;
}
ts.isTemplateLiteral = isTemplateLiteral;
+ /* @internal */
function isLeftHandSideExpression(node) {
return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}
ts.isLeftHandSideExpression = isLeftHandSideExpression;
function isLeftHandSideExpressionKind(kind) {
switch (kind) {
- case 185:
- case 186:
- case 188:
- case 187:
- case 255:
- case 256:
- case 259:
- case 189:
- case 183:
- case 191:
- case 184:
- case 205:
- case 192:
- case 71:
- case 12:
- case 8:
- case 9:
- case 13:
- case 202:
- case 86:
- case 95:
- case 99:
- case 101:
- case 97:
- case 209:
- case 210:
- case 91:
+ case 185 /* PropertyAccessExpression */:
+ case 186 /* ElementAccessExpression */:
+ case 188 /* NewExpression */:
+ case 187 /* CallExpression */:
+ case 255 /* JsxElement */:
+ case 256 /* JsxSelfClosingElement */:
+ case 259 /* JsxFragment */:
+ case 189 /* TaggedTemplateExpression */:
+ case 183 /* ArrayLiteralExpression */:
+ case 191 /* ParenthesizedExpression */:
+ case 184 /* ObjectLiteralExpression */:
+ case 205 /* ClassExpression */:
+ case 192 /* FunctionExpression */:
+ case 71 /* Identifier */:
+ case 12 /* RegularExpressionLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ case 202 /* TemplateExpression */:
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ case 99 /* ThisKeyword */:
+ case 101 /* TrueKeyword */:
+ case 97 /* SuperKeyword */:
+ case 209 /* NonNullExpression */:
+ case 210 /* MetaProperty */:
+ case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
return true;
default:
return false;
}
}
+ /* @internal */
function isUnaryExpression(node) {
return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}
ts.isUnaryExpression = isUnaryExpression;
function isUnaryExpressionKind(kind) {
switch (kind) {
- case 198:
- case 199:
- case 194:
- case 195:
- case 196:
- case 197:
- case 190:
+ case 198 /* PrefixUnaryExpression */:
+ case 199 /* PostfixUnaryExpression */:
+ case 194 /* DeleteExpression */:
+ case 195 /* TypeOfExpression */:
+ case 196 /* VoidExpression */:
+ case 197 /* AwaitExpression */:
+ case 190 /* TypeAssertionExpression */:
return true;
default:
return isLeftHandSideExpressionKind(kind);
}
}
+ /* @internal */
function isUnaryExpressionWithWrite(expr) {
switch (expr.kind) {
- case 199:
+ case 199 /* PostfixUnaryExpression */:
return true;
- case 198:
- return expr.operator === 43 ||
- expr.operator === 44;
+ case 198 /* PrefixUnaryExpression */:
+ return expr.operator === 43 /* PlusPlusToken */ ||
+ expr.operator === 44 /* MinusMinusToken */;
default:
return false;
}
}
ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
+ /* @internal */
+ /**
+ * Determines whether a node is an expression based only on its kind.
+ * Use `isExpressionNode` if not in transforms.
+ */
function isExpression(node) {
return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}
ts.isExpression = isExpression;
function isExpressionKind(kind) {
switch (kind) {
- case 201:
- case 203:
- case 193:
- case 200:
- case 204:
- case 208:
- case 206:
- case 303:
- case 302:
+ case 201 /* ConditionalExpression */:
+ case 203 /* YieldExpression */:
+ case 193 /* ArrowFunction */:
+ case 200 /* BinaryExpression */:
+ case 204 /* SpreadElement */:
+ case 208 /* AsExpression */:
+ case 206 /* OmittedExpression */:
+ case 303 /* CommaListExpression */:
+ case 302 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -11834,18 +13351,21 @@ var ts;
}
function isAssertionExpression(node) {
var kind = node.kind;
- return kind === 190
- || kind === 208;
+ return kind === 190 /* TypeAssertionExpression */
+ || kind === 208 /* AsExpression */;
}
ts.isAssertionExpression = isAssertionExpression;
+ /* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 302;
+ return node.kind === 302 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
+ /* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 301;
+ return node.kind === 301 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
+ /* @internal */
function isNotEmittedOrPartiallyEmittedNode(node) {
return isNotEmittedStatement(node)
|| isPartiallyEmittedExpression(node);
@@ -11853,152 +13373,169 @@ var ts;
ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
function isIterationStatement(node, lookInLabeledStatements) {
switch (node.kind) {
- case 220:
- case 221:
- case 222:
- case 218:
- case 219:
+ case 220 /* ForStatement */:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
+ case 218 /* DoStatement */:
+ case 219 /* WhileStatement */:
return true;
- case 228:
+ case 228 /* LabeledStatement */:
return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
}
return false;
}
ts.isIterationStatement = isIterationStatement;
+ /* @internal */
function isForInOrOfStatement(node) {
- return node.kind === 221 || node.kind === 222;
+ return node.kind === 221 /* ForInStatement */ || node.kind === 222 /* ForOfStatement */;
}
ts.isForInOrOfStatement = isForInOrOfStatement;
+ // Element
+ /* @internal */
function isConciseBody(node) {
return ts.isBlock(node)
|| isExpression(node);
}
ts.isConciseBody = isConciseBody;
+ /* @internal */
function isFunctionBody(node) {
return ts.isBlock(node);
}
ts.isFunctionBody = isFunctionBody;
+ /* @internal */
function isForInitializer(node) {
return ts.isVariableDeclarationList(node)
|| isExpression(node);
}
ts.isForInitializer = isForInitializer;
+ /* @internal */
function isModuleBody(node) {
var kind = node.kind;
- return kind === 240
- || kind === 239
- || kind === 71;
+ return kind === 240 /* ModuleBlock */
+ || kind === 239 /* ModuleDeclaration */
+ || kind === 71 /* Identifier */;
}
ts.isModuleBody = isModuleBody;
+ /* @internal */
function isNamespaceBody(node) {
var kind = node.kind;
- return kind === 240
- || kind === 239;
+ return kind === 240 /* ModuleBlock */
+ || kind === 239 /* ModuleDeclaration */;
}
ts.isNamespaceBody = isNamespaceBody;
+ /* @internal */
function isJSDocNamespaceBody(node) {
var kind = node.kind;
- return kind === 71
- || kind === 239;
+ return kind === 71 /* Identifier */
+ || kind === 239 /* ModuleDeclaration */;
}
ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
+ /* @internal */
function isNamedImportBindings(node) {
var kind = node.kind;
- return kind === 247
- || kind === 246;
+ return kind === 247 /* NamedImports */
+ || kind === 246 /* NamespaceImport */;
}
ts.isNamedImportBindings = isNamedImportBindings;
+ /* @internal */
function isModuleOrEnumDeclaration(node) {
- return node.kind === 239 || node.kind === 238;
+ return node.kind === 239 /* ModuleDeclaration */ || node.kind === 238 /* EnumDeclaration */;
}
ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
function isDeclarationKind(kind) {
- return kind === 193
- || kind === 182
- || kind === 235
- || kind === 205
- || kind === 155
- || kind === 238
- || kind === 273
- || kind === 252
- || kind === 234
- || kind === 192
- || kind === 156
- || kind === 245
- || kind === 243
- || kind === 248
- || kind === 236
- || kind === 262
- || kind === 154
- || kind === 153
- || kind === 239
- || kind === 242
- || kind === 246
- || kind === 149
- || kind === 270
- || kind === 152
- || kind === 151
- || kind === 157
- || kind === 271
- || kind === 237
- || kind === 148
- || kind === 232
- || kind === 298
- || kind === 292
- || kind === 299;
+ return kind === 193 /* ArrowFunction */
+ || kind === 182 /* BindingElement */
+ || kind === 235 /* ClassDeclaration */
+ || kind === 205 /* ClassExpression */
+ || kind === 155 /* Constructor */
+ || kind === 238 /* EnumDeclaration */
+ || kind === 273 /* EnumMember */
+ || kind === 252 /* ExportSpecifier */
+ || kind === 234 /* FunctionDeclaration */
+ || kind === 192 /* FunctionExpression */
+ || kind === 156 /* GetAccessor */
+ || kind === 245 /* ImportClause */
+ || kind === 243 /* ImportEqualsDeclaration */
+ || kind === 248 /* ImportSpecifier */
+ || kind === 236 /* InterfaceDeclaration */
+ || kind === 262 /* JsxAttribute */
+ || kind === 154 /* MethodDeclaration */
+ || kind === 153 /* MethodSignature */
+ || kind === 239 /* ModuleDeclaration */
+ || kind === 242 /* NamespaceExportDeclaration */
+ || kind === 246 /* NamespaceImport */
+ || kind === 149 /* Parameter */
+ || kind === 270 /* PropertyAssignment */
+ || kind === 152 /* PropertyDeclaration */
+ || kind === 151 /* PropertySignature */
+ || kind === 157 /* SetAccessor */
+ || kind === 271 /* ShorthandPropertyAssignment */
+ || kind === 237 /* TypeAliasDeclaration */
+ || kind === 148 /* TypeParameter */
+ || kind === 232 /* VariableDeclaration */
+ || kind === 298 /* JSDocTypedefTag */
+ || kind === 292 /* JSDocCallbackTag */
+ || kind === 299 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
- return kind === 234
- || kind === 253
- || kind === 235
- || kind === 236
- || kind === 237
- || kind === 238
- || kind === 239
- || kind === 244
- || kind === 243
- || kind === 250
- || kind === 249
- || kind === 242;
+ return kind === 234 /* FunctionDeclaration */
+ || kind === 253 /* MissingDeclaration */
+ || kind === 235 /* ClassDeclaration */
+ || kind === 236 /* InterfaceDeclaration */
+ || kind === 237 /* TypeAliasDeclaration */
+ || kind === 238 /* EnumDeclaration */
+ || kind === 239 /* ModuleDeclaration */
+ || kind === 244 /* ImportDeclaration */
+ || kind === 243 /* ImportEqualsDeclaration */
+ || kind === 250 /* ExportDeclaration */
+ || kind === 249 /* ExportAssignment */
+ || kind === 242 /* NamespaceExportDeclaration */;
}
function isStatementKindButNotDeclarationKind(kind) {
- return kind === 224
- || kind === 223
- || kind === 231
- || kind === 218
- || kind === 216
- || kind === 215
- || kind === 221
- || kind === 222
- || kind === 220
- || kind === 217
- || kind === 228
- || kind === 225
- || kind === 227
- || kind === 229
- || kind === 230
- || kind === 214
- || kind === 219
- || kind === 226
- || kind === 301
- || kind === 305
- || kind === 304;
+ return kind === 224 /* BreakStatement */
+ || kind === 223 /* ContinueStatement */
+ || kind === 231 /* DebuggerStatement */
+ || kind === 218 /* DoStatement */
+ || kind === 216 /* ExpressionStatement */
+ || kind === 215 /* EmptyStatement */
+ || kind === 221 /* ForInStatement */
+ || kind === 222 /* ForOfStatement */
+ || kind === 220 /* ForStatement */
+ || kind === 217 /* IfStatement */
+ || kind === 228 /* LabeledStatement */
+ || kind === 225 /* ReturnStatement */
+ || kind === 227 /* SwitchStatement */
+ || kind === 229 /* ThrowStatement */
+ || kind === 230 /* TryStatement */
+ || kind === 214 /* VariableStatement */
+ || kind === 219 /* WhileStatement */
+ || kind === 226 /* WithStatement */
+ || kind === 301 /* NotEmittedStatement */
+ || kind === 305 /* EndOfDeclarationMarker */
+ || kind === 304 /* MergeDeclarationMarker */;
}
+ /* @internal */
function isDeclaration(node) {
- if (node.kind === 148) {
- return node.parent.kind !== 297 || ts.isInJavaScriptFile(node);
+ if (node.kind === 148 /* TypeParameter */) {
+ return node.parent.kind !== 297 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
ts.isDeclaration = isDeclaration;
+ /* @internal */
function isDeclarationStatement(node) {
return isDeclarationStatementKind(node.kind);
}
ts.isDeclarationStatement = isDeclarationStatement;
+ /**
+ * Determines whether the node is a statement that is not also a declaration
+ */
+ /* @internal */
function isStatementButNotDeclaration(node) {
return isStatementKindButNotDeclarationKind(node.kind);
}
ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
+ /* @internal */
function isStatement(node) {
var kind = node.kind;
return isStatementKindButNotDeclarationKind(kind)
@@ -12007,156 +13544,183 @@ var ts;
}
ts.isStatement = isStatement;
function isBlockStatement(node) {
- if (node.kind !== 213)
+ if (node.kind !== 213 /* Block */)
return false;
if (node.parent !== undefined) {
- if (node.parent.kind === 230 || node.parent.kind === 269) {
+ if (node.parent.kind === 230 /* TryStatement */ || node.parent.kind === 269 /* CatchClause */) {
return false;
}
}
return !ts.isFunctionBlock(node);
}
+ // Module references
+ /* @internal */
function isModuleReference(node) {
var kind = node.kind;
- return kind === 254
- || kind === 146
- || kind === 71;
+ return kind === 254 /* ExternalModuleReference */
+ || kind === 146 /* QualifiedName */
+ || kind === 71 /* Identifier */;
}
ts.isModuleReference = isModuleReference;
+ // JSX
+ /* @internal */
function isJsxTagNameExpression(node) {
var kind = node.kind;
- return kind === 99
- || kind === 71
- || kind === 185;
+ return kind === 99 /* ThisKeyword */
+ || kind === 71 /* Identifier */
+ || kind === 185 /* PropertyAccessExpression */;
}
ts.isJsxTagNameExpression = isJsxTagNameExpression;
+ /* @internal */
function isJsxChild(node) {
var kind = node.kind;
- return kind === 255
- || kind === 265
- || kind === 256
- || kind === 10
- || kind === 259;
+ return kind === 255 /* JsxElement */
+ || kind === 265 /* JsxExpression */
+ || kind === 256 /* JsxSelfClosingElement */
+ || kind === 10 /* JsxText */
+ || kind === 259 /* JsxFragment */;
}
ts.isJsxChild = isJsxChild;
+ /* @internal */
function isJsxAttributeLike(node) {
var kind = node.kind;
- return kind === 262
- || kind === 264;
+ return kind === 262 /* JsxAttribute */
+ || kind === 264 /* JsxSpreadAttribute */;
}
ts.isJsxAttributeLike = isJsxAttributeLike;
+ /* @internal */
function isStringLiteralOrJsxExpression(node) {
var kind = node.kind;
- return kind === 9
- || kind === 265;
+ return kind === 9 /* StringLiteral */
+ || kind === 265 /* JsxExpression */;
}
ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
function isJsxOpeningLikeElement(node) {
var kind = node.kind;
- return kind === 257
- || kind === 256;
+ return kind === 257 /* JsxOpeningElement */
+ || kind === 256 /* JsxSelfClosingElement */;
}
ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
+ // Clauses
function isCaseOrDefaultClause(node) {
var kind = node.kind;
- return kind === 266
- || kind === 267;
+ return kind === 266 /* CaseClause */
+ || kind === 267 /* DefaultClause */;
}
ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
+ // JSDoc
+ /** True if node is of some JSDoc syntax kind. */
+ /* @internal */
function isJSDocNode(node) {
- return node.kind >= 278 && node.kind <= 299;
+ return node.kind >= 278 /* FirstJSDocNode */ && node.kind <= 299 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
+ /** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 286 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 286 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
+ // TODO: determine what this does before making it public.
+ /* @internal */
function isJSDocTag(node) {
- return node.kind >= 289 && node.kind <= 299;
+ return node.kind >= 289 /* FirstJSDocTagNode */ && node.kind <= 299 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
- return node.kind === 157;
+ return node.kind === 157 /* SetAccessor */;
}
ts.isSetAccessor = isSetAccessor;
function isGetAccessor(node) {
- return node.kind === 156;
+ return node.kind === 156 /* GetAccessor */;
}
ts.isGetAccessor = isGetAccessor;
+ /** True if has jsdoc nodes attached to it. */
+ /* @internal */
+ // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
function hasJSDocNodes(node) {
var jsDoc = node.jsDoc;
return !!jsDoc && jsDoc.length > 0;
}
ts.hasJSDocNodes = hasJSDocNodes;
+ /** True if has type node attached to it. */
+ /* @internal */
function hasType(node) {
return !!node.type;
}
ts.hasType = hasType;
+ /* True if the node could have a type node a `.type` */
+ /* @internal */
function couldHaveType(node) {
switch (node.kind) {
- case 149:
- case 151:
- case 152:
- case 153:
- case 154:
- case 155:
- case 156:
- case 157:
- case 158:
- case 159:
- case 160:
- case 161:
- case 163:
- case 164:
- case 173:
- case 175:
- case 177:
- case 190:
- case 192:
- case 193:
- case 208:
- case 232:
- case 234:
- case 237:
- case 278:
- case 281:
- case 282:
- case 283:
- case 284:
- case 285:
+ case 149 /* Parameter */:
+ case 151 /* PropertySignature */:
+ case 152 /* PropertyDeclaration */:
+ case 153 /* MethodSignature */:
+ case 154 /* MethodDeclaration */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 158 /* CallSignature */:
+ case 159 /* ConstructSignature */:
+ case 160 /* IndexSignature */:
+ case 161 /* TypePredicate */:
+ case 163 /* FunctionType */:
+ case 164 /* ConstructorType */:
+ case 173 /* ParenthesizedType */:
+ case 175 /* TypeOperator */:
+ case 177 /* MappedType */:
+ case 190 /* TypeAssertionExpression */:
+ case 192 /* FunctionExpression */:
+ case 193 /* ArrowFunction */:
+ case 208 /* AsExpression */:
+ case 232 /* VariableDeclaration */:
+ case 234 /* FunctionDeclaration */:
+ case 237 /* TypeAliasDeclaration */:
+ case 278 /* JSDocTypeExpression */:
+ case 281 /* JSDocNullableType */:
+ case 282 /* JSDocNonNullableType */:
+ case 283 /* JSDocOptionalType */:
+ case 284 /* JSDocFunctionType */:
+ case 285 /* JSDocVariadicType */:
return true;
}
return false;
}
ts.couldHaveType = couldHaveType;
+ /** True if has initializer node attached to it. */
+ /* @internal */
function hasInitializer(node) {
return !!node.initializer;
}
ts.hasInitializer = hasInitializer;
+ /** True if has initializer node attached to it. */
+ /* @internal */
function hasOnlyExpressionInitializer(node) {
return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node);
}
ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
function isObjectLiteralElement(node) {
switch (node.kind) {
- case 262:
- case 264:
- case 270:
- case 271:
- case 154:
- case 156:
- case 157:
+ case 262 /* JsxAttribute */:
+ case 264 /* JsxSpreadAttribute */:
+ case 270 /* PropertyAssignment */:
+ case 271 /* ShorthandPropertyAssignment */:
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
return true;
default:
return false;
}
}
ts.isObjectLiteralElement = isObjectLiteralElement;
+ /* @internal */
function isTypeReferenceType(node) {
- return node.kind === 162 || node.kind === 207;
+ return node.kind === 162 /* TypeReference */ || node.kind === 207 /* ExpressionWithTypeArguments */;
}
ts.isTypeReferenceType = isTypeReferenceType;
var MAX_SMI_X86 = 1073741823;
+ /* @internal */
function guessIndentation(lines) {
var indentation = MAX_SMI_X86;
for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
@@ -12181,13 +13745,15 @@ var ts;
}
ts.guessIndentation = guessIndentation;
function isStringLiteralLike(node) {
- return node.kind === 9 || node.kind === 13;
+ return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */;
}
ts.isStringLiteralLike = isStringLiteralLike;
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
+ /** @internal */
function isNamedImportsOrExports(node) {
- return node.kind === 247 || node.kind === 251;
+ return node.kind === 247 /* NamedImports */ || node.kind === 251 /* NamedExports */;
}
ts.isNamedImportsOrExports = isNamedImportsOrExports;
function Symbol(flags, name) {
@@ -12205,15 +13771,15 @@ var ts;
this.checker = checker;
}
}
- function Signature() { }
+ function Signature() { } // tslint:disable-line no-empty
function Node(kind, pos, end) {
this.pos = pos;
this.end = end;
this.kind = kind;
this.id = 0;
- this.flags = 0;
- this.modifierFlagsCache = 0;
- this.transformFlags = 0;
+ this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
this.original = undefined;
}
@@ -12232,6 +13798,7 @@ var ts;
getSignatureConstructor: function () { return Signature; },
getSourceMapSourceConstructor: function () { return SourceMapSource; },
};
+ /* @internal */
function formatStringFromArgs(text, args, baseIndex) {
if (baseIndex === void 0) { baseIndex = 0; }
return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); });
@@ -12263,6 +13830,7 @@ var ts;
};
}
ts.createFileDiagnostic = createFileDiagnostic;
+ /* @internal */
function formatMessage(_dummy, message) {
var text = getLocaleSpecificMessage(message);
if (arguments.length > 2) {
@@ -12287,6 +13855,7 @@ var ts;
};
}
ts.createCompilerDiagnostic = createCompilerDiagnostic;
+ /* @internal */
function createCompilerDiagnosticFromMessageChain(chain) {
return {
file: undefined,
@@ -12323,19 +13892,21 @@ var ts;
function getDiagnosticFilePath(diagnostic) {
return diagnostic.file ? diagnostic.file.path : undefined;
}
+ /* @internal */
function compareDiagnostics(d1, d2) {
return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
ts.compareValues(d1.start, d2.start) ||
ts.compareValues(d1.length, d2.length) ||
ts.compareValues(d1.code, d2.code) ||
compareMessageText(d1.messageText, d2.messageText) ||
- 0;
+ 0 /* EqualTo */;
}
ts.compareDiagnostics = compareDiagnostics;
function compareMessageText(t1, t2) {
var text1 = t1;
var text2 = t2;
while (text1 && text2) {
+ // We still have both chains.
var string1 = ts.isString(text1) ? text1 : text1.messageText;
var string2 = ts.isString(text2) ? text2 : text2.messageText;
var res = ts.compareStringsCaseSensitive(string1, string2);
@@ -12346,18 +13917,20 @@ var ts;
text2 = ts.isString(text2) ? undefined : text2.next;
}
if (!text1 && !text2) {
- return 0;
+ // if the chains are done, then these messages are the same.
+ return 0 /* EqualTo */;
}
- return text1 ? 1 : -1;
+ // We still have one chain remaining. The shorter chain should come first.
+ return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
}
function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0;
+ return compilerOptions.target || 0 /* ES3 */;
}
ts.getEmitScriptTarget = getEmitScriptTarget;
function getEmitModuleKind(compilerOptions) {
return typeof compilerOptions.module === "number" ?
compilerOptions.module :
- getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
+ getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
}
ts.getEmitModuleKind = getEmitModuleKind;
function getEmitModuleResolutionKind(compilerOptions) {
@@ -12400,11 +13973,12 @@ var ts;
function hasZeroOrOneAsteriskCharacter(str) {
var seenAsterisk = false;
for (var i = 0; i < str.length; i++) {
- if (str.charCodeAt(i) === 42) {
+ if (str.charCodeAt(i) === 42 /* asterisk */) {
if (!seenAsterisk) {
seenAsterisk = true;
}
else {
+ // have already seen asterisk
return false;
}
}
@@ -12412,78 +13986,126 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ /**
+ * Internally, we represent paths as strings with '/' as the directory separator.
+ * When we make system calls (eg: LanguageServiceHost.getDirectory()),
+ * we expect the host to correctly handle paths in our specified format.
+ */
ts.directorySeparator = "/";
var altDirectorySeparator = "\\";
var urlSchemeSeparator = "://";
var backslashRegExp = /\\/g;
+ /**
+ * Normalize path separators.
+ */
function normalizeSlashes(path) {
return path.replace(backslashRegExp, ts.directorySeparator);
}
ts.normalizeSlashes = normalizeSlashes;
function isVolumeCharacter(charCode) {
- return (charCode >= 97 && charCode <= 122) ||
- (charCode >= 65 && charCode <= 90);
+ return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
+ (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
}
function getFileUrlVolumeSeparatorEnd(url, start) {
var ch0 = url.charCodeAt(start);
- if (ch0 === 58)
+ if (ch0 === 58 /* colon */)
return start + 1;
- if (ch0 === 37 && url.charCodeAt(start + 1) === 51) {
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
var ch2 = url.charCodeAt(start + 2);
- if (ch2 === 97 || ch2 === 65)
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
return start + 3;
}
return -1;
}
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ * If the root is part of a URL, the twos-complement of the root length is returned.
+ */
function getEncodedRootLength(path) {
if (!path)
return 0;
var ch0 = path.charCodeAt(0);
- if (ch0 === 47 || ch0 === 92) {
+ // POSIX or UNC
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
if (path.charCodeAt(1) !== ch0)
- return 1;
- var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2);
+ return 1; // POSIX: "/" (or non-normalized "\")
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
if (p1 < 0)
- return path.length;
- return p1 + 1;
+ return path.length; // UNC: "//server" or "\\server"
+ return p1 + 1; // UNC: "//server/" or "\\server\"
}
- if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) {
+ // DOS
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
var ch2 = path.charCodeAt(2);
- if (ch2 === 47 || ch2 === 92)
- return 3;
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
+ return 3; // DOS: "c:/" or "c:\"
if (path.length === 2)
- return 2;
+ return 2; // DOS: "c:" (but not "c:d")
}
+ // URL
var schemeEnd = path.indexOf(urlSchemeSeparator);
if (schemeEnd !== -1) {
var authorityStart = schemeEnd + urlSchemeSeparator.length;
var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
- if (authorityEnd !== -1) {
+ if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
+ // For local "file" URLs, include the leading DOS volume (if present).
+ // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
+ // special case interpreted as "the machine from which the URL is being interpreted".
var scheme = path.slice(0, schemeEnd);
var authority = path.slice(authorityStart, authorityEnd);
if (scheme === "file" && (authority === "" || authority === "localhost") &&
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
if (volumeSeparatorEnd !== -1) {
- if (path.charCodeAt(volumeSeparatorEnd) === 47) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
+ // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
return ~(volumeSeparatorEnd + 1);
}
if (volumeSeparatorEnd === path.length) {
+ // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
+ // but not "file:///c:d" or "file:///c%3ad"
return ~volumeSeparatorEnd;
}
}
}
- return ~(authorityEnd + 1);
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
- return ~path.length;
+ return ~path.length; // URL: "file://server", "http://server"
}
+ // relative
return 0;
}
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ *
+ * For example:
+ * ```ts
+ * getRootLength("a") === 0 // ""
+ * getRootLength("/") === 1 // "/"
+ * getRootLength("c:") === 2 // "c:"
+ * getRootLength("c:d") === 0 // ""
+ * getRootLength("c:/") === 3 // "c:/"
+ * getRootLength("c:\\") === 3 // "c:\\"
+ * getRootLength("//server") === 7 // "//server"
+ * getRootLength("//server/share") === 8 // "//server/"
+ * getRootLength("\\\\server") === 7 // "\\\\server"
+ * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
+ * getRootLength("file:///path") === 8 // "file:///"
+ * getRootLength("file:///c:") === 10 // "file:///c:"
+ * getRootLength("file:///c:d") === 8 // "file:///"
+ * getRootLength("file:///c:/path") === 11 // "file:///c:/"
+ * getRootLength("file://server") === 13 // "file://server"
+ * getRootLength("file://server/path") === 14 // "file://server/"
+ * getRootLength("http://server") === 13 // "http://server"
+ * getRootLength("http://server/path") === 14 // "http://server/"
+ * ```
+ */
function getRootLength(path) {
var rootLength = getEncodedRootLength(path);
return rootLength < 0 ? ~rootLength : rootLength;
}
ts.getRootLength = getRootLength;
+ // TODO(rbuckton): replace references with `resolvePath`
function normalizePath(path) {
return ts.resolvePath(path);
}
@@ -12502,9 +14124,12 @@ var ts;
ts.normalizePathAndParts = normalizePathAndParts;
function getDirectoryPath(path) {
path = normalizeSlashes(path);
+ // If the path provided is itself the root, then return it.
var rootLength = getRootLength(path);
if (rootLength === path.length)
return path;
+ // return the leading portion of the path up to the last (non-terminal) directory separator
+ // but not including any trailing directory separator.
path = ts.removeTrailingDirectorySeparator(path);
return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
}
@@ -12517,19 +14142,27 @@ var ts;
return /^\.\.?($|[\\/])/.test(path);
}
ts.pathIsRelative = pathIsRelative;
+ /**
+ * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
+ * like `c:`, `c:\` or `c:/`).
+ */
function isRootedDiskPath(path) {
return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ /**
+ * Determines whether a path consists only of a path root.
+ */
function isDiskPathRoot(path) {
var rootLength = getEncodedRootLength(path);
return rootLength > 0 && rootLength === path.length;
}
ts.isDiskPathRoot = isDiskPathRoot;
+ /* @internal */
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
- : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
+ : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
ts.convertToRelativePath = convertToRelativePath;
function pathComponents(path, rootLength) {
@@ -12539,6 +14172,12 @@ var ts;
rest.pop();
return [root].concat(rest);
}
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is not normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
function getPathComponents(path, currentDirectory) {
if (currentDirectory === void 0) { currentDirectory = ""; }
path = ts.combinePaths(currentDirectory, path);
@@ -12546,6 +14185,10 @@ var ts;
return pathComponents(path, rootLength);
}
ts.getPathComponents = getPathComponents;
+ /**
+ * Reduce an array of path components to a more simplified path by navigating any
+ * `"."` or `".."` entries in the path.
+ */
function reducePathComponents(components) {
if (!ts.some(components))
return [];
@@ -12571,6 +14214,12 @@ var ts;
return reduced;
}
ts.reducePathComponents = reducePathComponents;
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
function getNormalizedPathComponents(path, currentDirectory) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
@@ -12579,6 +14228,10 @@ var ts;
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
+ /**
+ * Formats a parsed path consisting of a root component (at index 0) and zero or more path
+ * segments (at indices > 0).
+ */
function getPathFromPathComponents(pathComponents) {
if (pathComponents.length === 0)
return "";
@@ -12589,6 +14242,7 @@ var ts;
}
ts.getPathFromPathComponents = getPathFromPathComponents;
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
var fromComponents = ts.reducePathComponents(ts.getPathComponents(from));
@@ -12634,21 +14288,31 @@ var ts;
return ts.getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
+ /**
+ * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
+ * with `./` or `../`) so as not to be confused with an unprefixed module name.
+ */
function ensurePathIsNonModuleName(path) {
return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path;
}
ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
function getBaseFileName(path, extensions, ignoreCase) {
path = ts.normalizeSlashes(path);
+ // if the path provided is itself the root, then it has not file name.
var rootLength = ts.getRootLength(path);
if (rootLength === path.length)
return "";
+ // return the trailing portion of the path starting after the last (non-terminal) directory
+ // separator but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
+ /**
+ * Combines paths. If a path is absolute, it replaces any previous path.
+ */
function combinePaths(path) {
var paths = [];
for (var _i = 1; _i < arguments.length; _i++) {
@@ -12671,6 +14335,10 @@ var ts;
return path;
}
ts.combinePaths = combinePaths;
+ /**
+ * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
+ * `.` and `..` path components are resolved.
+ */
function resolvePath(path) {
var paths = [];
for (var _i = 1; _i < arguments.length; _i++) {
@@ -12681,11 +14349,14 @@ var ts;
return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
}
ts.resolvePath = resolvePath;
+ /**
+ * Determines whether a path has a trailing separator (`/` or `\\`).
+ */
function hasTrailingDirectorySeparator(path) {
if (path.length === 0)
return false;
var ch = path.charCodeAt(path.length - 1);
- return ch === 47 || ch === 92;
+ return ch === 47 /* slash */ || ch === 92 /* backslash */;
}
ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
@@ -12704,27 +14375,33 @@ var ts;
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
function comparePathsWorker(a, b, componentComparer) {
if (a === b)
- return 0;
+ return 0 /* EqualTo */;
if (a === undefined)
- return -1;
+ return -1 /* LessThan */;
if (b === undefined)
- return 1;
+ return 1 /* GreaterThan */;
var aComponents = ts.reducePathComponents(ts.getPathComponents(a));
var bComponents = ts.reducePathComponents(ts.getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
for (var i = 0; i < sharedLength; i++) {
var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer;
var result = stringComparer(aComponents[i], bComponents[i]);
- if (result !== 0) {
+ if (result !== 0 /* EqualTo */) {
return result;
}
}
return ts.compareValues(aComponents.length, bComponents.length);
}
+ /**
+ * Performs a case-sensitive comparison of two paths.
+ */
function comparePathsCaseSensitive(a, b) {
return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
}
ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ /**
+ * Performs a case-insensitive comparison of two paths.
+ */
function comparePathsCaseInsensitive(a, b) {
return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
}
@@ -12772,16 +14449,19 @@ var ts;
if (a === undefined)
return undefined;
switch (a.charCodeAt(0)) {
- case 47:
- case 92:
+ case 47 /* slash */:
+ case 92 /* backslash */:
return a.slice(1);
default:
return undefined;
}
}
ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
+ // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
+ // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
+ // proof.
var reservedCharacterPattern = /[^\w\s\/]/g;
- var wildcardCharCodes = [42, 63];
+ var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
function hasExtension(fileName) {
return ts.stringContains(getBaseFileName(fileName), ".");
}
@@ -12789,12 +14469,26 @@ var ts;
ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
var filesMatcher = {
+ /**
+ * Matches any single directory segment unless it is the last segment and a .min.js file
+ * Breakdown:
+ * [^./] # matches everything up to the first . character (excluding directory separators)
+ * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
+ */
singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
+ /**
+ * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
+ * files or directories, does not match subdirectories that start with a . character
+ */
doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
};
var directoriesMatcher = {
singleAsteriskRegexFragment: "[^/]*",
+ /**
+ * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
+ * files or directories, does not match subdirectories that start with a . character
+ */
doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
};
@@ -12814,6 +14508,7 @@ var ts;
return undefined;
}
var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
+ // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
var terminator = usage === "exclude" ? "($|/)" : "$";
return "^(" + pattern + ")" + terminator;
}
@@ -12826,6 +14521,10 @@ var ts;
return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
});
}
+ /**
+ * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
+ * and does not contain any glob characters itself.
+ */
function isImplicitGlob(lastPathComponent) {
return !/[.*?]/.test(lastPathComponent);
}
@@ -12839,6 +14538,8 @@ var ts;
if (usage !== "exclude" && lastComponent === "**") {
return undefined;
}
+ // getNormalizedPathComponents includes the separator for the root component.
+ // We need to remove to create our regex correctly.
components[0] = removeTrailingDirectorySeparator(components[0]);
if (isImplicitGlob(lastComponent)) {
components.push("**", "*");
@@ -12859,15 +14560,24 @@ var ts;
}
if (usage !== "exclude") {
var componentPattern = "";
- if (component.charCodeAt(0) === 42) {
+ // The * and ? wildcards should not match directories or files that start with . if they
+ // appear first in a component. Dotted directories and files can be included explicitly
+ // like so: **/.*/.*
+ if (component.charCodeAt(0) === 42 /* asterisk */) {
componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
component = component.substr(1);
}
- else if (component.charCodeAt(0) === 63) {
+ else if (component.charCodeAt(0) === 63 /* question */) {
componentPattern += "[^./]";
component = component.substr(1);
}
componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
+ // Patterns should not include subfolders like node_modules unless they are
+ // explicitly included as part of the path.
+ //
+ // As an optimization, if the component pattern is the same as the component,
+ // then there definitely were no wildcard characters and we do not need to
+ // add the exclusion pattern.
if (componentPattern !== component) {
subpattern += implicitExcludePathRegexPattern;
}
@@ -12888,6 +14598,7 @@ var ts;
function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
}
+ /** @param path directory of the tsconfig.json */
function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
@@ -12905,6 +14616,7 @@ var ts;
return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
}
ts.getRegexFromPattern = getRegexFromPattern;
+ /** @param path directory of the tsconfig.json */
function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
@@ -12912,6 +14624,8 @@ var ts;
var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
+ // Associate an array of results with each include regex. This keeps results in order of the "include" order.
+ // If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
@@ -12959,21 +14673,32 @@ var ts;
}
}
ts.matchFiles = matchFiles;
+ /**
+ * Computes the unique non-wildcard base paths amongst the provided include patterns.
+ */
function getBasePaths(path, includes, useCaseSensitiveFileNames) {
+ // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
var basePaths = [path];
if (includes) {
+ // Storage for literal base paths amongst the include patterns.
var includeBasePaths = [];
for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
var include = includes_1[_i];
+ // We also need to check the relative paths by converting them to absolute and normalizing
+ // in case they escape the base path (e.g "..\somedirectory")
var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include));
+ // Append the literal and canonical candidate base paths.
includeBasePaths.push(getIncludeBasePath(absolute));
}
+ // Sort the offsets array using either the literal or canonical path representations.
includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
var _loop_2 = function (includeBasePath) {
if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
+ // Iterate over each include base path and include unique base paths that are not a
+ // subpath of an existing base path
for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
var includeBasePath = includeBasePaths_1[_a];
_loop_2(includeBasePath);
@@ -12984,6 +14709,7 @@ var ts;
function getIncludeBasePath(absolute) {
var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
if (wildcardOffset < 0) {
+ // No "*" or "?" in the path
return !hasExtension(absolute)
? absolute
: removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
@@ -12991,42 +14717,52 @@ var ts;
return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
}
function ensureScriptKind(fileName, scriptKind) {
- return scriptKind || getScriptKindFromFileName(fileName) || 3;
+ // Using scriptKind as a condition handles both:
+ // - 'scriptKind' is unspecified and thus it is `undefined`
+ // - 'scriptKind' is set and it is `Unknown` (0)
+ // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
+ // to get the ScriptKind from the file name. If it cannot be resolved
+ // from the file name then the default 'TS' script kind is returned.
+ return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
}
ts.ensureScriptKind = ensureScriptKind;
function getScriptKindFromFileName(fileName) {
var ext = fileName.substr(fileName.lastIndexOf("."));
switch (ext.toLowerCase()) {
- case ".js":
- return 1;
- case ".jsx":
- return 2;
- case ".ts":
- return 3;
- case ".tsx":
- return 4;
- case ".json":
- return 6;
+ case ".js" /* Js */:
+ return 1 /* JS */;
+ case ".jsx" /* Jsx */:
+ return 2 /* JSX */;
+ case ".ts" /* Ts */:
+ return 3 /* TS */;
+ case ".tsx" /* Tsx */:
+ return 4 /* TSX */;
+ case ".json" /* Json */:
+ return 6 /* JSON */;
default:
- return 0;
+ return 0 /* Unknown */;
}
}
ts.getScriptKindFromFileName = getScriptKindFromFileName;
- ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"];
- ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"];
- ts.supportedJavascriptExtensions = [".js", ".jsx"];
+ /**
+ * List of supported extensions in order of file resolution precedence.
+ */
+ ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
+ /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
+ ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
+ ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
var needJsExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
function isJavaScriptLike(scriptKind) {
- return scriptKind === 1 || scriptKind === 2;
+ return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
}
function hasJavaScriptFileExtension(fileName) {
return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
@@ -13049,6 +14785,11 @@ var ts;
return false;
}
ts.isSupportedSourceFileName = isSupportedSourceFileName;
+ /**
+ * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
+ * aligned to the offset of the highest priority extension in the
+ * allSupportedExtensions array.
+ */
var ExtensionPriority;
(function (ExtensionPriority) {
ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
@@ -13062,31 +14803,39 @@ var ts;
return adjustExtensionPriority(i, supportedExtensions);
}
}
- return 0;
+ // If its not in the list of supported extensions, this is likely a
+ // TypeScript file with a non-ts extension
+ return 0 /* Highest */;
}
ts.getExtensionPriority = getExtensionPriority;
+ /**
+ * Adjusts an extension priority to be the highest priority within the same range.
+ */
function adjustExtensionPriority(extensionPriority, supportedExtensions) {
- if (extensionPriority < 2) {
- return 0;
+ if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
+ return 0 /* TypeScriptFiles */;
}
else if (extensionPriority < supportedExtensions.length) {
- return 2;
+ return 2 /* DeclarationAndJavaScriptFiles */;
}
else {
return supportedExtensions.length;
}
}
ts.adjustExtensionPriority = adjustExtensionPriority;
+ /**
+ * Gets the next lowest extension priority for a given priority.
+ */
function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
- if (extensionPriority < 2) {
- return 2;
+ if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
+ return 2 /* DeclarationAndJavaScriptFiles */;
}
else {
return supportedExtensions.length;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"];
+ var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -13107,7 +14856,7 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return changeAnyExtension(path, newExtension, extensionsToRemove, false);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
}
ts.changeExtension = changeExtension;
function changeAnyExtension(path, ext, extensions, ignoreCase) {
@@ -13139,6 +14888,7 @@ var ts;
Debug.showSyntaxKind = showSyntaxKind;
})(Debug = ts.Debug || (ts.Debug = {}));
function tryParsePattern(pattern) {
+ // This should be verified outside of here and a proper error thrown.
Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
var indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
@@ -13148,17 +14898,24 @@ var ts;
}
ts.tryParsePattern = tryParsePattern;
function positionIsSynthesized(pos) {
+ // This is a fast way of testing the following conditions:
+ // pos === undefined || pos === null || isNaN(pos) || pos < 0;
return !(pos >= 0);
}
ts.positionIsSynthesized = positionIsSynthesized;
+ /** True if an extension is one of the supported TypeScript extensions. */
function extensionIsTypeScript(ext) {
- return ext === ".ts" || ext === ".tsx" || ext === ".d.ts";
+ return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
}
ts.extensionIsTypeScript = extensionIsTypeScript;
function resolutionExtensionIsTypeScriptOrJson(ext) {
- return extensionIsTypeScript(ext) || ext === ".json";
+ return extensionIsTypeScript(ext) || ext === ".json" /* Json */;
}
ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
+ /**
+ * Gets the extension from a path.
+ * Path must have a valid extension.
+ */
function extensionFromPath(path) {
var ext = tryGetExtensionFromPath(path);
return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension.");
@@ -13189,6 +14946,8 @@ var ts;
return "";
}
function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ // Retrieves any string from the final "." onwards from a base file name.
+ // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
if (extensions) {
return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
}
@@ -13208,6 +14967,11 @@ var ts;
files: ts.emptyArray,
directories: ts.emptyArray
};
+ /**
+ * patternStrings contains both pattern strings (containing "*") and regular strings.
+ * Return an exact match if possible, or a pattern match, or undefined.
+ * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
+ */
function matchPatternOrExact(patternStrings, candidate) {
var patterns = [];
for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
@@ -13217,6 +14981,7 @@ var ts;
patterns.push(pattern);
}
else if (patternString === candidate) {
+ // pattern was matched as is - no need to search further
return patternString;
}
}
@@ -13235,15 +15000,17 @@ var ts;
SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
})(SignatureFlags || (SignatureFlags = {}));
+ // tslint:disable variable-name
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
+ // tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 274) {
+ if (kind === 274 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
- else if (kind === 71) {
+ else if (kind === 71 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (!ts.isNodeKind(kind)) {
@@ -13271,35 +15038,49 @@ var ts;
}
}
}
+ /*@internal*/
function isJSDocLikeText(text, start) {
- return text.charCodeAt(start + 1) === 42 &&
- text.charCodeAt(start + 2) === 42 &&
- text.charCodeAt(start + 3) !== 47;
+ return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(start + 2) === 42 /* asterisk */ &&
+ text.charCodeAt(start + 3) !== 47 /* slash */;
}
ts.isJSDocLikeText = isJSDocLikeText;
+ /**
+ * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
+ * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
+ * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
+ * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
+ *
+ * @param node a given node to visit its children
+ * @param cbNode a callback to be invoked for all child nodes
+ * @param cbNodes a callback to be invoked for embedded array
+ *
+ * @remarks `forEachChild` must visit the children of a node in the order
+ * that they appear in the source code. The language service depends on this property to locate nodes by position.
+ */
function forEachChild(node, cbNode, cbNodes) {
- if (!node || node.kind <= 145) {
+ if (!node || node.kind <= 145 /* LastToken */) {
return;
}
switch (node.kind) {
- case 146:
+ case 146 /* QualifiedName */:
return visitNode(cbNode, node.left) ||
visitNode(cbNode, node.right);
- case 148:
+ case 148 /* TypeParameter */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.constraint) ||
visitNode(cbNode, node.default) ||
visitNode(cbNode, node.expression);
- case 271:
+ case 271 /* ShorthandPropertyAssignment */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.equalsToken) ||
visitNode(cbNode, node.objectAssignmentInitializer);
- case 272:
+ case 272 /* SpreadAssignment */:
return visitNode(cbNode, node.expression);
- case 149:
+ case 149 /* Parameter */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.dotDotDotToken) ||
@@ -13307,7 +15088,7 @@ var ts;
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.initializer);
- case 152:
+ case 152 /* PropertyDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
@@ -13315,51 +15096,51 @@ var ts;
visitNode(cbNode, node.exclamationToken) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.initializer);
- case 151:
+ case 151 /* PropertySignature */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.initializer);
- case 270:
+ case 270 /* PropertyAssignment */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.initializer);
- case 232:
+ case 232 /* VariableDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.exclamationToken) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.initializer);
- case 182:
+ case 182 /* BindingElement */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.dotDotDotToken) ||
visitNode(cbNode, node.propertyName) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.initializer);
- case 163:
- case 164:
- case 158:
- case 159:
- case 160:
+ case 163 /* FunctionType */:
+ case 164 /* ConstructorType */:
+ case 158 /* CallSignature */:
+ case 159 /* ConstructSignature */:
+ case 160 /* IndexSignature */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNodes(cbNode, cbNodes, node.typeParameters) ||
visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 154:
- case 153:
- case 155:
- case 156:
- case 157:
- case 192:
- case 234:
- case 193:
+ case 154 /* MethodDeclaration */:
+ case 153 /* MethodSignature */:
+ case 155 /* Constructor */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 192 /* FunctionExpression */:
+ case 234 /* FunctionDeclaration */:
+ case 193 /* ArrowFunction */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.asteriskToken) ||
@@ -13370,304 +15151,304 @@ var ts;
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.equalsGreaterThanToken) ||
visitNode(cbNode, node.body);
- case 162:
+ case 162 /* TypeReference */:
return visitNode(cbNode, node.typeName) ||
visitNodes(cbNode, cbNodes, node.typeArguments);
- case 161:
+ case 161 /* TypePredicate */:
return visitNode(cbNode, node.parameterName) ||
visitNode(cbNode, node.type);
- case 165:
+ case 165 /* TypeQuery */:
return visitNode(cbNode, node.exprName);
- case 166:
+ case 166 /* TypeLiteral */:
return visitNodes(cbNode, cbNodes, node.members);
- case 167:
+ case 167 /* ArrayType */:
return visitNode(cbNode, node.elementType);
- case 168:
+ case 168 /* TupleType */:
return visitNodes(cbNode, cbNodes, node.elementTypes);
- case 169:
- case 170:
+ case 169 /* UnionType */:
+ case 170 /* IntersectionType */:
return visitNodes(cbNode, cbNodes, node.types);
- case 171:
+ case 171 /* ConditionalType */:
return visitNode(cbNode, node.checkType) ||
visitNode(cbNode, node.extendsType) ||
visitNode(cbNode, node.trueType) ||
visitNode(cbNode, node.falseType);
- case 172:
+ case 172 /* InferType */:
return visitNode(cbNode, node.typeParameter);
- case 179:
+ case 179 /* ImportType */:
return visitNode(cbNode, node.argument) ||
visitNode(cbNode, node.qualifier) ||
visitNodes(cbNode, cbNodes, node.typeArguments);
- case 173:
- case 175:
+ case 173 /* ParenthesizedType */:
+ case 175 /* TypeOperator */:
return visitNode(cbNode, node.type);
- case 176:
+ case 176 /* IndexedAccessType */:
return visitNode(cbNode, node.objectType) ||
visitNode(cbNode, node.indexType);
- case 177:
+ case 177 /* MappedType */:
return visitNode(cbNode, node.readonlyToken) ||
visitNode(cbNode, node.typeParameter) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.type);
- case 178:
+ case 178 /* LiteralType */:
return visitNode(cbNode, node.literal);
- case 180:
- case 181:
+ case 180 /* ObjectBindingPattern */:
+ case 181 /* ArrayBindingPattern */:
return visitNodes(cbNode, cbNodes, node.elements);
- case 183:
+ case 183 /* ArrayLiteralExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
- case 184:
+ case 184 /* ObjectLiteralExpression */:
return visitNodes(cbNode, cbNodes, node.properties);
- case 185:
+ case 185 /* PropertyAccessExpression */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.name);
- case 186:
+ case 186 /* ElementAccessExpression */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.argumentExpression);
- case 187:
- case 188:
+ case 187 /* CallExpression */:
+ case 188 /* NewExpression */:
return visitNode(cbNode, node.expression) ||
visitNodes(cbNode, cbNodes, node.typeArguments) ||
visitNodes(cbNode, cbNodes, node.arguments);
- case 189:
+ case 189 /* TaggedTemplateExpression */:
return visitNode(cbNode, node.tag) ||
visitNodes(cbNode, cbNodes, node.typeArguments) ||
visitNode(cbNode, node.template);
- case 190:
+ case 190 /* TypeAssertionExpression */:
return visitNode(cbNode, node.type) ||
visitNode(cbNode, node.expression);
- case 191:
+ case 191 /* ParenthesizedExpression */:
return visitNode(cbNode, node.expression);
- case 194:
+ case 194 /* DeleteExpression */:
return visitNode(cbNode, node.expression);
- case 195:
+ case 195 /* TypeOfExpression */:
return visitNode(cbNode, node.expression);
- case 196:
+ case 196 /* VoidExpression */:
return visitNode(cbNode, node.expression);
- case 198:
+ case 198 /* PrefixUnaryExpression */:
return visitNode(cbNode, node.operand);
- case 203:
+ case 203 /* YieldExpression */:
return visitNode(cbNode, node.asteriskToken) ||
visitNode(cbNode, node.expression);
- case 197:
+ case 197 /* AwaitExpression */:
return visitNode(cbNode, node.expression);
- case 199:
+ case 199 /* PostfixUnaryExpression */:
return visitNode(cbNode, node.operand);
- case 200:
+ case 200 /* BinaryExpression */:
return visitNode(cbNode, node.left) ||
visitNode(cbNode, node.operatorToken) ||
visitNode(cbNode, node.right);
- case 208:
+ case 208 /* AsExpression */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.type);
- case 209:
+ case 209 /* NonNullExpression */:
return visitNode(cbNode, node.expression);
- case 210:
+ case 210 /* MetaProperty */:
return visitNode(cbNode, node.name);
- case 201:
+ case 201 /* ConditionalExpression */:
return visitNode(cbNode, node.condition) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.whenTrue) ||
visitNode(cbNode, node.colonToken) ||
visitNode(cbNode, node.whenFalse);
- case 204:
+ case 204 /* SpreadElement */:
return visitNode(cbNode, node.expression);
- case 213:
- case 240:
+ case 213 /* Block */:
+ case 240 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 274:
+ case 274 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
- case 214:
+ case 214 /* VariableStatement */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.declarationList);
- case 233:
+ case 233 /* VariableDeclarationList */:
return visitNodes(cbNode, cbNodes, node.declarations);
- case 216:
+ case 216 /* ExpressionStatement */:
return visitNode(cbNode, node.expression);
- case 217:
+ case 217 /* IfStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.thenStatement) ||
visitNode(cbNode, node.elseStatement);
- case 218:
+ case 218 /* DoStatement */:
return visitNode(cbNode, node.statement) ||
visitNode(cbNode, node.expression);
- case 219:
+ case 219 /* WhileStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 220:
+ case 220 /* ForStatement */:
return visitNode(cbNode, node.initializer) ||
visitNode(cbNode, node.condition) ||
visitNode(cbNode, node.incrementor) ||
visitNode(cbNode, node.statement);
- case 221:
+ case 221 /* ForInStatement */:
return visitNode(cbNode, node.initializer) ||
visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 222:
+ case 222 /* ForOfStatement */:
return visitNode(cbNode, node.awaitModifier) ||
visitNode(cbNode, node.initializer) ||
visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 223:
- case 224:
+ case 223 /* ContinueStatement */:
+ case 224 /* BreakStatement */:
return visitNode(cbNode, node.label);
- case 225:
+ case 225 /* ReturnStatement */:
return visitNode(cbNode, node.expression);
- case 226:
+ case 226 /* WithStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 227:
+ case 227 /* SwitchStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.caseBlock);
- case 241:
+ case 241 /* CaseBlock */:
return visitNodes(cbNode, cbNodes, node.clauses);
- case 266:
+ case 266 /* CaseClause */:
return visitNode(cbNode, node.expression) ||
visitNodes(cbNode, cbNodes, node.statements);
- case 267:
+ case 267 /* DefaultClause */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 228:
+ case 228 /* LabeledStatement */:
return visitNode(cbNode, node.label) ||
visitNode(cbNode, node.statement);
- case 229:
+ case 229 /* ThrowStatement */:
return visitNode(cbNode, node.expression);
- case 230:
+ case 230 /* TryStatement */:
return visitNode(cbNode, node.tryBlock) ||
visitNode(cbNode, node.catchClause) ||
visitNode(cbNode, node.finallyBlock);
- case 269:
+ case 269 /* CatchClause */:
return visitNode(cbNode, node.variableDeclaration) ||
visitNode(cbNode, node.block);
- case 150:
+ case 150 /* Decorator */:
return visitNode(cbNode, node.expression);
- case 235:
- case 205:
+ case 235 /* ClassDeclaration */:
+ case 205 /* ClassExpression */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNode, cbNodes, node.typeParameters) ||
visitNodes(cbNode, cbNodes, node.heritageClauses) ||
visitNodes(cbNode, cbNodes, node.members);
- case 236:
+ case 236 /* InterfaceDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNode, cbNodes, node.typeParameters) ||
visitNodes(cbNode, cbNodes, node.heritageClauses) ||
visitNodes(cbNode, cbNodes, node.members);
- case 237:
+ case 237 /* TypeAliasDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNode, cbNodes, node.typeParameters) ||
visitNode(cbNode, node.type);
- case 238:
+ case 238 /* EnumDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNode, cbNodes, node.members);
- case 273:
+ case 273 /* EnumMember */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.initializer);
- case 239:
+ case 239 /* ModuleDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.body);
- case 243:
+ case 243 /* ImportEqualsDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.moduleReference);
- case 244:
+ case 244 /* ImportDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.importClause) ||
visitNode(cbNode, node.moduleSpecifier);
- case 245:
+ case 245 /* ImportClause */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.namedBindings);
- case 242:
+ case 242 /* NamespaceExportDeclaration */:
return visitNode(cbNode, node.name);
- case 246:
+ case 246 /* NamespaceImport */:
return visitNode(cbNode, node.name);
- case 247:
- case 251:
+ case 247 /* NamedImports */:
+ case 251 /* NamedExports */:
return visitNodes(cbNode, cbNodes, node.elements);
- case 250:
+ case 250 /* ExportDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.exportClause) ||
visitNode(cbNode, node.moduleSpecifier);
- case 248:
- case 252:
+ case 248 /* ImportSpecifier */:
+ case 252 /* ExportSpecifier */:
return visitNode(cbNode, node.propertyName) ||
visitNode(cbNode, node.name);
- case 249:
+ case 249 /* ExportAssignment */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.expression);
- case 202:
+ case 202 /* TemplateExpression */:
return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
- case 211:
+ case 211 /* TemplateSpan */:
return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
- case 147:
+ case 147 /* ComputedPropertyName */:
return visitNode(cbNode, node.expression);
- case 268:
+ case 268 /* HeritageClause */:
return visitNodes(cbNode, cbNodes, node.types);
- case 207:
+ case 207 /* ExpressionWithTypeArguments */:
return visitNode(cbNode, node.expression) ||
visitNodes(cbNode, cbNodes, node.typeArguments);
- case 254:
+ case 254 /* ExternalModuleReference */:
return visitNode(cbNode, node.expression);
- case 253:
+ case 253 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 303:
+ case 303 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
- case 255:
+ case 255 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
visitNodes(cbNode, cbNodes, node.children) ||
visitNode(cbNode, node.closingElement);
- case 259:
+ case 259 /* JsxFragment */:
return visitNode(cbNode, node.openingFragment) ||
visitNodes(cbNode, cbNodes, node.children) ||
visitNode(cbNode, node.closingFragment);
- case 256:
- case 257:
+ case 256 /* JsxSelfClosingElement */:
+ case 257 /* JsxOpeningElement */:
return visitNode(cbNode, node.tagName) ||
visitNodes(cbNode, cbNodes, node.typeArguments) ||
visitNode(cbNode, node.attributes);
- case 263:
+ case 263 /* JsxAttributes */:
return visitNodes(cbNode, cbNodes, node.properties);
- case 262:
+ case 262 /* JsxAttribute */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.initializer);
- case 264:
+ case 264 /* JsxSpreadAttribute */:
return visitNode(cbNode, node.expression);
- case 265:
+ case 265 /* JsxExpression */:
return visitNode(cbNode, node.dotDotDotToken) ||
visitNode(cbNode, node.expression);
- case 258:
+ case 258 /* JsxClosingElement */:
return visitNode(cbNode, node.tagName);
- case 278:
+ case 278 /* JSDocTypeExpression */:
return visitNode(cbNode, node.type);
- case 282:
+ case 282 /* JSDocNonNullableType */:
return visitNode(cbNode, node.type);
- case 281:
+ case 281 /* JSDocNullableType */:
return visitNode(cbNode, node.type);
- case 283:
+ case 283 /* JSDocOptionalType */:
return visitNode(cbNode, node.type);
- case 284:
+ case 284 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 285:
+ case 285 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 286:
+ case 286 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 293:
- case 299:
+ case 293 /* JSDocParameterTag */:
+ case 299 /* JSDocPropertyTag */:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -13676,17 +15457,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
- case 294:
+ case 294 /* JSDocReturnTag */:
return visitNode(cbNode, node.typeExpression);
- case 296:
+ case 296 /* JSDocTypeTag */:
return visitNode(cbNode, node.typeExpression);
- case 290:
+ case 290 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.class);
- case 297:
+ case 297 /* JSDocTemplateTag */:
return visitNodes(cbNode, cbNodes, node.typeParameters);
- case 298:
+ case 298 /* JSDocTypedefTag */:
if (node.typeExpression &&
- node.typeExpression.kind === 278) {
+ node.typeExpression.kind === 278 /* JSDocTypeExpression */) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -13694,18 +15475,18 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 292:
+ case 292 /* JSDocCallbackTag */:
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 295:
+ case 295 /* JSDocThisTag */:
return visitNode(cbNode, node.typeExpression);
- case 288:
+ case 288 /* JSDocSignature */:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNodes(cbNode, cbNodes, node.typeParameters) ||
visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 287:
+ case 287 /* JSDocTypeLiteral */:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -13713,7 +15494,7 @@ var ts;
}
}
return;
- case 302:
+ case 302 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -13722,11 +15503,11 @@ var ts;
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
var result;
- if (languageVersion === 100) {
- result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes);
+ if (languageVersion === 100 /* JSON */) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
}
else {
- result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind);
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
}
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
@@ -13737,41 +15518,71 @@ var ts;
return Parser.parseIsolatedEntityName(text, languageVersion);
}
ts.parseIsolatedEntityName = parseIsolatedEntityName;
+ /**
+ * Parse json text into SyntaxTree and return node and parse errors if any
+ * @param fileName
+ * @param sourceText
+ */
function parseJsonText(fileName, sourceText) {
return Parser.parseJsonText(fileName, sourceText);
}
ts.parseJsonText = parseJsonText;
+ // See also `isExternalOrCommonJsModule` in utilities.ts
function isExternalModule(file) {
return file.externalModuleIndicator !== undefined;
}
ts.isExternalModule = isExternalModule;
+ // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
+ // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
+ // The SourceFile will be created with the compiler attempting to reuse as many nodes from
+ // this file as possible.
+ //
+ // Note: this function mutates nodes from this SourceFile. That means any existing nodes
+ // from this SourceFile that are being held onto may change as a result (including
+ // becoming detached from any SourceFile). It is recommended that this SourceFile not
+ // be used once 'update' is called on it.
function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
if (aggressiveChecks === void 0) { aggressiveChecks = false; }
var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
- newSourceFile.flags |= (sourceFile.flags & 1572864);
+ // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import.
+ // We will manually port the flag to the new source file.
+ newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */);
return newSourceFile;
}
ts.updateSourceFile = updateSourceFile;
+ /* @internal */
function parseIsolatedJSDocComment(content, start, length) {
var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
if (result && result.jsDoc) {
+ // because the jsDocComment was parsed out of the source file, it might
+ // not be covered by the fixupParentReferences.
Parser.fixupParentReferences(result.jsDoc);
}
return result;
}
ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
+ /* @internal */
+ // Exposed only for testing.
function parseJSDocTypeExpressionForTests(content, start, length) {
return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
}
ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
+ // Implement the parser as a singleton module. We do this for perf reasons because creating
+ // parser instances can actually be expensive enough to impact us on projects with many source
+ // files.
var Parser;
(function (Parser) {
- var scanner = ts.createScanner(6, true);
- var disallowInAndDecoratorContext = 2048 | 8192;
+ // Share a single scanner across all calls to parse a source file. This helps speed things
+ // up by avoiding the cost of creating/compiling scanners over and over again.
+ var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
+ // capture constructors in 'initializeState' to avoid null checks
+ // tslint:disable variable-name
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
+ // tslint:enable variable-name
var sourceFile;
var parseDiagnostics;
var syntaxCursor;
@@ -13781,14 +15592,87 @@ var ts;
var identifiers;
var identifierCount;
var parsingContext;
+ // Flags that dictate what parsing context we're in. For example:
+ // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
+ // that some tokens that would be considered identifiers may be considered keywords.
+ //
+ // When adding more parser context flags, consider which is the more common case that the
+ // flag will be in. This should be the 'false' state for that flag. The reason for this is
+ // that we don't store data in our nodes unless the value is in the *non-default* state. So,
+ // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
+ // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
+ // all nodes would need extra state on them to store this info.
+ //
+ // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
+ // grammar specification.
+ //
+ // An important thing about these context concepts. By default they are effectively inherited
+ // while parsing through every grammar production. i.e. if you don't change them, then when
+ // you parse a sub-production, it will have the same context values as the parent production.
+ // This is great most of the time. After all, consider all the 'expression' grammar productions
+ // and how nearly all of them pass along the 'in' and 'yield' context values:
+ //
+ // EqualityExpression[In, Yield] :
+ // RelationalExpression[?In, ?Yield]
+ // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
+ // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
+ // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
+ // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
+ //
+ // Where you have to be careful is then understanding what the points are in the grammar
+ // where the values are *not* passed along. For example:
+ //
+ // SingleNameBinding[Yield,GeneratorParameter]
+ // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
+ // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
+ //
+ // Here this is saying that if the GeneratorParameter context flag is set, that we should
+ // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
+ // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
+ // production. Conversely, if the GeneratorParameter context flag is not set, then we
+ // should leave the 'yield' context flag alone.
+ //
+ // Getting this all correct is tricky and requires careful reading of the grammar to
+ // understand when these values should be changed versus when they should be inherited.
+ //
+ // Note: it should not be necessary to save/restore these flags during speculative/lookahead
+ // parsing. These context flags are naturally stored and restored through normal recursive
+ // descent parsing and unwinding.
var contextFlags;
+ // Whether or not we've had a parse error since creating the last AST node. If we have
+ // encountered an error, it will be stored on the next AST node we create. Parse errors
+ // can be broken down into three categories:
+ //
+ // 1) An error that occurred during scanning. For example, an unterminated literal, or a
+ // character that was completely not understood.
+ //
+ // 2) A token was expected, but was not present. This type of error is commonly produced
+ // by the 'parseExpected' function.
+ //
+ // 3) A token was present that no parsing function was able to consume. This type of error
+ // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
+ // decides to skip the token.
+ //
+ // In all of these cases, we want to mark the next node as having had an error before it.
+ // With this mark, we can know in incremental settings if this node can be reused, or if
+ // we have to reparse it. If we don't keep this information around, we may just reuse the
+ // node. in that event we would then not produce the same errors as we did before, causing
+ // significant confusion problems.
+ //
+ // Note: it is necessary that this value be saved/restored during speculative/lookahead
+ // parsing. During lookahead parsing, we will often create a node. That node will have
+ // this value attached, and then this value will be set back to 'false'. If we decide to
+ // rewind, we must get back to the same value we had prior to the lookahead.
+ //
+ // Note: any errors at the end of the file that do not precede a regular node, should get
+ // attached to the EOF token.
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
- if (scriptKind === 6) {
+ if (scriptKind === 6 /* JSON */) {
var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
- ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
result_1.typeReferenceDirectives = ts.emptyArray;
result_1.amdDependencies = ts.emptyArray;
return result_1;
@@ -13800,57 +15684,62 @@ var ts;
}
Parser.parseSourceFile = parseSourceFile;
function parseIsolatedEntityName(content, languageVersion) {
- initializeState(content, languageVersion, undefined, 1);
+ // Choice of `isDeclarationFile` should be arbitrary
+ initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
+ // Prime the scanner.
nextToken();
- var entityName = parseEntityName(true);
- var isInvalid = token() === 1 && !parseDiagnostics.length;
+ var entityName = parseEntityName(/*allowReservedWords*/ true);
+ var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
clearState();
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
- if (languageVersion === void 0) { languageVersion = 2; }
- initializeState(sourceText, languageVersion, syntaxCursor, 6);
- sourceFile = createSourceFile(fileName, 2, 6, false);
+ if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
+ // Set source file so that errors will be reported with this file name
+ sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
sourceFile.flags = contextFlags;
+ // Prime the scanner.
nextToken();
var pos = getNodePos();
- if (token() === 1) {
+ if (token() === 1 /* EndOfFileToken */) {
sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
else {
- var statement = createNode(216);
+ var statement = createNode(216 /* ExpressionStatement */);
switch (token()) {
- case 21:
+ case 21 /* OpenBracketToken */:
statement.expression = parseArrayLiteralExpression();
break;
- case 101:
- case 86:
- case 95:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
statement.expression = parseTokenNode();
break;
- case 38:
- if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) {
+ case 38 /* MinusToken */:
+ if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) {
statement.expression = parsePrefixUnaryExpression();
}
else {
statement.expression = parseObjectLiteralExpression();
}
break;
- case 8:
- case 9:
- if (lookAhead(function () { return nextToken() !== 56; })) {
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) {
statement.expression = parseLiteralNode();
break;
}
+ // falls through
default:
statement.expression = parseObjectLiteralExpression();
break;
}
finishNode(statement);
sourceFile.statements = createNodeArray([statement], pos);
- sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token);
+ sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
}
if (setParentNodes) {
fixupParentReferences(sourceFile);
@@ -13862,7 +15751,8 @@ var ts;
}
Parser.parseJsonText = parseJsonText;
function getLanguageVariant(scriptKind) {
- return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0;
+ // .tsx and .jsx files are treated as jsx language variant.
+ return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
}
function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
@@ -13877,26 +15767,29 @@ var ts;
identifierCount = 0;
nodeCount = 0;
switch (scriptKind) {
- case 1:
- case 2:
- contextFlags = 65536;
+ case 1 /* JS */:
+ case 2 /* JSX */:
+ contextFlags = 65536 /* JavaScriptFile */;
break;
- case 6:
- contextFlags = 65536 | 16777216;
+ case 6 /* JSON */:
+ contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
break;
default:
- contextFlags = 0;
+ contextFlags = 0 /* None */;
break;
}
parseErrorBeforeNextFinishedNode = false;
+ // Initialize and prime the scanner before parsing the source elements.
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
scanner.setLanguageVariant(getLanguageVariant(scriptKind));
}
function clearState() {
+ // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
scanner.setText("");
scanner.setOnError(undefined);
+ // Clear any data. We don't want to accidentally hold onto it for too long.
parseDiagnostics = undefined;
sourceFile = undefined;
identifiers = undefined;
@@ -13906,15 +15799,17 @@ var ts;
function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
var isDeclarationFile = isDeclarationFileName(fileName);
if (isDeclarationFile) {
- contextFlags |= 4194304;
+ contextFlags |= 4194304 /* Ambient */;
}
sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
sourceFile.flags = contextFlags;
+ // Prime the scanner.
nextToken();
+ // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
processCommentPragmas(sourceFile, sourceText);
processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
- sourceFile.statements = parseList(0, parseStatement);
- ts.Debug.assert(token() === 1);
+ sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
+ ts.Debug.assert(token() === 1 /* EndOfFileToken */);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
setExternalModuleIndicator(sourceFile);
sourceFile.nodeCount = nodeCount;
@@ -13940,10 +15835,17 @@ var ts;
return node;
}
function fixupParentReferences(rootNode) {
+ // normally parent references are set during binding. However, for clients that only need
+ // a syntax tree, and no semantic features, then the binding process is an unnecessary
+ // overhead. This functions allows us to set all the parents, without all the expense of
+ // binding.
var parent = rootNode;
forEachChild(rootNode, visitNode);
return;
function visitNode(n) {
+ // walk down setting parents that differ from the parent we think it should be. This
+ // allows us to quickly bail out of setting parents for subtrees during incremental
+ // parsing
if (n.parent !== parent) {
n.parent = parent;
var saveParent = parent;
@@ -13963,7 +15865,9 @@ var ts;
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
- var sourceFile = new SourceFileConstructor(274, 0, 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(274 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -13984,81 +15888,102 @@ var ts;
}
}
function setDisallowInContext(val) {
- setContextFlag(val, 2048);
+ setContextFlag(val, 2048 /* DisallowInContext */);
}
function setYieldContext(val) {
- setContextFlag(val, 4096);
+ setContextFlag(val, 4096 /* YieldContext */);
}
function setDecoratorContext(val) {
- setContextFlag(val, 8192);
+ setContextFlag(val, 8192 /* DecoratorContext */);
}
function setAwaitContext(val) {
- setContextFlag(val, 16384);
+ setContextFlag(val, 16384 /* AwaitContext */);
}
function doOutsideOfContext(context, func) {
+ // contextFlagsToClear will contain only the context flags that are
+ // currently set that we need to temporarily clear
+ // We don't just blindly reset to the previous flags to ensure
+ // that we do not mutate cached flags for the incremental
+ // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
+ // HasAggregatedChildData).
var contextFlagsToClear = context & contextFlags;
if (contextFlagsToClear) {
- setContextFlag(false, contextFlagsToClear);
+ // clear the requested context flags
+ setContextFlag(/*val*/ false, contextFlagsToClear);
var result = func();
- setContextFlag(true, contextFlagsToClear);
+ // restore the context flags we just cleared
+ setContextFlag(/*val*/ true, contextFlagsToClear);
return result;
}
+ // no need to do anything special as we are not in any of the requested contexts
return func();
}
function doInsideOfContext(context, func) {
+ // contextFlagsToSet will contain only the context flags that
+ // are not currently set that we need to temporarily enable.
+ // We don't just blindly reset to the previous flags to ensure
+ // that we do not mutate cached flags for the incremental
+ // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
+ // HasAggregatedChildData).
var contextFlagsToSet = context & ~contextFlags;
if (contextFlagsToSet) {
- setContextFlag(true, contextFlagsToSet);
+ // set the requested context flags
+ setContextFlag(/*val*/ true, contextFlagsToSet);
var result = func();
- setContextFlag(false, contextFlagsToSet);
+ // reset the context flags we just set
+ setContextFlag(/*val*/ false, contextFlagsToSet);
return result;
}
+ // no need to do anything special as we are already in all of the requested contexts
return func();
}
function allowInAnd(func) {
- return doOutsideOfContext(2048, func);
+ return doOutsideOfContext(2048 /* DisallowInContext */, func);
}
function disallowInAnd(func) {
- return doInsideOfContext(2048, func);
+ return doInsideOfContext(2048 /* DisallowInContext */, func);
}
function doInYieldContext(func) {
- return doInsideOfContext(4096, func);
+ return doInsideOfContext(4096 /* YieldContext */, func);
}
function doInDecoratorContext(func) {
- return doInsideOfContext(8192, func);
+ return doInsideOfContext(8192 /* DecoratorContext */, func);
}
function doInAwaitContext(func) {
- return doInsideOfContext(16384, func);
+ return doInsideOfContext(16384 /* AwaitContext */, func);
}
function doOutsideOfAwaitContext(func) {
- return doOutsideOfContext(16384, func);
+ return doOutsideOfContext(16384 /* AwaitContext */, func);
}
function doInYieldAndAwaitContext(func) {
- return doInsideOfContext(4096 | 16384, func);
+ return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func);
}
function inContext(flags) {
return (contextFlags & flags) !== 0;
}
function inYieldContext() {
- return inContext(4096);
+ return inContext(4096 /* YieldContext */);
}
function inDisallowInContext() {
- return inContext(2048);
+ return inContext(2048 /* DisallowInContext */);
}
function inDecoratorContext() {
- return inContext(8192);
+ return inContext(8192 /* DecoratorContext */);
}
function inAwaitContext() {
- return inContext(16384);
+ return inContext(16384 /* AwaitContext */);
}
function parseErrorAtCurrentToken(message, arg0) {
parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
}
function parseErrorAtPosition(start, length, message, arg0) {
+ // Don't report another error if it would just be at the same position as the last error.
var lastError = ts.lastOrUndefined(parseDiagnostics);
if (!lastError || start !== lastError.start) {
parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
}
+ // Mark that we've encountered an error. We'll set an appropriate bit on the next
+ // node we finish so that it can't be reused incrementally.
parseErrorBeforeNextFinishedNode = true;
}
function parseErrorAt(start, end, message, arg0) {
@@ -14073,6 +15998,12 @@ var ts;
function getNodePos() {
return scanner.getStartPos();
}
+ // Use this function to access the current token instead of reading the currentToken
+ // variable. Since function results aren't narrowed in control flow analysis, this ensures
+ // that the type checker doesn't make wrong assumptions about the type of the current
+ // token (e.g. a call to nextToken() changes the current token but the checker doesn't
+ // reason about this side effect). Mainstream VMs inline simple functions like this, so
+ // there is no performance penalty.
function token() {
return currentToken;
}
@@ -14098,14 +16029,25 @@ var ts;
return currentToken = scanner.scanJsxAttributeValue();
}
function speculationHelper(callback, isLookAhead) {
+ // Keep track of the state we'll need to rollback to if lookahead fails (or if the
+ // caller asked us to always reset our state).
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
+ // Note: it is not actually necessary to save/restore the context flags here. That's
+ // because the saving/restoring of these flags happens naturally through the recursive
+ // descent nature of our parser. However, we still store this here just so we can
+ // assert that invariant holds.
var saveContextFlags = contextFlags;
+ // If we're only looking ahead, then tell the scanner to only lookahead as well.
+ // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
+ // same.
var result = isLookAhead
? scanner.lookAhead(callback)
: scanner.tryScan(callback);
ts.Debug.assert(saveContextFlags === contextFlags);
+ // If our callback returned something 'falsy' or we're just looking ahead,
+ // then unconditionally restore us to where we were.
if (!result || isLookAhead) {
currentToken = saveToken;
parseDiagnostics.length = saveParseDiagnosticsLength;
@@ -14113,23 +16055,37 @@ var ts;
}
return result;
}
+ /** Invokes the provided callback then unconditionally restores the parser to the state it
+ * was in immediately prior to invoking the callback. The result of invoking the callback
+ * is returned from this function.
+ */
function lookAhead(callback) {
- return speculationHelper(callback, true);
+ return speculationHelper(callback, /*isLookAhead*/ true);
}
+ /** Invokes the provided callback. If the callback returns something falsy, then it restores
+ * the parser to the state it was in immediately prior to invoking the callback. If the
+ * callback returns something truthy, then the parser state is not rolled back. The result
+ * of invoking the callback is returned from this function.
+ */
function tryParse(callback) {
- return speculationHelper(callback, false);
+ return speculationHelper(callback, /*isLookAhead*/ false);
}
+ // Ignore strict mode flag because we will report an error in type checker instead.
function isIdentifier() {
- if (token() === 71) {
+ if (token() === 71 /* Identifier */) {
return true;
}
- if (token() === 116 && inYieldContext()) {
+ // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
+ // considered a keyword and is not an identifier.
+ if (token() === 116 /* YieldKeyword */ && inYieldContext()) {
return false;
}
- if (token() === 121 && inAwaitContext()) {
+ // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
+ // considered a keyword and is not an identifier.
+ if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) {
return false;
}
- return token() > 107;
+ return token() > 107 /* LastReservedWord */;
}
function parseExpected(kind, diagnosticMessage, shouldAdvance) {
if (shouldAdvance === void 0) { shouldAdvance = true; }
@@ -14139,6 +16095,7 @@ var ts;
}
return true;
}
+ // Report specific message if provided with one. Otherwise, report generic fallback message.
if (diagnosticMessage) {
parseErrorAtCurrentToken(diagnosticMessage);
}
@@ -14162,7 +16119,7 @@ var ts;
}
function parseExpectedToken(t, diagnosticMessage, arg0) {
return parseOptionalToken(t) ||
- createMissingNode(t, false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
+ createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
}
function parseTokenNode() {
var node = createNode(token());
@@ -14170,37 +16127,43 @@ var ts;
return finishNode(node);
}
function canParseSemicolon() {
- if (token() === 25) {
+ // If there's a real semicolon, then we can always parse it out.
+ if (token() === 25 /* SemicolonToken */) {
return true;
}
- return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak();
+ // We can parse out an optional semicolon in ASI cases in the following cases.
+ return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
}
function parseSemicolon() {
if (canParseSemicolon()) {
- if (token() === 25) {
+ if (token() === 25 /* SemicolonToken */) {
+ // consume the semicolon if it was explicitly provided.
nextToken();
}
return true;
}
else {
- return parseExpected(25);
+ return parseExpected(25 /* SemicolonToken */);
}
}
function createNode(kind, pos) {
nodeCount++;
var p = pos >= 0 ? pos : scanner.getStartPos();
- return ts.isNodeKind(kind) || kind === 0 ? new NodeConstructor(kind, p, p) :
- kind === 71 ? new IdentifierConstructor(kind, p, p) :
+ return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
+ kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
new TokenConstructor(kind, p, p);
}
function createNodeWithJSDoc(kind, pos) {
var node = createNode(kind, pos);
- if (scanner.getTokenFlags() & 2) {
+ if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) {
addJSDocComment(node);
}
return node;
}
function createNodeArray(elements, pos, end) {
+ // Since the element list of a node array is typically created by starting with an empty array and
+ // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
+ // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
var length = elements.length;
var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
array.pos = pos;
@@ -14212,9 +16175,12 @@ var ts;
if (contextFlags) {
node.flags |= contextFlags;
}
+ // Keep track on the node if we encountered an error while parsing it. If we did, then
+ // we cannot reuse the node incrementally. Once we've marked this node, clear out the
+ // flag so that we don't mark any subsequent nodes.
if (parseErrorBeforeNextFinishedNode) {
parseErrorBeforeNextFinishedNode = false;
- node.flags |= 32768;
+ node.flags |= 32768 /* ThisNodeHasError */;
}
return node;
}
@@ -14226,7 +16192,7 @@ var ts;
parseErrorAtCurrentToken(diagnosticMessage, arg0);
}
var result = createNode(kind);
- if (kind === 71) {
+ if (kind === 71 /* Identifier */) {
result.escapedText = "";
}
else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
@@ -14241,19 +16207,24 @@ var ts;
}
return identifier;
}
+ // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
+ // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
+ // each identifier in order to reduce memory consumption.
function createIdentifier(isIdentifier, diagnosticMessage) {
identifierCount++;
if (isIdentifier) {
- var node = createNode(71);
- if (token() !== 71) {
+ var node = createNode(71 /* Identifier */);
+ // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
+ if (token() !== 71 /* Identifier */) {
node.originalKeywordKind = token();
}
node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
nextToken();
return finishNode(node);
}
- var reportAtCurrentPosition = token() === 1;
- return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected);
+ // Only for end of file because the error gets reported incorrectly on embedded script tags.
+ var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
+ return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected);
}
function parseIdentifier(diagnosticMessage) {
return createIdentifier(isIdentifier(), diagnosticMessage);
@@ -14263,28 +16234,34 @@ var ts;
}
function isLiteralPropertyName() {
return ts.tokenIsIdentifierOrKeyword(token()) ||
- token() === 9 ||
- token() === 8;
+ token() === 9 /* StringLiteral */ ||
+ token() === 8 /* NumericLiteral */;
}
function parsePropertyNameWorker(allowComputedPropertyNames) {
- if (token() === 9 || token() === 8) {
+ if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
var node = parseLiteralNode();
node.text = internIdentifier(node.text);
return node;
}
- if (allowComputedPropertyNames && token() === 21) {
+ if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) {
return parseComputedPropertyName();
}
return parseIdentifierName();
}
function parsePropertyName() {
- return parsePropertyNameWorker(true);
+ return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
}
function parseComputedPropertyName() {
- var node = createNode(147);
- parseExpected(21);
+ // PropertyName [Yield]:
+ // LiteralPropertyName
+ // ComputedPropertyName[?Yield]
+ var node = createNode(147 /* ComputedPropertyName */);
+ parseExpected(21 /* OpenBracketToken */);
+ // We parse any expression (including a comma expression). But the grammar
+ // says that only an assignment expression is allowed, so the grammar checker
+ // will error if it sees a comma expression.
node.expression = allowInAnd(parseExpression);
- parseExpected(22);
+ parseExpected(22 /* CloseBracketToken */);
return finishNode(node);
}
function parseContextualModifier(t) {
@@ -14299,19 +16276,20 @@ var ts;
}
function nextTokenCanFollowModifier() {
switch (token()) {
- case 76:
- return nextToken() === 83;
- case 84:
+ case 76 /* ConstKeyword */:
+ // 'const' is only a modifier if followed by 'enum'.
+ return nextToken() === 83 /* EnumKeyword */;
+ case 84 /* ExportKeyword */:
nextToken();
- if (token() === 79) {
+ if (token() === 79 /* DefaultKeyword */) {
return lookAhead(nextTokenCanFollowDefaultKeyword);
}
- return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier();
- case 79:
+ return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier();
+ case 79 /* DefaultKeyword */:
return nextTokenCanFollowDefaultKeyword();
- case 115:
- case 125:
- case 136:
+ case 115 /* StaticKeyword */:
+ case 125 /* GetKeyword */:
+ case 136 /* SetKeyword */:
nextToken();
return canFollowModifier();
default:
@@ -14322,86 +16300,112 @@ var ts;
return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
}
function canFollowModifier() {
- return token() === 21
- || token() === 17
- || token() === 39
- || token() === 24
+ return token() === 21 /* OpenBracketToken */
+ || token() === 17 /* OpenBraceToken */
+ || token() === 39 /* AsteriskToken */
+ || token() === 24 /* DotDotDotToken */
|| isLiteralPropertyName();
}
function nextTokenCanFollowDefaultKeyword() {
nextToken();
- return token() === 75 || token() === 89 ||
- token() === 109 ||
- (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
- (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
+ return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ ||
+ token() === 109 /* InterfaceKeyword */ ||
+ (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
+ (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
}
+ // True if positioned at the start of a list element
function isListElement(parsingContext, inErrorRecovery) {
var node = currentNode(parsingContext);
if (node) {
return true;
}
switch (parsingContext) {
- case 0:
- case 1:
- case 3:
- return !(token() === 25 && inErrorRecovery) && isStartOfStatement();
- case 2:
- return token() === 73 || token() === 79;
- case 4:
+ case 0 /* SourceElements */:
+ case 1 /* BlockStatements */:
+ case 3 /* SwitchClauseStatements */:
+ // If we're in error recovery, then we don't want to treat ';' as an empty statement.
+ // The problem is that ';' can show up in far too many contexts, and if we see one
+ // and assume it's a statement, then we may bail out inappropriately from whatever
+ // we're parsing. For example, if we have a semicolon in the middle of a class, then
+ // we really don't want to assume the class is over and we're on a statement in the
+ // outer module. We just want to consume and move on.
+ return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
+ case 2 /* SwitchClauses */:
+ return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */;
+ case 4 /* TypeMembers */:
return lookAhead(isTypeMemberStart);
- case 5:
- return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery);
- case 6:
- return token() === 21 || isLiteralPropertyName();
- case 12:
- return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName();
- case 17:
+ case 5 /* ClassMembers */:
+ // We allow semicolons as class elements (as specified by ES6) as long as we're
+ // not in error recovery. If we're in error recovery, we don't want an errant
+ // semicolon to be treated as a class member (since they're almost always used
+ // for statements.
+ return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery);
+ case 6 /* EnumMembers */:
+ // Include open bracket computed properties. This technically also lets in indexers,
+ // which would be a candidate for improved error reporting.
+ return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName();
+ case 12 /* ObjectLiteralMembers */:
+ return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName();
+ case 17 /* RestProperties */:
return isLiteralPropertyName();
- case 9:
- return token() === 21 || token() === 24 || isLiteralPropertyName();
- case 7:
- if (token() === 17) {
+ case 9 /* ObjectBindingElements */:
+ return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || 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.
+ if (token() === 17 /* OpenBraceToken */) {
return lookAhead(isValidHeritageClauseObjectLiteral);
}
if (!inErrorRecovery) {
return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
}
else {
+ // If we're in error recovery we tighten up what we're willing to match.
+ // That way we don't treat something like "this" as a valid heritage clause
+ // element during recovery.
return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
}
- case 8:
+ case 8 /* VariableDeclarations */:
return isIdentifierOrPattern();
- case 10:
- return token() === 26 || token() === 24 || isIdentifierOrPattern();
- case 18:
+ case 10 /* ArrayBindingElements */:
+ return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern();
+ case 18 /* TypeParameters */:
return isIdentifier();
- case 15:
- if (token() === 26) {
+ case 15 /* ArrayLiteralMembers */:
+ if (token() === 26 /* CommaToken */) {
return true;
}
- case 11:
- return token() === 24 || isStartOfExpression();
- case 16:
+ // falls through
+ case 11 /* ArgumentExpressions */:
+ return token() === 24 /* DotDotDotToken */ || isStartOfExpression();
+ case 16 /* Parameters */:
return isStartOfParameter();
- case 19:
- case 20:
- return token() === 26 || isStartOfType();
- case 21:
+ case 19 /* TypeArguments */:
+ case 20 /* TupleElementTypes */:
+ return token() === 26 /* CommaToken */ || isStartOfType();
+ case 21 /* HeritageClauses */:
return isHeritageClause();
- case 22:
+ case 22 /* ImportOrExportSpecifiers */:
return ts.tokenIsIdentifierOrKeyword(token());
- case 13:
- return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17;
- case 14:
+ case 13 /* JsxAttributes */:
+ return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */;
+ case 14 /* JsxChildren */:
return true;
}
return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
}
function isValidHeritageClauseObjectLiteral() {
- ts.Debug.assert(token() === 17);
- if (nextToken() === 18) {
+ ts.Debug.assert(token() === 17 /* OpenBraceToken */);
+ if (nextToken() === 18 /* CloseBraceToken */) {
+ // if we see "extends {}" then only treat the {} as what we're extending (and not
+ // the class body) if we have:
+ //
+ // extends {} {
+ // extends {},
+ // extends {} extends
+ // extends {} implements
var next = nextToken();
- return next === 26 || next === 17 || next === 85 || next === 108;
+ return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */;
}
return true;
}
@@ -14418,8 +16422,8 @@ var ts;
return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
}
function isHeritageClauseExtendsOrImplementsKeyword() {
- if (token() === 108 ||
- token() === 85) {
+ if (token() === 108 /* ImplementsKeyword */ ||
+ token() === 85 /* ExtendsKeyword */) {
return lookAhead(nextTokenIsStartOfExpression);
}
return false;
@@ -14432,78 +16436,95 @@ var ts;
nextToken();
return isStartOfType();
}
+ // True if positioned at a list terminator
function isListTerminator(kind) {
- if (token() === 1) {
+ if (token() === 1 /* EndOfFileToken */) {
+ // Being at the end of the file ends all lists.
return true;
}
switch (kind) {
- case 1:
- case 2:
- case 4:
- case 5:
- case 6:
- case 12:
- case 9:
- case 22:
- return token() === 18;
- case 3:
- return token() === 18 || token() === 73 || token() === 79;
- case 7:
- return token() === 17 || token() === 85 || token() === 108;
- case 8:
+ case 1 /* BlockStatements */:
+ case 2 /* SwitchClauses */:
+ case 4 /* TypeMembers */:
+ case 5 /* ClassMembers */:
+ case 6 /* EnumMembers */:
+ case 12 /* ObjectLiteralMembers */:
+ case 9 /* ObjectBindingElements */:
+ case 22 /* ImportOrExportSpecifiers */:
+ return token() === 18 /* CloseBraceToken */;
+ case 3 /* SwitchClauseStatements */:
+ return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */;
+ case 7 /* HeritageClauseElement */:
+ return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */;
+ case 8 /* VariableDeclarations */:
return isVariableDeclaratorListTerminator();
- case 18:
- return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108;
- case 11:
- return token() === 20 || token() === 25;
- case 15:
- case 20:
- case 10:
- return token() === 22;
- case 16:
- case 17:
- return token() === 20 || token() === 22;
- case 19:
- return token() !== 26;
- case 21:
- return token() === 17 || token() === 18;
- case 13:
- return token() === 29 || token() === 41;
- case 14:
- return token() === 27 && lookAhead(nextTokenIsSlash);
+ case 18 /* TypeParameters */:
+ // Tokens other than '>' are here for better error recovery
+ return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */;
+ case 11 /* ArgumentExpressions */:
+ // Tokens other than ')' are here for better error recovery
+ return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */;
+ case 15 /* ArrayLiteralMembers */:
+ case 20 /* TupleElementTypes */:
+ case 10 /* ArrayBindingElements */:
+ return token() === 22 /* CloseBracketToken */;
+ case 16 /* Parameters */:
+ case 17 /* RestProperties */:
+ // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
+ return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
+ case 19 /* TypeArguments */:
+ // All other tokens should cause the type-argument to terminate except comma token
+ return token() !== 26 /* CommaToken */;
+ case 21 /* HeritageClauses */:
+ return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */;
+ case 13 /* JsxAttributes */:
+ return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */;
+ case 14 /* JsxChildren */:
+ return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
default:
return false;
}
}
function isVariableDeclaratorListTerminator() {
+ // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
+ // with parsing the list of variable declarators.
if (canParseSemicolon()) {
return true;
}
+ // in the case where we're parsing the variable declarator of a 'for-in' statement, we
+ // are done if we see an 'in' keyword in front of us. Same with for-of
if (isInOrOfKeyword(token())) {
return true;
}
- if (token() === 36) {
+ // ERROR RECOVERY TWEAK:
+ // For better error recovery, if we see an '=>' then we just stop immediately. We've got an
+ // arrow function here and it's going to be very unlikely that we'll resynchronize and get
+ // another variable declaration.
+ if (token() === 36 /* EqualsGreaterThanToken */) {
return true;
}
+ // Keep trying to parse out variable declarators.
return false;
}
+ // True if positioned at element or terminator of the current list or any enclosing list
function isInSomeParsingContext() {
- for (var kind = 0; kind < 23; kind++) {
+ for (var kind = 0; kind < 23 /* Count */; kind++) {
if (parsingContext & (1 << kind)) {
- if (isListElement(kind, true) || isListTerminator(kind)) {
+ if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
return true;
}
}
}
return false;
}
+ // Parses a list of elements
function parseList(kind, parseElement) {
var saveParsingContext = parsingContext;
parsingContext |= 1 << kind;
var list = [];
var listPos = getNodePos();
while (!isListTerminator(kind)) {
- if (isListElement(kind, false)) {
+ if (isListElement(kind, /*inErrorRecovery*/ false)) {
var element = parseListElement(kind, parseElement);
list.push(element);
continue;
@@ -14523,85 +16544,145 @@ var ts;
return parseElement();
}
function currentNode(parsingContext) {
+ // If there is an outstanding parse error that we've encountered, but not attached to
+ // some node, then we cannot get a node from the old source tree. This is because we
+ // want to mark the next node we encounter as being unusable.
+ //
+ // Note: This may be too conservative. Perhaps we could reuse the node and set the bit
+ // on it (or its leftmost child) as having the error. For now though, being conservative
+ // is nice and likely won't ever affect perf.
if (parseErrorBeforeNextFinishedNode) {
return undefined;
}
if (!syntaxCursor) {
+ // if we don't have a cursor, we could never return a node from the old tree.
return undefined;
}
var node = syntaxCursor.currentNode(scanner.getStartPos());
+ // Can't reuse a missing node.
if (ts.nodeIsMissing(node)) {
return undefined;
}
+ // Can't reuse a node that intersected the change range.
if (node.intersectsChange) {
return undefined;
}
+ // Can't reuse a node that contains a parse error. This is necessary so that we
+ // produce the same set of errors again.
if (ts.containsParseError(node)) {
return undefined;
}
- var nodeContextFlags = node.flags & 12679168;
+ // We can only reuse a node if it was parsed under the same strict mode that we're
+ // currently in. i.e. if we originally parsed a node in non-strict mode, but then
+ // the user added 'using strict' at the top of the file, then we can't use that node
+ // again as the presence of strict mode may cause us to parse the tokens in the file
+ // differently.
+ //
+ // Note: we *can* reuse tokens when the strict mode changes. That's because tokens
+ // are unaffected by strict mode. It's just the parser will decide what to do with it
+ // differently depending on what mode it is in.
+ //
+ // This also applies to all our other context flags as well.
+ var nodeContextFlags = node.flags & 12679168 /* ContextFlags */;
if (nodeContextFlags !== contextFlags) {
return undefined;
}
+ // Ok, we have a node that looks like it could be reused. Now verify that it is valid
+ // in the current list parsing context that we're currently at.
if (!canReuseNode(node, parsingContext)) {
return undefined;
}
if (node.jsDocCache) {
+ // jsDocCache may include tags from parent nodes, which might have been modified.
node.jsDocCache = undefined;
}
return node;
}
function consumeNode(node) {
+ // Move the scanner so it is after the node we just consumed.
scanner.setTextPos(node.end);
nextToken();
return node;
}
function canReuseNode(node, parsingContext) {
switch (parsingContext) {
- case 5:
+ case 5 /* ClassMembers */:
return isReusableClassMember(node);
- case 2:
+ case 2 /* SwitchClauses */:
return isReusableSwitchClause(node);
- case 0:
- case 1:
- case 3:
+ case 0 /* SourceElements */:
+ case 1 /* BlockStatements */:
+ case 3 /* SwitchClauseStatements */:
return isReusableStatement(node);
- case 6:
+ case 6 /* EnumMembers */:
return isReusableEnumMember(node);
- case 4:
+ case 4 /* TypeMembers */:
return isReusableTypeMember(node);
- case 8:
+ case 8 /* VariableDeclarations */:
return isReusableVariableDeclaration(node);
- case 16:
+ case 16 /* Parameters */:
return isReusableParameter(node);
- case 17:
+ case 17 /* RestProperties */:
return false;
- case 21:
- case 18:
- case 20:
- case 19:
- case 11:
- case 12:
- case 7:
- case 13:
- case 14:
+ // Any other lists we do not care about reusing nodes in. But feel free to add if
+ // you can do so safely. Danger areas involve nodes that may involve speculative
+ // parsing. If speculative parsing is involved with the node, then the range the
+ // parser reached while looking ahead might be in the edited range (see the example
+ // in canReuseVariableDeclaratorNode for a good case of this).
+ case 21 /* HeritageClauses */:
+ // This would probably be safe to reuse. There is no speculative parsing with
+ // heritage clauses.
+ case 18 /* TypeParameters */:
+ // This would probably be safe to reuse. There is no speculative parsing with
+ // type parameters. Note that that's because type *parameters* only occur in
+ // unambiguous *type* contexts. While type *arguments* occur in very ambiguous
+ // *expression* contexts.
+ case 20 /* TupleElementTypes */:
+ // This would probably be safe to reuse. There is no speculative parsing with
+ // tuple types.
+ // Technically, type argument list types are probably safe to reuse. While
+ // speculative parsing is involved with them (since type argument lists are only
+ // produced from speculative parsing a < as a type argument list), we only have
+ // the types because speculative parsing succeeded. Thus, the lookahead never
+ // went past the end of the list and rewound.
+ case 19 /* TypeArguments */:
+ // Note: these are almost certainly not safe to ever reuse. Expressions commonly
+ // need a large amount of lookahead, and we should not reuse them as they may
+ // have actually intersected the edit.
+ case 11 /* ArgumentExpressions */:
+ // This is not safe to reuse for the same reason as the 'AssignmentExpression'
+ // cases. i.e. a property assignment may end with an expression, and thus might
+ // have lookahead far beyond it's old node.
+ case 12 /* ObjectLiteralMembers */:
+ // This is probably not safe to reuse. There can be speculative parsing with
+ // type names in a heritage clause. There can be generic names in the type
+ // name list, and there can be left hand side expressions (which can have type
+ // arguments.)
+ case 7 /* HeritageClauseElement */:
+ // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
+ // on any given element. Same for children.
+ case 13 /* JsxAttributes */:
+ case 14 /* JsxChildren */:
}
return false;
}
function isReusableClassMember(node) {
if (node) {
switch (node.kind) {
- case 155:
- case 160:
- case 156:
- case 157:
- case 152:
- case 212:
+ case 155 /* Constructor */:
+ case 160 /* IndexSignature */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ case 152 /* PropertyDeclaration */:
+ case 212 /* SemicolonClassElement */:
return true;
- case 154:
+ case 154 /* MethodDeclaration */:
+ // Method declarations are not necessarily reusable. An object-literal
+ // may have a method calls "constructor(...)" and we must reparse that
+ // into an actual .ConstructorDeclaration.
var methodDeclaration = node;
- var nameIsConstructor = methodDeclaration.name.kind === 71 &&
- methodDeclaration.name.originalKeywordKind === 123;
+ var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ &&
+ methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */;
return !nameIsConstructor;
}
}
@@ -14610,8 +16691,8 @@ var ts;
function isReusableSwitchClause(node) {
if (node) {
switch (node.kind) {
- case 266:
- case 267:
+ case 266 /* CaseClause */:
+ case 267 /* DefaultClause */:
return true;
}
}
@@ -14620,70 +16701,86 @@ var ts;
function isReusableStatement(node) {
if (node) {
switch (node.kind) {
- case 234:
- case 214:
- case 213:
- case 217:
- case 216:
- case 229:
- case 225:
- case 227:
- case 224:
- case 223:
- case 221:
- case 222:
- case 220:
- case 219:
- case 226:
- case 215:
- case 230:
- case 228:
- case 218:
- case 231:
- case 244:
- case 243:
- case 250:
- case 249:
- case 239:
- case 235:
- case 236:
- case 238:
- case 237:
+ case 234 /* FunctionDeclaration */:
+ case 214 /* VariableStatement */:
+ case 213 /* Block */:
+ case 217 /* IfStatement */:
+ case 216 /* ExpressionStatement */:
+ case 229 /* ThrowStatement */:
+ case 225 /* ReturnStatement */:
+ case 227 /* SwitchStatement */:
+ case 224 /* BreakStatement */:
+ case 223 /* ContinueStatement */:
+ case 221 /* ForInStatement */:
+ case 222 /* ForOfStatement */:
+ case 220 /* ForStatement */:
+ case 219 /* WhileStatement */:
+ case 226 /* WithStatement */:
+ case 215 /* EmptyStatement */:
+ case 230 /* TryStatement */:
+ case 228 /* LabeledStatement */:
+ case 218 /* DoStatement */:
+ case 231 /* DebuggerStatement */:
+ case 244 /* ImportDeclaration */:
+ case 243 /* ImportEqualsDeclaration */:
+ case 250 /* ExportDeclaration */:
+ case 249 /* ExportAssignment */:
+ case 239 /* ModuleDeclaration */:
+ case 235 /* ClassDeclaration */:
+ case 236 /* InterfaceDeclaration */:
+ case 238 /* EnumDeclaration */:
+ case 237 /* TypeAliasDeclaration */:
return true;
}
}
return false;
}
function isReusableEnumMember(node) {
- return node.kind === 273;
+ return node.kind === 273 /* EnumMember */;
}
function isReusableTypeMember(node) {
if (node) {
switch (node.kind) {
- case 159:
- case 153:
- case 160:
- case 151:
- case 158:
+ case 159 /* ConstructSignature */:
+ case 153 /* MethodSignature */:
+ case 160 /* IndexSignature */:
+ case 151 /* PropertySignature */:
+ case 158 /* CallSignature */:
return true;
}
}
return false;
}
function isReusableVariableDeclaration(node) {
- if (node.kind !== 232) {
+ if (node.kind !== 232 /* VariableDeclaration */) {
return false;
}
+ // Very subtle incremental parsing bug. Consider the following code:
+ //
+ // let v = new List < A, B
+ //
+ // This is actually legal code. It's a list of variable declarators "v = new List()
+ //
+ // then we have a problem. "v = new List= 0) {
+ // Always preserve a trailing comma by marking it on the NodeArray
result.hasTrailingComma = true;
}
return result;
@@ -14775,8 +16891,9 @@ var ts;
function parseEntityName(allowReservedWords, diagnosticMessage) {
var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
var dotPos = scanner.getStartPos();
- while (parseOptional(23)) {
- if (token() === 27) {
+ while (parseOptional(23 /* DotToken */)) {
+ if (token() === 27 /* LessThanToken */) {
+ // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
entity.jsdocDotPos = dotPos;
break;
}
@@ -14786,42 +16903,64 @@ var ts;
return entity;
}
function createQualifiedName(entity, name) {
- var node = createNode(146, entity.pos);
+ var node = createNode(146 /* QualifiedName */, entity.pos);
node.left = entity;
node.right = name;
return finishNode(node);
}
function parseRightSideOfDot(allowIdentifierNames) {
+ // Technically a keyword is valid here as all identifiers and keywords are identifier names.
+ // However, often we'll encounter this in error situations when the identifier or keyword
+ // is actually starting another valid construct.
+ //
+ // So, we check for the following specific case:
+ //
+ // name.
+ // identifierOrKeyword identifierNameOrKeyword
+ //
+ // Note: the newlines are important here. For example, if that above code
+ // were rewritten into:
+ //
+ // name.identifierOrKeyword
+ // identifierNameOrKeyword
+ //
+ // Then we would consider it valid. That's because ASI would take effect and
+ // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
+ // In the first case though, ASI will not take effect because there is not a
+ // line terminator after the identifier or keyword.
if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
if (matchesPattern) {
- return createMissingNode(71, true, ts.Diagnostics.Identifier_expected);
+ // 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(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
}
}
return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
}
function parseTemplateExpression() {
- var template = createNode(202);
+ var template = createNode(202 /* TemplateExpression */);
template.head = parseTemplateHead();
- ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind");
+ ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind");
var list = [];
var listPos = getNodePos();
do {
list.push(parseTemplateSpan());
- } while (ts.last(list).literal.kind === 15);
+ } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */);
template.templateSpans = createNodeArray(list, listPos);
return finishNode(template);
}
function parseTemplateSpan() {
- var span = createNode(211);
+ var span = createNode(211 /* TemplateSpan */);
span.expression = allowInAnd(parseExpression);
var literal;
- if (token() === 18) {
+ if (token() === 18 /* CloseBraceToken */) {
reScanTemplateToken();
literal = parseTemplateMiddleOrTemplateTail();
}
else {
- literal = parseExpectedToken(16, ts.Diagnostics._0_expected, ts.tokenToString(18));
+ literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */));
}
span.literal = literal;
return finishNode(span);
@@ -14831,12 +16970,12 @@ var ts;
}
function parseTemplateHead() {
var fragment = parseLiteralLikeNode(token());
- ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind");
+ ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind");
return fragment;
}
function parseTemplateMiddleOrTemplateTail() {
var fragment = parseLiteralLikeNode(token());
- ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind");
+ ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind");
return fragment;
}
function parseLiteralLikeNode(kind) {
@@ -14849,31 +16988,40 @@ var ts;
if (scanner.isUnterminated()) {
node.isUnterminated = true;
}
- if (node.kind === 8) {
- node.numericLiteralFlags = scanner.getTokenFlags() & 1008;
+ // Octal literals are not allowed in strict mode or ES5
+ // Note that theoretically the following condition would hold true literals like 009,
+ // which is not octal.But because of how the scanner separates the tokens, we would
+ // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
+ // We also do not need to check for negatives because any prefix operator would be part of a
+ // parent unary expression.
+ if (node.kind === 8 /* NumericLiteral */) {
+ node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
}
nextToken();
finishNode(node);
return node;
}
+ // TYPES
function parseTypeReference() {
- var node = createNode(162);
- node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected);
- if (!scanner.hasPrecedingLineBreak() && token() === 27) {
- node.typeArguments = parseBracketedList(19, parseType, 27, 29);
+ var node = createNode(162 /* TypeReference */);
+ node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
+ if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) {
+ node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */);
}
return finishNode(node);
}
+ // If true, we should abort parsing an error function.
function typeHasArrowFunctionBlockingParseError(node) {
switch (node.kind) {
- case 162:
+ case 162 /* TypeReference */:
return ts.nodeIsMissing(node.typeName);
- case 163:
- case 164: {
+ case 163 /* FunctionType */:
+ case 164 /* ConstructorType */: {
var _a = node, parameters = _a.parameters, type = _a.type;
+ // parameters.pos === parameters.end only if we used parseMissingList, else should contain at least `()`
return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type);
}
- case 173:
+ case 173 /* ParenthesizedType */:
return typeHasArrowFunctionBlockingParseError(node.type);
default:
return false;
@@ -14881,20 +17029,20 @@ var ts;
}
function parseThisTypePredicate(lhs) {
nextToken();
- var node = createNode(161, lhs.pos);
+ var node = createNode(161 /* TypePredicate */, lhs.pos);
node.parameterName = lhs;
node.type = parseType();
return finishNode(node);
}
function parseThisTypeNode() {
- var node = createNode(174);
+ var node = createNode(174 /* ThisType */);
nextToken();
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(279);
+ var result = createNode(279 /* JSDocAllType */);
if (postFixEquals) {
- return createJSDocPostfixType(283, result);
+ return createJSDocPostfixType(283 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -14902,127 +17050,162 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(282);
+ var result = createNode(282 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
}
function parseJSDocUnknownOrNullableType() {
var pos = scanner.getStartPos();
+ // skip the ?
nextToken();
- if (token() === 26 ||
- token() === 18 ||
- token() === 20 ||
- token() === 29 ||
- token() === 58 ||
- token() === 49) {
- var result = createNode(280, pos);
+ // Need to lookahead to decide if this is a nullable or unknown type.
+ // Here are cases where we'll pick the unknown type:
+ //
+ // Foo(?,
+ // { a: ? }
+ // Foo(?)
+ // Foo>
+ // Foo(?=
+ // (?|
+ if (token() === 26 /* CommaToken */ ||
+ token() === 18 /* CloseBraceToken */ ||
+ token() === 20 /* CloseParenToken */ ||
+ token() === 29 /* GreaterThanToken */ ||
+ token() === 58 /* EqualsToken */ ||
+ token() === 49 /* BarToken */) {
+ var result = createNode(280 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(281, pos);
+ var result = createNode(281 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(284);
+ var result = createNodeWithJSDoc(284 /* JSDocFunctionType */);
nextToken();
- fillSignature(56, 4 | 32, result);
+ fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
}
- var node = createNode(162);
+ var node = createNode(162 /* TypeReference */);
node.typeName = parseIdentifierName();
return finishNode(node);
}
function parseJSDocParameter() {
- var parameter = createNode(149);
- if (token() === 99 || token() === 94) {
+ var parameter = createNode(149 /* Parameter */);
+ if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) {
parameter.name = parseIdentifierName();
- parseExpected(56);
+ parseExpected(56 /* ColonToken */);
}
parameter.type = parseJSDocType();
return finishNode(parameter);
}
function parseJSDocType() {
- var dotdotdot = parseOptionalToken(24);
+ var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(285, dotdotdot.pos);
+ var variadic = createNode(285 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
- if (token() === 58) {
- return createJSDocPostfixType(283, type);
+ if (token() === 58 /* EqualsToken */) {
+ return createJSDocPostfixType(283 /* JSDocOptionalType */, type);
}
return type;
}
function parseTypeQuery() {
- var node = createNode(165);
- parseExpected(103);
- node.exprName = parseEntityName(true);
+ var node = createNode(165 /* TypeQuery */);
+ parseExpected(103 /* TypeOfKeyword */);
+ node.exprName = parseEntityName(/*allowReservedWords*/ true);
return finishNode(node);
}
function parseTypeParameter() {
- var node = createNode(148);
+ var node = createNode(148 /* TypeParameter */);
node.name = parseIdentifier();
- if (parseOptional(85)) {
+ if (parseOptional(85 /* ExtendsKeyword */)) {
+ // It's not uncommon for people to write improper constraints to a generic. If the
+ // user writes a constraint that is an expression and not an actual type, then parse
+ // it out as an expression (so we can recover well), but report that a type is needed
+ // instead.
if (isStartOfType() || !isStartOfExpression()) {
node.constraint = parseType();
}
else {
+ // It was not a type, and it looked like an expression. Parse out an expression
+ // here so we recover well. Note: it is important that we call parseUnaryExpression
+ // and not parseExpression here. If the user has:
+ //
+ //
+ //
+ // We do *not* want to consume the `>` as we're consuming the expression for "".
node.expression = parseUnaryExpressionOrHigher();
}
}
- if (parseOptional(58)) {
+ if (parseOptional(58 /* EqualsToken */)) {
node.default = parseType();
}
return finishNode(node);
}
function parseTypeParameters() {
- if (token() === 27) {
- return parseBracketedList(18, parseTypeParameter, 27, 29);
+ if (token() === 27 /* LessThanToken */) {
+ return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */);
}
}
function parseParameterType() {
- if (parseOptional(56)) {
+ if (parseOptional(56 /* ColonToken */)) {
return parseType();
}
return undefined;
}
function isStartOfParameter() {
- return token() === 24 ||
+ return token() === 24 /* DotDotDotToken */ ||
isIdentifierOrPattern() ||
ts.isModifierKind(token()) ||
- token() === 57 ||
- isStartOfType(true);
+ token() === 57 /* AtToken */ ||
+ isStartOfType(/*inStartOfParameter*/ true);
}
function parseParameter() {
- var node = createNodeWithJSDoc(149);
- if (token() === 99) {
- node.name = createIdentifier(true);
+ var node = createNodeWithJSDoc(149 /* Parameter */);
+ if (token() === 99 /* ThisKeyword */) {
+ node.name = createIdentifier(/*isIdentifier*/ true);
node.type = parseParameterType();
return finishNode(node);
}
node.decorators = parseDecorators();
node.modifiers = parseModifiers();
- node.dotDotDotToken = parseOptionalToken(24);
+ node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
+ // FormalParameter [Yield,Await]:
+ // BindingElement[?Yield,?Await]
node.name = parseIdentifierOrPattern();
if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) {
+ // in cases like
+ // 'use strict'
+ // function foo(static)
+ // isParameter('static') === true, because of isModifier('static')
+ // however 'static' is not a legal identifier in a strict mode.
+ // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
+ // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
+ // to avoid this we'll advance cursor to the next token.
nextToken();
}
- node.questionToken = parseOptionalToken(55);
+ node.questionToken = parseOptionalToken(55 /* QuestionToken */);
node.type = parseParameterType();
node.initializer = parseInitializer();
return finishNode(node);
}
+ /**
+ * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
+ * @returns If return type parsing succeeds
+ */
function fillSignature(returnToken, flags, signature) {
- if (!(flags & 32)) {
+ if (!(flags & 32 /* JSDoc */)) {
signature.typeParameters = parseTypeParameters();
}
var parametersParsedSuccessfully = parseParameterList(signature, flags);
- if (shouldParseReturnType(returnToken, !!(flags & 4))) {
+ if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
signature.type = parseTypeOrTypePredicate();
if (typeHasArrowFunctionBlockingParseError(signature.type))
return false;
@@ -15030,55 +17213,89 @@ var ts;
return parametersParsedSuccessfully;
}
function shouldParseReturnType(returnToken, isType) {
- if (returnToken === 36) {
+ if (returnToken === 36 /* EqualsGreaterThanToken */) {
parseExpected(returnToken);
return true;
}
- else if (parseOptional(56)) {
+ else if (parseOptional(56 /* ColonToken */)) {
return true;
}
- else if (isType && token() === 36) {
- parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56));
+ else if (isType && token() === 36 /* EqualsGreaterThanToken */) {
+ // This is easy to get backward, especially in type contexts, so parse the type anyway
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */));
nextToken();
return true;
}
return false;
}
+ // Returns true on success.
function parseParameterList(signature, flags) {
- if (!parseExpected(19)) {
+ // FormalParameters [Yield,Await]: (modified)
+ // [empty]
+ // FormalParameterList[?Yield,Await]
+ //
+ // FormalParameter[Yield,Await]: (modified)
+ // BindingElement[?Yield,Await]
+ //
+ // BindingElement [Yield,Await]: (modified)
+ // SingleNameBinding[?Yield,?Await]
+ // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
+ //
+ // SingleNameBinding [Yield,Await]:
+ // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
+ if (!parseExpected(19 /* OpenParenToken */)) {
signature.parameters = createMissingList();
return false;
}
var savedYieldContext = inYieldContext();
var savedAwaitContext = inAwaitContext();
- setYieldContext(!!(flags & 1));
- setAwaitContext(!!(flags & 2));
- signature.parameters = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter);
+ setYieldContext(!!(flags & 1 /* Yield */));
+ setAwaitContext(!!(flags & 2 /* Await */));
+ signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter);
setYieldContext(savedYieldContext);
setAwaitContext(savedAwaitContext);
- return parseExpected(20);
+ return parseExpected(20 /* CloseParenToken */);
}
function parseTypeMemberSemicolon() {
- if (parseOptional(26)) {
+ // We allow type members to be separated by commas or (possibly ASI) semicolons.
+ // First check if it was a comma. If so, we're done with the member.
+ if (parseOptional(26 /* CommaToken */)) {
return;
}
+ // Didn't have a comma. We must have a (possible ASI) semicolon.
parseSemicolon();
}
function parseSignatureMember(kind) {
var node = createNodeWithJSDoc(kind);
- if (kind === 159) {
- parseExpected(94);
+ if (kind === 159 /* ConstructSignature */) {
+ parseExpected(94 /* NewKeyword */);
}
- fillSignature(56, 4, node);
+ fillSignature(56 /* ColonToken */, 4 /* Type */, node);
parseTypeMemberSemicolon();
return finishNode(node);
}
function isIndexSignature() {
- return token() === 21 && lookAhead(isUnambiguouslyIndexSignature);
+ return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
}
function isUnambiguouslyIndexSignature() {
+ // The only allowed sequence is:
+ //
+ // [id:
+ //
+ // However, for error recovery, we also check the following cases:
+ //
+ // [...
+ // [id,
+ // [id?,
+ // [id?:
+ // [id?]
+ // [public id
+ // [private id
+ // [protected id
+ // []
+ //
nextToken();
- if (token() === 24 || token() === 22) {
+ if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) {
return true;
}
if (ts.isModifierKind(token())) {
@@ -15091,35 +17308,48 @@ var ts;
return false;
}
else {
+ // Skip the identifier
nextToken();
}
- if (token() === 56 || token() === 26) {
+ // A colon signifies a well formed indexer
+ // A comma should be a badly formed indexer because comma expressions are not allowed
+ // in computed properties.
+ if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) {
return true;
}
- if (token() !== 55) {
+ // Question mark could be an indexer with an optional property,
+ // or it could be a conditional expression in a computed property.
+ if (token() !== 55 /* QuestionToken */) {
return false;
}
+ // If any of the following tokens are after the question mark, it cannot
+ // be a conditional expression, so treat it as an indexer.
nextToken();
- return token() === 56 || token() === 26 || token() === 22;
+ return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */;
}
function parseIndexSignatureDeclaration(node) {
- node.kind = 160;
- node.parameters = parseBracketedList(16, parseParameter, 21, 22);
+ node.kind = 160 /* IndexSignature */;
+ node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */);
node.type = parseTypeAnnotation();
parseTypeMemberSemicolon();
return finishNode(node);
}
function parsePropertyOrMethodSignature(node) {
node.name = parsePropertyName();
- node.questionToken = parseOptionalToken(55);
- if (token() === 19 || token() === 27) {
- node.kind = 153;
- fillSignature(56, 4, node);
+ node.questionToken = parseOptionalToken(55 /* QuestionToken */);
+ if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
+ node.kind = 153 /* MethodSignature */;
+ // Method signatures don't exist in expression contexts. So they have neither
+ // [Yield] nor [Await]
+ fillSignature(56 /* ColonToken */, 4 /* Type */, node);
}
else {
- node.kind = 151;
+ node.kind = 151 /* PropertySignature */;
node.type = parseTypeAnnotation();
- if (token() === 58) {
+ if (token() === 58 /* 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.
node.initializer = parseInitializer();
}
}
@@ -15127,39 +17357,45 @@ var ts;
return finishNode(node);
}
function isTypeMemberStart() {
- if (token() === 19 || token() === 27) {
+ // Return true if we have the start of a signature member
+ if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
return true;
}
var idToken = false;
+ // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
while (ts.isModifierKind(token())) {
idToken = true;
nextToken();
}
- if (token() === 21) {
+ // Index signatures and computed property names are type members
+ if (token() === 21 /* OpenBracketToken */) {
return true;
}
+ // Try to get the first property-like token following all modifiers
if (isLiteralPropertyName()) {
idToken = true;
nextToken();
}
+ // If we were able to get any potential identifier, check that it is
+ // the start of a member declaration
if (idToken) {
- return token() === 19 ||
- token() === 27 ||
- token() === 55 ||
- token() === 56 ||
- token() === 26 ||
+ return token() === 19 /* OpenParenToken */ ||
+ token() === 27 /* LessThanToken */ ||
+ token() === 55 /* QuestionToken */ ||
+ token() === 56 /* ColonToken */ ||
+ token() === 26 /* CommaToken */ ||
canParseSemicolon();
}
return false;
}
function parseTypeMember() {
- if (token() === 19 || token() === 27) {
- return parseSignatureMember(158);
+ if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
+ return parseSignatureMember(158 /* CallSignature */);
}
- if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) {
- return parseSignatureMember(159);
+ if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
+ return parseSignatureMember(159 /* ConstructSignature */);
}
- var node = createNodeWithJSDoc(0);
+ var node = createNodeWithJSDoc(0 /* Unknown */);
node.modifiers = parseModifiers();
if (isIndexSignature()) {
return parseIndexSignatureDeclaration(node);
@@ -15168,30 +17404,30 @@ var ts;
}
function nextTokenIsOpenParenOrLessThan() {
nextToken();
- return token() === 19 || token() === 27;
+ return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */;
}
function nextTokenIsDot() {
- return nextToken() === 23;
+ return nextToken() === 23 /* DotToken */;
}
function nextTokenIsOpenParenOrLessThanOrDot() {
switch (nextToken()) {
- case 19:
- case 27:
- case 23:
+ case 19 /* OpenParenToken */:
+ case 27 /* LessThanToken */:
+ case 23 /* DotToken */:
return true;
}
return false;
}
function parseTypeLiteral() {
- var node = createNode(166);
+ var node = createNode(166 /* TypeLiteral */);
node.members = parseObjectTypeMembers();
return finishNode(node);
}
function parseObjectTypeMembers() {
var members;
- if (parseExpected(17)) {
- members = parseList(4, parseTypeMember);
- parseExpected(18);
+ if (parseExpected(17 /* OpenBraceToken */)) {
+ members = parseList(4 /* TypeMembers */, parseTypeMember);
+ parseExpected(18 /* CloseBraceToken */);
}
else {
members = createMissingList();
@@ -15200,76 +17436,76 @@ var ts;
}
function isStartOfMappedType() {
nextToken();
- if (token() === 37 || token() === 38) {
- return nextToken() === 132;
+ if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) {
+ return nextToken() === 132 /* ReadonlyKeyword */;
}
- if (token() === 132) {
+ if (token() === 132 /* ReadonlyKeyword */) {
nextToken();
}
- return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92;
+ return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */;
}
function parseMappedTypeParameter() {
- var node = createNode(148);
+ var node = createNode(148 /* TypeParameter */);
node.name = parseIdentifier();
- parseExpected(92);
+ parseExpected(92 /* InKeyword */);
node.constraint = parseType();
return finishNode(node);
}
function parseMappedType() {
- var node = createNode(177);
- parseExpected(17);
- if (token() === 132 || token() === 37 || token() === 38) {
+ var node = createNode(177 /* MappedType */);
+ parseExpected(17 /* OpenBraceToken */);
+ if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) {
node.readonlyToken = parseTokenNode();
- if (node.readonlyToken.kind !== 132) {
- parseExpectedToken(132);
+ if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) {
+ parseExpectedToken(132 /* ReadonlyKeyword */);
}
}
- parseExpected(21);
+ parseExpected(21 /* OpenBracketToken */);
node.typeParameter = parseMappedTypeParameter();
- parseExpected(22);
- if (token() === 55 || token() === 37 || token() === 38) {
+ parseExpected(22 /* CloseBracketToken */);
+ if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) {
node.questionToken = parseTokenNode();
- if (node.questionToken.kind !== 55) {
- parseExpectedToken(55);
+ if (node.questionToken.kind !== 55 /* QuestionToken */) {
+ parseExpectedToken(55 /* QuestionToken */);
}
}
node.type = parseTypeAnnotation();
parseSemicolon();
- parseExpected(18);
+ parseExpected(18 /* CloseBraceToken */);
return finishNode(node);
}
function parseTupleType() {
- var node = createNode(168);
- node.elementTypes = parseBracketedList(20, parseType, 21, 22);
+ var node = createNode(168 /* TupleType */);
+ node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */);
return finishNode(node);
}
function parseParenthesizedType() {
- var node = createNode(173);
- parseExpected(19);
+ var node = createNode(173 /* ParenthesizedType */);
+ parseExpected(19 /* OpenParenToken */);
node.type = parseType();
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
return finishNode(node);
}
function parseFunctionOrConstructorType() {
var pos = getNodePos();
- var kind = parseOptional(94) ? 164 : 163;
+ var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */;
var node = createNodeWithJSDoc(kind, pos);
- fillSignature(36, 4, node);
+ fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node);
return finishNode(node);
}
function parseKeywordAndNoDot() {
var node = parseTokenNode();
- return token() === 23 ? undefined : node;
+ return token() === 23 /* DotToken */ ? undefined : node;
}
function parseLiteralTypeNode(negative) {
- var node = createNode(178);
+ var node = createNode(178 /* LiteralType */);
var unaryMinusExpression;
if (negative) {
- unaryMinusExpression = createNode(198);
- unaryMinusExpression.operator = 38;
+ unaryMinusExpression = createNode(198 /* PrefixUnaryExpression */);
+ unaryMinusExpression.operator = 38 /* MinusToken */;
nextToken();
}
- var expression = token() === 101 || token() === 86
+ var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */
? parseTokenNode()
: parseLiteralLikeNode(token());
if (negative) {
@@ -15282,78 +17518,79 @@ var ts;
}
function isStartOfTypeOfImportType() {
nextToken();
- return token() === 91;
+ return token() === 91 /* ImportKeyword */;
}
function parseImportType() {
- sourceFile.flags |= 524288;
- var node = createNode(179);
- if (parseOptional(103)) {
+ sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */;
+ var node = createNode(179 /* ImportType */);
+ if (parseOptional(103 /* TypeOfKeyword */)) {
node.isTypeOf = true;
}
- parseExpected(91);
- parseExpected(19);
+ parseExpected(91 /* ImportKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.argument = parseType();
- parseExpected(20);
- if (parseOptional(23)) {
- node.qualifier = parseEntityName(true, ts.Diagnostics.Type_expected);
+ parseExpected(20 /* CloseParenToken */);
+ if (parseOptional(23 /* DotToken */)) {
+ node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
}
node.typeArguments = tryParseTypeArguments();
return finishNode(node);
}
function nextTokenIsNumericLiteral() {
- return nextToken() === 8;
+ return nextToken() === 8 /* NumericLiteral */;
}
function parseNonArrayType() {
switch (token()) {
- case 119:
- case 142:
- case 137:
- case 134:
- case 138:
- case 122:
- case 140:
- case 131:
- case 135:
+ case 119 /* AnyKeyword */:
+ case 142 /* UnknownKeyword */:
+ case 137 /* StringKeyword */:
+ case 134 /* NumberKeyword */:
+ case 138 /* SymbolKeyword */:
+ case 122 /* BooleanKeyword */:
+ case 140 /* UndefinedKeyword */:
+ case 131 /* NeverKeyword */:
+ case 135 /* ObjectKeyword */:
+ // If these are followed by a dot, then parse these out as a dotted type reference instead.
return tryParse(parseKeywordAndNoDot) || parseTypeReference();
- case 39:
- return parseJSDocAllType(false);
- case 61:
- return parseJSDocAllType(true);
- case 55:
+ case 39 /* AsteriskToken */:
+ return parseJSDocAllType(/*postfixEquals*/ false);
+ case 61 /* AsteriskEqualsToken */:
+ return parseJSDocAllType(/*postfixEquals*/ true);
+ case 55 /* QuestionToken */:
return parseJSDocUnknownOrNullableType();
- case 89:
+ case 89 /* FunctionKeyword */:
return parseJSDocFunctionType();
- case 51:
+ case 51 /* ExclamationToken */:
return parseJSDocNonNullableType();
- case 13:
- case 9:
- case 8:
- case 101:
- case 86:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
return parseLiteralTypeNode();
- case 38:
- return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference();
- case 105:
- case 95:
+ case 38 /* MinusToken */:
+ return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
+ case 105 /* VoidKeyword */:
+ case 95 /* NullKeyword */:
return parseTokenNode();
- case 99: {
+ case 99 /* ThisKeyword */: {
var thisKeyword = parseThisTypeNode();
- if (token() === 127 && !scanner.hasPrecedingLineBreak()) {
+ if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
return parseThisTypePredicate(thisKeyword);
}
else {
return thisKeyword;
}
}
- case 103:
+ case 103 /* TypeOfKeyword */:
return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
- case 17:
+ case 17 /* OpenBraceToken */:
return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
- case 21:
+ case 21 /* OpenBracketToken */:
return parseTupleType();
- case 19:
+ case 19 /* OpenParenToken */:
return parseParenthesizedType();
- case 91:
+ case 91 /* ImportKeyword */:
return parseImportType();
default:
return parseTypeReference();
@@ -15361,40 +17598,42 @@ var ts;
}
function isStartOfType(inStartOfParameter) {
switch (token()) {
- case 119:
- case 142:
- case 137:
- case 134:
- case 122:
- case 138:
- case 141:
- case 105:
- case 140:
- case 95:
- case 99:
- case 103:
- case 131:
- case 17:
- case 21:
- case 27:
- case 49:
- case 48:
- case 94:
- case 9:
- case 8:
- case 101:
- case 86:
- case 135:
- case 39:
- case 55:
- case 51:
- case 24:
- case 126:
- case 91:
+ case 119 /* AnyKeyword */:
+ case 142 /* UnknownKeyword */:
+ case 137 /* StringKeyword */:
+ case 134 /* NumberKeyword */:
+ case 122 /* BooleanKeyword */:
+ case 138 /* SymbolKeyword */:
+ case 141 /* UniqueKeyword */:
+ case 105 /* VoidKeyword */:
+ case 140 /* UndefinedKeyword */:
+ case 95 /* NullKeyword */:
+ case 99 /* ThisKeyword */:
+ case 103 /* TypeOfKeyword */:
+ case 131 /* NeverKeyword */:
+ case 17 /* OpenBraceToken */:
+ case 21 /* OpenBracketToken */:
+ case 27 /* LessThanToken */:
+ case 49 /* BarToken */:
+ case 48 /* AmpersandToken */:
+ case 94 /* NewKeyword */:
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 135 /* ObjectKeyword */:
+ case 39 /* AsteriskToken */:
+ case 55 /* QuestionToken */:
+ case 51 /* ExclamationToken */:
+ case 24 /* DotDotDotToken */:
+ case 126 /* InferKeyword */:
+ case 91 /* ImportKeyword */:
return true;
- case 38:
+ case 38 /* MinusToken */:
return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral);
- case 19:
+ case 19 /* OpenParenToken */:
+ // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
+ // or something that starts a type. We don't want to consider things like '(1)' a type.
return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
default:
return isIdentifier();
@@ -15402,34 +17641,35 @@ var ts;
}
function isStartOfParenthesizedOrFunctionType() {
nextToken();
- return token() === 20 || isStartOfParameter() || isStartOfType();
+ return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType();
}
function parsePostfixTypeOrHigher() {
var type = parseNonArrayType();
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
- case 51:
- type = createJSDocPostfixType(282, type);
+ case 51 /* ExclamationToken */:
+ type = createJSDocPostfixType(282 /* JSDocNonNullableType */, type);
break;
- case 55:
- if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) {
+ case 55 /* QuestionToken */:
+ // If not in JSDoc and next token is start of a type we have a conditional type
+ if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createJSDocPostfixType(281, type);
+ type = createJSDocPostfixType(281 /* JSDocNullableType */, type);
break;
- case 21:
- parseExpected(21);
+ case 21 /* OpenBracketToken */:
+ parseExpected(21 /* OpenBracketToken */);
if (isStartOfType()) {
- var node = createNode(176, type.pos);
+ var node = createNode(176 /* IndexedAccessType */, type.pos);
node.objectType = type;
node.indexType = parseType();
- parseExpected(22);
+ parseExpected(22 /* CloseBracketToken */);
type = finishNode(node);
}
else {
- var node = createNode(167, type.pos);
+ var node = createNode(167 /* ArrayType */, type.pos);
node.elementType = type;
- parseExpected(22);
+ parseExpected(22 /* CloseBracketToken */);
type = finishNode(node);
}
break;
@@ -15446,16 +17686,16 @@ var ts;
return finishNode(postfix);
}
function parseTypeOperator(operator) {
- var node = createNode(175);
+ var node = createNode(175 /* TypeOperator */);
parseExpected(operator);
node.operator = operator;
node.type = parseTypeOperatorOrHigher();
return finishNode(node);
}
function parseInferType() {
- var node = createNode(172);
- parseExpected(126);
- var typeParameter = createNode(148);
+ var node = createNode(172 /* InferType */);
+ parseExpected(126 /* InferKeyword */);
+ var typeParameter = createNode(148 /* TypeParameter */);
typeParameter.name = parseIdentifier();
node.typeParameter = finishNode(typeParameter);
return finishNode(node);
@@ -15463,10 +17703,10 @@ var ts;
function parseTypeOperatorOrHigher() {
var operator = token();
switch (operator) {
- case 128:
- case 141:
+ case 128 /* KeyOfKeyword */:
+ case 141 /* UniqueKeyword */:
return parseTypeOperator(operator);
- case 126:
+ case 126 /* InferKeyword */:
return parseInferType();
}
return parsePostfixTypeOrHigher();
@@ -15486,26 +17726,28 @@ var ts;
return type;
}
function parseIntersectionTypeOrHigher() {
- return parseUnionOrIntersectionType(170, parseTypeOperatorOrHigher, 48);
+ return parseUnionOrIntersectionType(170 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */);
}
function parseUnionTypeOrHigher() {
- return parseUnionOrIntersectionType(169, parseIntersectionTypeOrHigher, 49);
+ return parseUnionOrIntersectionType(169 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */);
}
function isStartOfFunctionType() {
- if (token() === 27) {
+ if (token() === 27 /* LessThanToken */) {
return true;
}
- return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType);
+ return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
}
function skipParameterStart() {
if (ts.isModifierKind(token())) {
+ // Skip modifiers
parseModifiers();
}
- if (isIdentifier() || token() === 99) {
+ if (isIdentifier() || token() === 99 /* ThisKeyword */) {
nextToken();
return true;
}
- if (token() === 21 || token() === 17) {
+ if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) {
+ // Return true if we can parse an array or object binding pattern with no errors
var previousErrorCount = parseDiagnostics.length;
parseIdentifierOrPattern();
return previousErrorCount === parseDiagnostics.length;
@@ -15514,17 +17756,26 @@ var ts;
}
function isUnambiguouslyStartOfFunctionType() {
nextToken();
- if (token() === 20 || token() === 24) {
+ if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) {
+ // ( )
+ // ( ...
return true;
}
if (skipParameterStart()) {
- if (token() === 56 || token() === 26 ||
- token() === 55 || token() === 58) {
+ // We successfully skipped modifiers (if any) and an identifier or binding pattern,
+ // now see if we have something that indicates a parameter declaration
+ if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ ||
+ token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) {
+ // ( xxx :
+ // ( xxx ,
+ // ( xxx ?
+ // ( xxx =
return true;
}
- if (token() === 20) {
+ if (token() === 20 /* CloseParenToken */) {
nextToken();
- if (token() === 36) {
+ if (token() === 36 /* EqualsGreaterThanToken */) {
+ // ( xxx ) =>
return true;
}
}
@@ -15535,7 +17786,7 @@ var ts;
var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
var type = parseType();
if (typePredicateVariable) {
- var node = createNode(161, typePredicateVariable.pos);
+ var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos);
node.parameterName = typePredicateVariable;
node.type = type;
return finishNode(node);
@@ -15546,56 +17797,60 @@ var ts;
}
function parseTypePredicatePrefix() {
var id = parseIdentifier();
- if (token() === 127 && !scanner.hasPrecedingLineBreak()) {
+ if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
nextToken();
return id;
}
}
function parseType() {
- return doOutsideOfContext(20480, parseTypeWorker);
+ // The rules about 'yield' only apply to actual code/expression contexts. They don't
+ // apply to 'type' contexts. So we disable these parameters here before moving on.
+ return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker);
}
function parseTypeWorker(noConditionalTypes) {
- if (isStartOfFunctionType() || token() === 94) {
+ if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) {
return parseFunctionOrConstructorType();
}
var type = parseUnionTypeOrHigher();
- if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85)) {
- var node = createNode(171, type.pos);
+ if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) {
+ var node = createNode(171 /* ConditionalType */, type.pos);
node.checkType = type;
- node.extendsType = parseTypeWorker(true);
- parseExpected(55);
+ // The type following 'extends' is not permitted to be another conditional type
+ node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
+ parseExpected(55 /* QuestionToken */);
node.trueType = parseTypeWorker();
- parseExpected(56);
+ parseExpected(56 /* ColonToken */);
node.falseType = parseTypeWorker();
return finishNode(node);
}
return type;
}
function parseTypeAnnotation() {
- return parseOptional(56) ? parseType() : undefined;
+ return parseOptional(56 /* ColonToken */) ? parseType() : undefined;
}
+ // EXPRESSIONS
function isStartOfLeftHandSideExpression() {
switch (token()) {
- case 99:
- case 97:
- case 95:
- case 101:
- case 86:
- case 8:
- case 9:
- case 13:
- case 14:
- case 19:
- case 21:
- case 17:
- case 89:
- case 75:
- case 94:
- case 41:
- case 63:
- case 71:
+ case 99 /* ThisKeyword */:
+ case 97 /* SuperKeyword */:
+ case 95 /* NullKeyword */:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ case 14 /* TemplateHead */:
+ case 19 /* OpenParenToken */:
+ case 21 /* OpenBracketToken */:
+ case 17 /* OpenBraceToken */:
+ case 89 /* FunctionKeyword */:
+ case 75 /* ClassKeyword */:
+ case 94 /* NewKeyword */:
+ case 41 /* SlashToken */:
+ case 63 /* SlashEqualsToken */:
+ case 71 /* Identifier */:
return true;
- case 91:
+ case 91 /* ImportKeyword */:
return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
default:
return isIdentifier();
@@ -15606,20 +17861,27 @@ var ts;
return true;
}
switch (token()) {
- case 37:
- case 38:
- case 52:
- case 51:
- case 80:
- case 103:
- case 105:
- case 43:
- case 44:
- case 27:
- case 121:
- case 116:
+ case 37 /* PlusToken */:
+ case 38 /* MinusToken */:
+ case 52 /* TildeToken */:
+ case 51 /* ExclamationToken */:
+ case 80 /* DeleteKeyword */:
+ case 103 /* TypeOfKeyword */:
+ case 105 /* VoidKeyword */:
+ case 43 /* PlusPlusToken */:
+ case 44 /* MinusMinusToken */:
+ case 27 /* LessThanToken */:
+ case 121 /* AwaitKeyword */:
+ case 116 /* YieldKeyword */:
+ // Yield/await always starts an expression. Either it is an identifier (in which case
+ // it is definitely an expression). Or it's a keyword (either because we're in
+ // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
return true;
default:
+ // Error tolerance. If we see the start of some binary operator, we consider
+ // that the start of an expression. That way we'll parse out a missing identifier,
+ // give a good message about an identifier being missing, and then consume the
+ // rest of the binary expression.
if (isBinaryOperator()) {
return true;
}
@@ -15627,52 +17889,114 @@ var ts;
}
}
function isStartOfExpressionStatement() {
- return token() !== 17 &&
- token() !== 89 &&
- token() !== 75 &&
- token() !== 57 &&
+ // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
+ return token() !== 17 /* OpenBraceToken */ &&
+ token() !== 89 /* FunctionKeyword */ &&
+ token() !== 75 /* ClassKeyword */ &&
+ token() !== 57 /* AtToken */ &&
isStartOfExpression();
}
function parseExpression() {
+ // Expression[in]:
+ // AssignmentExpression[in]
+ // Expression[in] , AssignmentExpression[in]
+ // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
var saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
- setDecoratorContext(false);
+ setDecoratorContext(/*val*/ false);
}
var expr = parseAssignmentExpressionOrHigher();
var operatorToken;
- while ((operatorToken = parseOptionalToken(26))) {
+ while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) {
expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
}
if (saveDecoratorContext) {
- setDecoratorContext(true);
+ setDecoratorContext(/*val*/ true);
}
return expr;
}
function parseInitializer() {
- return parseOptional(58) ? parseAssignmentExpressionOrHigher() : undefined;
+ return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
}
function parseAssignmentExpressionOrHigher() {
+ // AssignmentExpression[in,yield]:
+ // 1) ConditionalExpression[?in,?yield]
+ // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
+ // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
+ // 4) ArrowFunctionExpression[?in,?yield]
+ // 5) AsyncArrowFunctionExpression[in,yield,await]
+ // 6) [+Yield] YieldExpression[?In]
+ //
+ // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
+ // (i.e. they're both BinaryExpressions with an assignment operator in it).
+ // First, do the simple check if we have a YieldExpression (production '6').
if (isYieldExpression()) {
return parseYieldExpression();
}
+ // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
+ // parameter list or is an async arrow function.
+ // AsyncArrowFunctionExpression:
+ // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
+ // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
+ // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
+ // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
+ //
+ // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
+ // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done
+ // with AssignmentExpression if we see one.
var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
if (arrowExpression) {
return arrowExpression;
}
- var expr = parseBinaryExpressionOrHigher(0);
- if (expr.kind === 71 && token() === 36) {
+ // Now try to see if we're in production '1', '2' or '3'. A conditional expression can
+ // start with a LogicalOrExpression, while the assignment productions can only start with
+ // LeftHandSideExpressions.
+ //
+ // So, first, we try to just parse out a BinaryExpression. If we get something that is a
+ // LeftHandSide or higher, then we can try to parse out the assignment expression part.
+ // Otherwise, we try to parse out the conditional expression bit. We want to allow any
+ // binary expression here, so we pass in the 'lowest' precedence here so that it matches
+ // and consumes anything.
+ var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
+ // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
+ // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
+ // identifier and the current token is an arrow.
+ if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) {
return parseSimpleArrowFunctionExpression(expr);
}
+ // Now see if we might be in cases '2' or '3'.
+ // If the expression was a LHS expression, and we have an assignment operator, then
+ // we're in '2' or '3'. Consume the assignment and return.
+ //
+ // Note: we call reScanGreaterToken so that we get an appropriately merged token
+ // for cases like `> > =` becoming `>>=`
if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
}
+ // It wasn't an assignment or a lambda. This is a conditional expression:
return parseConditionalExpressionRest(expr);
}
function isYieldExpression() {
- if (token() === 116) {
+ if (token() === 116 /* YieldKeyword */) {
+ // If we have a 'yield' keyword, and this is a context where yield expressions are
+ // allowed, then definitely parse out a yield expression.
if (inYieldContext()) {
return true;
}
+ // We're in a context where 'yield expr' is not allowed. However, if we can
+ // definitely tell that the user was trying to parse a 'yield expr' and not
+ // just a normal expr that start with a 'yield' identifier, then parse out
+ // a 'yield expr'. We can then report an error later that they are only
+ // allowed in generator expressions.
+ //
+ // for example, if we see 'yield(foo)', then we'll have to treat that as an
+ // invocation expression of something called 'yield'. However, if we have
+ // 'yield foo' then that is not legal as a normal expression, so we can
+ // definitely recognize this as a yield expression.
+ //
+ // for now we just check if the next token is an identifier. More heuristics
+ // can be added here later as necessary. We just need to make sure that we
+ // don't accidentally consume something legal.
return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
}
return false;
@@ -15682,213 +18006,302 @@ var ts;
return !scanner.hasPrecedingLineBreak() && isIdentifier();
}
function parseYieldExpression() {
- var node = createNode(203);
+ var node = createNode(203 /* YieldExpression */);
+ // YieldExpression[In] :
+ // yield
+ // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
+ // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
nextToken();
if (!scanner.hasPrecedingLineBreak() &&
- (token() === 39 || isStartOfExpression())) {
- node.asteriskToken = parseOptionalToken(39);
+ (token() === 39 /* AsteriskToken */ || isStartOfExpression())) {
+ node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
node.expression = parseAssignmentExpressionOrHigher();
return finishNode(node);
}
else {
+ // if the next token is not on the same line as yield. or we don't have an '*' or
+ // the start of an expression, then this is just a simple "yield" expression.
return finishNode(node);
}
}
function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
- ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
+ ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
var node;
if (asyncModifier) {
- node = createNode(193, asyncModifier.pos);
+ node = createNode(193 /* ArrowFunction */, asyncModifier.pos);
node.modifiers = asyncModifier;
}
else {
- node = createNode(193, identifier.pos);
+ node = createNode(193 /* ArrowFunction */, identifier.pos);
}
- var parameter = createNode(149, identifier.pos);
+ var parameter = createNode(149 /* Parameter */, identifier.pos);
parameter.name = identifier;
finishNode(parameter);
node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
- node.equalsGreaterThanToken = parseExpectedToken(36);
- node.body = parseArrowFunctionExpressionBody(!!asyncModifier);
+ node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */);
+ node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
return addJSDocComment(finishNode(node));
}
function tryParseParenthesizedArrowFunctionExpression() {
var triState = isParenthesizedArrowFunctionExpression();
- if (triState === 0) {
+ if (triState === 0 /* False */) {
+ // It's definitely not a parenthesized arrow function expression.
return undefined;
}
- var arrowFunction = triState === 1
- ? parseParenthesizedArrowFunctionExpressionHead(true)
+ // If we definitely have an arrow function, then we can just parse one, not requiring a
+ // following => or { token. Otherwise, we *might* have an arrow function. Try to parse
+ // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
+ // expression instead.
+ var arrowFunction = triState === 1 /* True */
+ ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
: tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
if (!arrowFunction) {
+ // Didn't appear to actually be a parenthesized arrow function. Just bail out.
return undefined;
}
- var isAsync = ts.hasModifier(arrowFunction, 256);
+ var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */);
+ // If we have an arrow, then try to parse the body. Even if not, try to parse if we
+ // have an opening brace, just in case we're in an error state.
var lastToken = token();
- arrowFunction.equalsGreaterThanToken = parseExpectedToken(36);
- arrowFunction.body = (lastToken === 36 || lastToken === 17)
+ arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */);
+ arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */)
? parseArrowFunctionExpressionBody(isAsync)
: parseIdentifier();
return finishNode(arrowFunction);
}
+ // True -> We definitely expect a parenthesized arrow function here.
+ // False -> There *cannot* be a parenthesized arrow function here.
+ // Unknown -> There *might* be a parenthesized arrow function here.
+ // Speculatively look ahead to be sure, and rollback if not.
function isParenthesizedArrowFunctionExpression() {
- if (token() === 19 || token() === 27 || token() === 120) {
+ if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) {
return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
}
- if (token() === 36) {
- return 1;
+ if (token() === 36 /* EqualsGreaterThanToken */) {
+ // ERROR RECOVERY TWEAK:
+ // If we see a standalone => try to parse it as an arrow function expression as that's
+ // likely what the user intended to write.
+ return 1 /* True */;
}
- return 0;
+ // Definitely not a parenthesized arrow function.
+ return 0 /* False */;
}
function isParenthesizedArrowFunctionExpressionWorker() {
- if (token() === 120) {
+ if (token() === 120 /* AsyncKeyword */) {
nextToken();
if (scanner.hasPrecedingLineBreak()) {
- return 0;
+ return 0 /* False */;
}
- if (token() !== 19 && token() !== 27) {
- return 0;
+ if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) {
+ return 0 /* False */;
}
}
var first = token();
var second = nextToken();
- if (first === 19) {
- if (second === 20) {
+ if (first === 19 /* OpenParenToken */) {
+ if (second === 20 /* CloseParenToken */) {
+ // Simple cases: "() =>", "(): ", and "() {".
+ // This is an arrow function with no parameters.
+ // The last one is not actually an arrow function,
+ // but this is probably what the user intended.
var third = nextToken();
switch (third) {
- case 36:
- case 56:
- case 17:
- return 1;
+ case 36 /* EqualsGreaterThanToken */:
+ case 56 /* ColonToken */:
+ case 17 /* OpenBraceToken */:
+ return 1 /* True */;
default:
- return 0;
+ return 0 /* False */;
}
}
- if (second === 21 || second === 17) {
- return 2;
+ // If encounter "([" or "({", this could be the start of a binding pattern.
+ // Examples:
+ // ([ x ]) => { }
+ // ({ x }) => { }
+ // ([ x ])
+ // ({ x })
+ if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) {
+ return 2 /* Unknown */;
}
- if (second === 24) {
- return 1;
+ // Simple case: "(..."
+ // This is an arrow function with a rest parameter.
+ if (second === 24 /* DotDotDotToken */) {
+ return 1 /* True */;
}
- if (ts.isModifierKind(second) && second !== 120 && lookAhead(nextTokenIsIdentifier)) {
- return 1;
+ // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
+ // isn't actually allowed, but we want to treat it as a lambda so we can provide
+ // a good error message.
+ if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
+ return 1 /* True */;
}
+ // If we had "(" followed by something that's not an identifier,
+ // then this definitely doesn't look like a lambda.
if (!isIdentifier()) {
- return 0;
+ return 0 /* False */;
}
switch (nextToken()) {
- case 56:
- return 1;
- case 55:
+ case 56 /* ColonToken */:
+ // If we have something like "(a:", then we must have a
+ // type-annotated parameter in an arrow function expression.
+ return 1 /* True */;
+ case 55 /* QuestionToken */:
nextToken();
- if (token() === 56 || token() === 26 || token() === 58 || token() === 20) {
- return 1;
+ // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
+ if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) {
+ return 1 /* True */;
}
- return 0;
- case 26:
- case 58:
- case 20:
- return 2;
+ // Otherwise it is definitely not a lambda.
+ return 0 /* False */;
+ case 26 /* CommaToken */:
+ case 58 /* EqualsToken */:
+ case 20 /* CloseParenToken */:
+ // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
+ return 2 /* Unknown */;
}
- return 0;
+ // It is definitely not an arrow function
+ return 0 /* False */;
}
else {
- ts.Debug.assert(first === 27);
+ ts.Debug.assert(first === 27 /* LessThanToken */);
+ // If we have "<" not followed by an identifier,
+ // then this definitely is not an arrow function.
if (!isIdentifier()) {
- return 0;
+ return 0 /* False */;
}
- if (sourceFile.languageVariant === 1) {
+ // JSX overrides
+ if (sourceFile.languageVariant === 1 /* JSX */) {
var isArrowFunctionInJsx = lookAhead(function () {
var third = nextToken();
- if (third === 85) {
+ if (third === 85 /* ExtendsKeyword */) {
var fourth = nextToken();
switch (fourth) {
- case 58:
- case 29:
+ case 58 /* EqualsToken */:
+ case 29 /* GreaterThanToken */:
return false;
default:
return true;
}
}
- else if (third === 26) {
+ else if (third === 26 /* CommaToken */) {
return true;
}
return false;
});
if (isArrowFunctionInJsx) {
- return 1;
+ return 1 /* True */;
}
- return 0;
+ return 0 /* False */;
}
- return 2;
+ // This *could* be a parenthesized arrow function.
+ return 2 /* Unknown */;
}
}
function parsePossibleParenthesizedArrowFunctionExpressionHead() {
- return parseParenthesizedArrowFunctionExpressionHead(false);
+ return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
}
function tryParseAsyncSimpleArrowFunctionExpression() {
- if (token() === 120) {
- if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) {
+ // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
+ if (token() === 120 /* AsyncKeyword */) {
+ if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
var asyncModifier = parseModifiersForArrowFunction();
- var expr = parseBinaryExpressionOrHigher(0);
+ var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
return parseSimpleArrowFunctionExpression(expr, asyncModifier);
}
}
return undefined;
}
function isUnParenthesizedAsyncArrowFunctionWorker() {
- if (token() === 120) {
+ // AsyncArrowFunctionExpression:
+ // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
+ // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
+ if (token() === 120 /* AsyncKeyword */) {
nextToken();
- if (scanner.hasPrecedingLineBreak() || token() === 36) {
- return 0;
+ // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
+ // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
+ if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) {
+ return 0 /* False */;
}
- var expr = parseBinaryExpressionOrHigher(0);
- if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) {
- return 1;
+ // Check for un-parenthesized AsyncArrowFunction
+ var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
+ if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) {
+ return 1 /* True */;
}
}
- return 0;
+ return 0 /* False */;
}
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
- var node = createNodeWithJSDoc(193);
+ var node = createNodeWithJSDoc(193 /* ArrowFunction */);
node.modifiers = parseModifiersForArrowFunction();
- var isAsync = ts.hasModifier(node, 256) ? 2 : 0;
- if (!fillSignature(56, isAsync, node) && !allowAmbiguity) {
+ var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
+ // Arrow functions are never generators.
+ //
+ // If we're speculatively parsing a signature for a parenthesized arrow function, then
+ // we have to have a complete parameter list. Otherwise we might see something like
+ // a => (b => c)
+ // And think that "(b =>" was actually a parenthesized arrow function with a missing
+ // close paren.
+ if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
return undefined;
}
- if (!allowAmbiguity && token() !== 36 && token() !== 17) {
+ // Parsing a signature isn't enough.
+ // Parenthesized arrow signatures often look like other valid expressions.
+ // For instance:
+ // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
+ // - "(x,y)" is a comma expression parsed as a signature with two parameters.
+ // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
+ //
+ // So we need just a bit of lookahead to ensure that it can only be a signature.
+ if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) {
+ // Returning undefined here will cause our caller to rewind to where we started from.
return undefined;
}
return node;
}
function parseArrowFunctionExpressionBody(isAsync) {
- if (token() === 17) {
- return parseFunctionBlock(isAsync ? 2 : 0);
+ if (token() === 17 /* OpenBraceToken */) {
+ return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
}
- if (token() !== 25 &&
- token() !== 89 &&
- token() !== 75 &&
+ if (token() !== 25 /* SemicolonToken */ &&
+ token() !== 89 /* FunctionKeyword */ &&
+ token() !== 75 /* ClassKeyword */ &&
isStartOfStatement() &&
!isStartOfExpressionStatement()) {
- return parseFunctionBlock(16 | (isAsync ? 2 : 0));
+ // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
+ //
+ // Here we try to recover from a potential error situation in the case where the
+ // user meant to supply a block. For example, if the user wrote:
+ //
+ // a =>
+ // let v = 0;
+ // }
+ //
+ // they may be missing an open brace. Check to see if that's the case so we can
+ // try to recover better. If we don't do this, then the next close curly we see may end
+ // up preemptively closing the containing construct.
+ //
+ // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
+ return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
}
return isAsync
? doInAwaitContext(parseAssignmentExpressionOrHigher)
: doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
}
function parseConditionalExpressionRest(leftOperand) {
- var questionToken = parseOptionalToken(55);
+ // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
+ var questionToken = parseOptionalToken(55 /* QuestionToken */);
if (!questionToken) {
return leftOperand;
}
- var node = createNode(201, leftOperand.pos);
+ // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
+ // we do not that for the 'whenFalse' part.
+ var node = createNode(201 /* ConditionalExpression */, leftOperand.pos);
node.condition = leftOperand;
node.questionToken = questionToken;
node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
- node.colonToken = parseExpectedToken(56);
+ node.colonToken = parseExpectedToken(56 /* ColonToken */);
node.whenFalse = ts.nodeIsPresent(node.colonToken)
? parseAssignmentExpressionOrHigher()
- : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56));
+ : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */));
return finishNode(node);
}
function parseBinaryExpressionOrHigher(precedence) {
@@ -15896,22 +18309,50 @@ var ts;
return parseBinaryExpressionRest(precedence, leftOperand);
}
function isInOrOfKeyword(t) {
- return t === 92 || t === 145;
+ return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */;
}
function parseBinaryExpressionRest(precedence, leftOperand) {
while (true) {
+ // We either have a binary operator here, or we're finished. We call
+ // reScanGreaterToken so that we merge token sequences like > and = into >=
reScanGreaterToken();
var newPrecedence = ts.getBinaryOperatorPrecedence(token());
- var consumeCurrentOperator = token() === 40 ?
+ // Check the precedence to see if we should "take" this operator
+ // - For left associative operator (all operator but **), consume the operator,
+ // recursively call the function below, and parse binaryExpression as a rightOperand
+ // of the caller if the new precedence of the operator is greater then or equal to the current precedence.
+ // For example:
+ // a - b - c;
+ // ^token; leftOperand = b. Return b to the caller as a rightOperand
+ // a * b - c
+ // ^token; leftOperand = b. Return b to the caller as a rightOperand
+ // a - b * c;
+ // ^token; leftOperand = b. Return b * c to the caller as a rightOperand
+ // - For right associative operator (**), consume the operator, recursively call the function
+ // and parse binaryExpression as a rightOperand of the caller if the new precedence of
+ // the operator is strictly grater than the current precedence
+ // For example:
+ // a ** b ** c;
+ // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
+ // a - b ** c;
+ // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
+ // a ** b - c
+ // ^token; leftOperand = b. Return b to the caller as a rightOperand
+ var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ?
newPrecedence >= precedence :
newPrecedence > precedence;
if (!consumeCurrentOperator) {
break;
}
- if (token() === 92 && inDisallowInContext()) {
+ if (token() === 92 /* InKeyword */ && inDisallowInContext()) {
break;
}
- if (token() === 118) {
+ if (token() === 118 /* AsKeyword */) {
+ // Make sure we *do* perform ASI for constructs like this:
+ // var x = foo
+ // as (Bar)
+ // This should be parsed as an initialized variable, followed
+ // by a function call to 'as' with the argument 'Bar'
if (scanner.hasPrecedingLineBreak()) {
break;
}
@@ -15927,77 +18368,105 @@ var ts;
return leftOperand;
}
function isBinaryOperator() {
- if (inDisallowInContext() && token() === 92) {
+ if (inDisallowInContext() && token() === 92 /* InKeyword */) {
return false;
}
return ts.getBinaryOperatorPrecedence(token()) > 0;
}
function makeBinaryExpression(left, operatorToken, right) {
- var node = createNode(200, left.pos);
+ var node = createNode(200 /* BinaryExpression */, left.pos);
node.left = left;
node.operatorToken = operatorToken;
node.right = right;
return finishNode(node);
}
function makeAsExpression(left, right) {
- var node = createNode(208, left.pos);
+ var node = createNode(208 /* AsExpression */, left.pos);
node.expression = left;
node.type = right;
return finishNode(node);
}
function parsePrefixUnaryExpression() {
- var node = createNode(198);
+ var node = createNode(198 /* PrefixUnaryExpression */);
node.operator = token();
nextToken();
node.operand = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseDeleteExpression() {
- var node = createNode(194);
+ var node = createNode(194 /* DeleteExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseTypeOfExpression() {
- var node = createNode(195);
+ var node = createNode(195 /* TypeOfExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseVoidExpression() {
- var node = createNode(196);
+ var node = createNode(196 /* VoidExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
function isAwaitExpression() {
- if (token() === 121) {
+ if (token() === 121 /* AwaitKeyword */) {
if (inAwaitContext()) {
return true;
}
+ // here we are using similar heuristics as 'isYieldExpression'
return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
}
return false;
}
function parseAwaitExpression() {
- var node = createNode(197);
+ var node = createNode(197 /* AwaitExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
+ /**
+ * Parse ES7 exponential expression and await expression
+ *
+ * ES7 ExponentiationExpression:
+ * 1) UnaryExpression[?Yield]
+ * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
+ *
+ */
function parseUnaryExpressionOrHigher() {
+ /**
+ * ES7 UpdateExpression:
+ * 1) LeftHandSideExpression[?Yield]
+ * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++
+ * 3) LeftHandSideExpression[?Yield][no LineTerminator here]--
+ * 4) ++UnaryExpression[?Yield]
+ * 5) --UnaryExpression[?Yield]
+ */
if (isUpdateExpression()) {
var updateExpression = parseUpdateExpression();
- return token() === 40 ?
+ return token() === 40 /* AsteriskAsteriskToken */ ?
parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
updateExpression;
}
+ /**
+ * ES7 UnaryExpression:
+ * 1) UpdateExpression[?yield]
+ * 2) delete UpdateExpression[?yield]
+ * 3) void UpdateExpression[?yield]
+ * 4) typeof UpdateExpression[?yield]
+ * 5) + UpdateExpression[?yield]
+ * 6) - UpdateExpression[?yield]
+ * 7) ~ UpdateExpression[?yield]
+ * 8) ! UpdateExpression[?yield]
+ */
var unaryOperator = token();
var simpleUnaryExpression = parseSimpleUnaryExpression();
- if (token() === 40) {
+ if (token() === 40 /* AsteriskAsteriskToken */) {
var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
var end = simpleUnaryExpression.end;
- if (simpleUnaryExpression.kind === 190) {
+ if (simpleUnaryExpression.kind === 190 /* TypeAssertionExpression */) {
parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
}
else {
@@ -16006,63 +18475,108 @@ var ts;
}
return simpleUnaryExpression;
}
+ /**
+ * Parse ES7 simple-unary expression or higher:
+ *
+ * ES7 UnaryExpression:
+ * 1) UpdateExpression[?yield]
+ * 2) delete UnaryExpression[?yield]
+ * 3) void UnaryExpression[?yield]
+ * 4) typeof UnaryExpression[?yield]
+ * 5) + UnaryExpression[?yield]
+ * 6) - UnaryExpression[?yield]
+ * 7) ~ UnaryExpression[?yield]
+ * 8) ! UnaryExpression[?yield]
+ * 9) [+Await] await UnaryExpression[?yield]
+ */
function parseSimpleUnaryExpression() {
switch (token()) {
- case 37:
- case 38:
- case 52:
- case 51:
+ case 37 /* PlusToken */:
+ case 38 /* MinusToken */:
+ case 52 /* TildeToken */:
+ case 51 /* ExclamationToken */:
return parsePrefixUnaryExpression();
- case 80:
+ case 80 /* DeleteKeyword */:
return parseDeleteExpression();
- case 103:
+ case 103 /* TypeOfKeyword */:
return parseTypeOfExpression();
- case 105:
+ case 105 /* VoidKeyword */:
return parseVoidExpression();
- case 27:
+ case 27 /* LessThanToken */:
+ // This is modified UnaryExpression grammar in TypeScript
+ // UnaryExpression (modified):
+ // < type > UnaryExpression
return parseTypeAssertion();
- case 121:
+ case 121 /* AwaitKeyword */:
if (isAwaitExpression()) {
return parseAwaitExpression();
}
+ // falls through
default:
return parseUpdateExpression();
}
}
+ /**
+ * Check if the current token can possibly be an ES7 increment expression.
+ *
+ * ES7 UpdateExpression:
+ * LeftHandSideExpression[?Yield]
+ * LeftHandSideExpression[?Yield][no LineTerminator here]++
+ * LeftHandSideExpression[?Yield][no LineTerminator here]--
+ * ++LeftHandSideExpression[?Yield]
+ * --LeftHandSideExpression[?Yield]
+ */
function isUpdateExpression() {
+ // This function is called inside parseUnaryExpression to decide
+ // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
switch (token()) {
- case 37:
- case 38:
- case 52:
- case 51:
- case 80:
- case 103:
- case 105:
- case 121:
+ case 37 /* PlusToken */:
+ case 38 /* MinusToken */:
+ case 52 /* TildeToken */:
+ case 51 /* ExclamationToken */:
+ case 80 /* DeleteKeyword */:
+ case 103 /* TypeOfKeyword */:
+ case 105 /* VoidKeyword */:
+ case 121 /* AwaitKeyword */:
return false;
- case 27:
- if (sourceFile.languageVariant !== 1) {
+ case 27 /* LessThanToken */:
+ // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
+ if (sourceFile.languageVariant !== 1 /* JSX */) {
return false;
}
+ // We are in JSX context and the token is part of JSXElement.
+ // falls through
default:
return true;
}
}
+ /**
+ * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
+ *
+ * ES7 UpdateExpression[yield]:
+ * 1) LeftHandSideExpression[?yield]
+ * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
+ * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
+ * 4) ++LeftHandSideExpression[?yield]
+ * 5) --LeftHandSideExpression[?yield]
+ * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
+ */
function parseUpdateExpression() {
- if (token() === 43 || token() === 44) {
- var node = createNode(198);
+ if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) {
+ var node = createNode(198 /* PrefixUnaryExpression */);
node.operator = token();
nextToken();
node.operand = parseLeftHandSideExpressionOrHigher();
return finishNode(node);
}
- else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
- return parseJsxElementOrSelfClosingElementOrFragment(true);
+ else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
+ // JSXElement is part of primaryExpression
+ return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
}
var expression = parseLeftHandSideExpressionOrHigher();
ts.Debug.assert(ts.isLeftHandSideExpression(expression));
- if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) {
- var node = createNode(199, expression.pos);
+ if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
+ var node = createNode(199 /* PostfixUnaryExpression */, expression.pos);
node.operand = expression;
node.operator = token();
nextToken();
@@ -16071,51 +18585,139 @@ var ts;
return expression;
}
function parseLeftHandSideExpressionOrHigher() {
+ // Original Ecma:
+ // LeftHandSideExpression: See 11.2
+ // NewExpression
+ // CallExpression
+ //
+ // Our simplification:
+ //
+ // LeftHandSideExpression: See 11.2
+ // MemberExpression
+ // CallExpression
+ //
+ // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
+ // MemberExpression to make our lives easier.
+ //
+ // to best understand the below code, it's important to see how CallExpression expands
+ // out into its own productions:
+ //
+ // CallExpression:
+ // MemberExpression Arguments
+ // CallExpression Arguments
+ // CallExpression[Expression]
+ // CallExpression.IdentifierName
+ // import (AssignmentExpression)
+ // super Arguments
+ // super.IdentifierName
+ //
+ // Because of the recursion in these calls, we need to bottom out first. There are three
+ // bottom out states we can run into: 1) We see 'super' which must start either of
+ // the last two CallExpression productions. 2) We see 'import' which must start import call.
+ // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
+ // or starts the beginning of the first four CallExpression productions.
var expression;
- if (token() === 91) {
+ if (token() === 91 /* ImportKeyword */) {
if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
- sourceFile.flags |= 524288;
+ // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
+ // For example:
+ // var foo3 = require("subfolder
+ // import * as foo1 from "module-from-node
+ // We want this import to be a statement rather than import call expression
+ sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */;
expression = parseTokenNode();
}
else if (lookAhead(nextTokenIsDot)) {
+ // This is an 'import.*' metaproperty (i.e. 'import.meta')
var fullStart = scanner.getStartPos();
- nextToken();
- nextToken();
- var node = createNode(210, fullStart);
- node.keywordToken = 91;
+ nextToken(); // advance past the 'import'
+ nextToken(); // advance past the dot
+ var node = createNode(210 /* MetaProperty */, fullStart);
+ node.keywordToken = 91 /* ImportKeyword */;
node.name = parseIdentifierName();
expression = finishNode(node);
- sourceFile.flags |= 1048576;
+ sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */;
}
else {
expression = parseMemberExpressionOrHigher();
}
}
else {
- expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher();
+ expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
}
+ // Now, we *may* be complete. However, we might have consumed the start of a
+ // CallExpression. As such, we need to consume the rest of it here to be complete.
return parseCallExpressionRest(expression);
}
function parseMemberExpressionOrHigher() {
+ // Note: to make our lives simpler, we decompose the NewExpression productions and
+ // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
+ // like so:
+ //
+ // PrimaryExpression : See 11.1
+ // this
+ // Identifier
+ // Literal
+ // ArrayLiteral
+ // ObjectLiteral
+ // (Expression)
+ // FunctionExpression
+ // new MemberExpression Arguments?
+ //
+ // MemberExpression : See 11.2
+ // PrimaryExpression
+ // MemberExpression[Expression]
+ // MemberExpression.IdentifierName
+ //
+ // CallExpression : See 11.2
+ // MemberExpression
+ // CallExpression Arguments
+ // CallExpression[Expression]
+ // CallExpression.IdentifierName
+ //
+ // Technically this is ambiguous. i.e. CallExpression defines:
+ //
+ // CallExpression:
+ // CallExpression Arguments
+ //
+ // If you see: "new Foo()"
+ //
+ // Then that could be treated as a single ObjectCreationExpression, or it could be
+ // treated as the invocation of "new Foo". We disambiguate that in code (to match
+ // the original grammar) by making sure that if we see an ObjectCreationExpression
+ // we always consume arguments if they are there. So we treat "new Foo()" as an
+ // object creation only, and not at all as an invocation. Another way to think
+ // about this is that for every "new" that we see, we will consume an argument list if
+ // it is there as part of the *associated* object creation node. Any additional
+ // argument lists we see, will become invocation expressions.
+ //
+ // Because there are no other places in the grammar now that refer to FunctionExpression
+ // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
+ // production.
+ //
+ // Because CallExpression and MemberExpression are left recursive, we need to bottom out
+ // of the recursion immediately. So we parse out a primary expression to start with.
var expression = parsePrimaryExpression();
return parseMemberExpressionRest(expression);
}
function parseSuperExpression() {
var expression = parseTokenNode();
- if (token() === 19 || token() === 23 || token() === 21) {
+ if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) {
return expression;
}
- var node = createNode(185, expression.pos);
+ // If we have seen "super" it must be followed by '(' or '.'.
+ // If it wasn't then just try to parse out a '.' and report an error.
+ var node = createNode(185 /* PropertyAccessExpression */, expression.pos);
node.expression = expression;
- parseExpectedToken(23, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
- node.name = parseRightSideOfDot(true);
+ parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
+ node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
return finishNode(node);
}
function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
var result;
- if (opening.kind === 257) {
- var node = createNode(255, opening.pos);
+ if (opening.kind === 257 /* JsxOpeningElement */) {
+ var node = createNode(255 /* JsxElement */, opening.pos);
node.openingElement = opening;
node.children = parseJsxChildren(node.openingElement);
node.closingElement = parseJsxClosingElement(inExpressionContext);
@@ -16124,26 +18726,34 @@ var ts;
}
result = finishNode(node);
}
- else if (opening.kind === 260) {
- var node = createNode(259, opening.pos);
+ else if (opening.kind === 260 /* JsxOpeningFragment */) {
+ var node = createNode(259 /* JsxFragment */, opening.pos);
node.openingFragment = opening;
node.children = parseJsxChildren(node.openingFragment);
node.closingFragment = parseJsxClosingFragment(inExpressionContext);
result = finishNode(node);
}
else {
- ts.Debug.assert(opening.kind === 256);
+ ts.Debug.assert(opening.kind === 256 /* JsxSelfClosingElement */);
+ // Nothing else to do for self-closing elements
result = opening;
}
- if (inExpressionContext && token() === 27) {
- var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(true); });
+ // If the user writes the invalid code '' in an expression context (i.e. not wrapped in
+ // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag
+ // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
+ // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
+ // does less damage and we can report a better error.
+ // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
+ // of one sort or another.
+ if (inExpressionContext && token() === 27 /* LessThanToken */) {
+ var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
if (invalidElement) {
parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
- var badNode = createNode(200, result.pos);
+ var badNode = createNode(200 /* BinaryExpression */, result.pos);
badNode.end = invalidElement.end;
badNode.left = result;
badNode.right = invalidElement;
- badNode.operatorToken = createMissingNode(26, false, undefined);
+ badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217
badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
return badNode;
}
@@ -16151,14 +18761,16 @@ var ts;
return result;
}
function parseJsxText() {
- var node = createNode(10);
- node.containsOnlyWhiteSpaces = currentToken === 11;
+ var node = createNode(10 /* JsxText */);
+ node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
function parseJsxChild(openingTag, token) {
switch (token) {
- case 1:
+ case 1 /* EndOfFileToken */:
+ // If we hit EOF, issue the error at the tag that lacks the closing element
+ // rather than at the end of the file (which is useless)
if (ts.isJsxOpeningFragment(openingTag)) {
parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
}
@@ -16166,16 +18778,16 @@ var ts;
parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
}
return undefined;
- case 28:
- case 7:
+ case 28 /* LessThanSlashToken */:
+ case 7 /* ConflictMarkerTrivia */:
return undefined;
- case 10:
- case 11:
+ case 10 /* JsxText */:
+ case 11 /* JsxTextAllWhiteSpaces */:
return parseJsxText();
- case 17:
- return parseJsxExpression(false);
- case 27:
- return parseJsxElementOrSelfClosingElementOrFragment(false);
+ case 17 /* OpenBraceToken */:
+ return parseJsxExpression(/*inExpressionContext*/ false);
+ case 27 /* LessThanToken */:
+ return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
default:
return ts.Debug.assertNever(token);
}
@@ -16184,7 +18796,7 @@ var ts;
var list = [];
var listPos = getNodePos();
var saveParsingContext = parsingContext;
- parsingContext |= 1 << 14;
+ parsingContext |= 1 << 14 /* JsxChildren */;
while (true) {
var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
if (!child)
@@ -16195,15 +18807,16 @@ var ts;
return createNodeArray(list, listPos);
}
function parseJsxAttributes() {
- var jsxAttributes = createNode(263);
- jsxAttributes.properties = parseList(13, parseJsxAttribute);
+ var jsxAttributes = createNode(263 /* JsxAttributes */);
+ jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
return finishNode(jsxAttributes);
}
function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
var fullStart = scanner.getStartPos();
- parseExpected(27);
- if (token() === 29) {
- var node_1 = createNode(260, fullStart);
+ parseExpected(27 /* LessThanToken */);
+ if (token() === 29 /* GreaterThanToken */) {
+ // See below for explanation of scanJsxText
+ var node_1 = createNode(260 /* JsxOpeningFragment */, fullStart);
scanJsxText();
return finishNode(node_1);
}
@@ -16211,20 +18824,23 @@ var ts;
var typeArguments = tryParseTypeArguments();
var attributes = parseJsxAttributes();
var node;
- if (token() === 29) {
- node = createNode(257, fullStart);
+ if (token() === 29 /* GreaterThanToken */) {
+ // Closing tag, so scan the immediately-following text with the JSX scanning instead
+ // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
+ // scanning errors
+ node = createNode(257 /* JsxOpeningElement */, fullStart);
scanJsxText();
}
else {
- parseExpected(41);
+ parseExpected(41 /* SlashToken */);
if (inExpressionContext) {
- parseExpected(29);
+ parseExpected(29 /* GreaterThanToken */);
}
else {
- parseExpected(29, undefined, false);
+ parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
- node = createNode(256, fullStart);
+ node = createNode(256 /* JsxSelfClosingElement */, fullStart);
}
node.tagName = tagName;
node.typeArguments = typeArguments;
@@ -16233,119 +18849,125 @@ var ts;
}
function parseJsxElementName() {
scanJsxIdentifier();
- var expression = token() === 99 ?
+ // JsxElement can have name in the form of
+ // propertyAccessExpression
+ // primaryExpression in the form of an identifier and "this" keyword
+ // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
+ // We only want to consider "this" as a primaryExpression
+ var expression = token() === 99 /* ThisKeyword */ ?
parseTokenNode() : parseIdentifierName();
- while (parseOptional(23)) {
- var propertyAccess = createNode(185, expression.pos);
+ while (parseOptional(23 /* DotToken */)) {
+ var propertyAccess = createNode(185 /* PropertyAccessExpression */, expression.pos);
propertyAccess.expression = expression;
- propertyAccess.name = parseRightSideOfDot(true);
+ propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
expression = finishNode(propertyAccess);
}
return expression;
}
function parseJsxExpression(inExpressionContext) {
- var node = createNode(265);
- if (!parseExpected(17)) {
+ var node = createNode(265 /* JsxExpression */);
+ if (!parseExpected(17 /* OpenBraceToken */)) {
return undefined;
}
- if (token() !== 18) {
- node.dotDotDotToken = parseOptionalToken(24);
+ if (token() !== 18 /* CloseBraceToken */) {
+ node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
}
if (inExpressionContext) {
- parseExpected(18);
+ parseExpected(18 /* CloseBraceToken */);
}
else {
- parseExpected(18, undefined, false);
+ parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
return finishNode(node);
}
function parseJsxAttribute() {
- if (token() === 17) {
+ if (token() === 17 /* OpenBraceToken */) {
return parseJsxSpreadAttribute();
}
scanJsxIdentifier();
- var node = createNode(262);
+ var node = createNode(262 /* JsxAttribute */);
node.name = parseIdentifierName();
- if (token() === 58) {
+ if (token() === 58 /* EqualsToken */) {
switch (scanJsxAttributeValue()) {
- case 9:
+ case 9 /* StringLiteral */:
node.initializer = parseLiteralNode();
break;
default:
- node.initializer = parseJsxExpression(true);
+ node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
break;
}
}
return finishNode(node);
}
function parseJsxSpreadAttribute() {
- var node = createNode(264);
- parseExpected(17);
- parseExpected(24);
+ var node = createNode(264 /* JsxSpreadAttribute */);
+ parseExpected(17 /* OpenBraceToken */);
+ parseExpected(24 /* DotDotDotToken */);
node.expression = parseExpression();
- parseExpected(18);
+ parseExpected(18 /* CloseBraceToken */);
return finishNode(node);
}
function parseJsxClosingElement(inExpressionContext) {
- var node = createNode(258);
- parseExpected(28);
+ var node = createNode(258 /* JsxClosingElement */);
+ parseExpected(28 /* LessThanSlashToken */);
node.tagName = parseJsxElementName();
if (inExpressionContext) {
- parseExpected(29);
+ parseExpected(29 /* GreaterThanToken */);
}
else {
- parseExpected(29, undefined, false);
+ parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
return finishNode(node);
}
function parseJsxClosingFragment(inExpressionContext) {
- var node = createNode(261);
- parseExpected(28);
+ var node = createNode(261 /* JsxClosingFragment */);
+ parseExpected(28 /* LessThanSlashToken */);
if (ts.tokenIsIdentifierOrKeyword(token())) {
parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
}
if (inExpressionContext) {
- parseExpected(29);
+ parseExpected(29 /* GreaterThanToken */);
}
else {
- parseExpected(29, undefined, false);
+ parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
return finishNode(node);
}
function parseTypeAssertion() {
- var node = createNode(190);
- parseExpected(27);
+ var node = createNode(190 /* TypeAssertionExpression */);
+ parseExpected(27 /* LessThanToken */);
node.type = parseType();
- parseExpected(29);
+ parseExpected(29 /* GreaterThanToken */);
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseMemberExpressionRest(expression) {
while (true) {
- var dotToken = parseOptionalToken(23);
+ var dotToken = parseOptionalToken(23 /* DotToken */);
if (dotToken) {
- var propertyAccess = createNode(185, expression.pos);
+ var propertyAccess = createNode(185 /* PropertyAccessExpression */, expression.pos);
propertyAccess.expression = expression;
- propertyAccess.name = parseRightSideOfDot(true);
+ propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
expression = finishNode(propertyAccess);
continue;
}
- if (token() === 51 && !scanner.hasPrecedingLineBreak()) {
+ if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
nextToken();
- var nonNullExpression = createNode(209, expression.pos);
+ var nonNullExpression = createNode(209 /* NonNullExpression */, expression.pos);
nonNullExpression.expression = expression;
expression = finishNode(nonNullExpression);
continue;
}
- if (!inDecoratorContext() && parseOptional(21)) {
- var indexedAccess = createNode(186, expression.pos);
+ // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
+ if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) {
+ var indexedAccess = createNode(186 /* ElementAccessExpression */, expression.pos);
indexedAccess.expression = expression;
- if (token() === 22) {
- indexedAccess.argumentExpression = createMissingNode(71, true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
+ if (token() === 22 /* CloseBracketToken */) {
+ indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
}
else {
var argument = allowInAnd(parseExpression);
@@ -16354,25 +18976,25 @@ var ts;
}
indexedAccess.argumentExpression = argument;
}
- parseExpected(22);
+ parseExpected(22 /* CloseBracketToken */);
expression = finishNode(indexedAccess);
continue;
}
if (isTemplateStartOfTaggedTemplate()) {
- expression = parseTaggedTemplateRest(expression, undefined);
+ expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined);
continue;
}
return expression;
}
}
function isTemplateStartOfTaggedTemplate() {
- return token() === 13 || token() === 14;
+ return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */;
}
function parseTaggedTemplateRest(tag, typeArguments) {
- var tagExpression = createNode(189, tag.pos);
+ var tagExpression = createNode(189 /* TaggedTemplateExpression */, tag.pos);
tagExpression.tag = tag;
tagExpression.typeArguments = typeArguments;
- tagExpression.template = token() === 13
+ tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */
? parseLiteralNode()
: parseTemplateExpression();
return finishNode(tagExpression);
@@ -16380,7 +19002,11 @@ var ts;
function parseCallExpressionRest(expression) {
while (true) {
expression = parseMemberExpressionRest(expression);
- if (token() === 27) {
+ if (token() === 27 /* LessThanToken */) {
+ // See if this is the start of a generic invocation. If so, consume it and
+ // keep checking for postfix expressions. Otherwise, it's just a '<' that's
+ // part of an arithmetic expression. Break out so we consume it higher in the
+ // stack.
var typeArguments = tryParse(parseTypeArgumentsInExpression);
if (!typeArguments) {
return expression;
@@ -16389,15 +19015,15 @@ var ts;
expression = parseTaggedTemplateRest(expression, typeArguments);
continue;
}
- var callExpr = createNode(187, expression.pos);
+ var callExpr = createNode(187 /* CallExpression */, expression.pos);
callExpr.expression = expression;
callExpr.typeArguments = typeArguments;
callExpr.arguments = parseArgumentList();
expression = finishNode(callExpr);
continue;
}
- else if (token() === 19) {
- var callExpr = createNode(187, expression.pos);
+ else if (token() === 19 /* OpenParenToken */) {
+ var callExpr = createNode(187 /* CallExpression */, expression.pos);
callExpr.expression = expression;
callExpr.arguments = parseArgumentList();
expression = finishNode(callExpr);
@@ -16407,191 +19033,217 @@ var ts;
}
}
function parseArgumentList() {
- parseExpected(19);
- var result = parseDelimitedList(11, parseArgumentExpression);
- parseExpected(20);
+ parseExpected(19 /* OpenParenToken */);
+ var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
+ parseExpected(20 /* CloseParenToken */);
return result;
}
function parseTypeArgumentsInExpression() {
- if (!parseOptional(27)) {
+ if (!parseOptional(27 /* LessThanToken */)) {
return undefined;
}
- var typeArguments = parseDelimitedList(19, parseType);
- if (!parseExpected(29)) {
+ var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType);
+ if (!parseExpected(29 /* GreaterThanToken */)) {
+ // If it doesn't have the closing `>` then it's definitely not an type argument list.
return undefined;
}
+ // If we have a '<', then only parse this as a argument list if the type arguments
+ // are complete and we have an open paren. if we don't, rewind and return nothing.
return typeArguments && canFollowTypeArgumentsInExpression()
? typeArguments
: undefined;
}
function canFollowTypeArgumentsInExpression() {
switch (token()) {
- case 19:
- case 13:
- case 14:
- case 23:
- case 20:
- case 22:
- case 56:
- case 25:
- case 55:
- case 32:
- case 34:
- case 33:
- case 35:
- case 53:
- case 54:
- case 50:
- case 48:
- case 49:
- case 18:
- case 1:
+ case 19 /* OpenParenToken */: // foo(
+ case 13 /* NoSubstitutionTemplateLiteral */: // foo `...`
+ case 14 /* TemplateHead */: // foo `...${100}...`
+ // these are the only tokens can legally follow a type argument
+ // list. So we definitely want to treat them as type arg lists.
+ case 23 /* DotToken */: // foo.
+ case 20 /* CloseParenToken */: // foo)
+ case 22 /* CloseBracketToken */: // foo]
+ case 56 /* ColonToken */: // foo:
+ case 25 /* SemicolonToken */: // foo;
+ case 55 /* QuestionToken */: // foo?
+ case 32 /* EqualsEqualsToken */: // foo ==
+ case 34 /* EqualsEqualsEqualsToken */: // foo ===
+ case 33 /* ExclamationEqualsToken */: // foo !=
+ case 35 /* ExclamationEqualsEqualsToken */: // foo !==
+ case 53 /* AmpersandAmpersandToken */: // foo &&
+ case 54 /* BarBarToken */: // foo ||
+ case 50 /* CaretToken */: // foo ^
+ case 48 /* AmpersandToken */: // foo &
+ case 49 /* BarToken */: // foo |
+ case 18 /* CloseBraceToken */: // foo }
+ case 1 /* EndOfFileToken */: // foo
+ // these cases can't legally follow a type arg list. However, they're not legal
+ // expressions either. The user is probably in the middle of a generic type. So
+ // treat it as such.
return true;
- case 26:
- case 17:
+ case 26 /* CommaToken */: // foo,
+ case 17 /* OpenBraceToken */: // foo {
+ // We don't want to treat these as type arguments. Otherwise we'll parse this
+ // as an invocation expression. Instead, we want to parse out the expression
+ // in isolation from the type arguments.
default:
+ // Anything else treat as an expression.
return false;
}
}
function parsePrimaryExpression() {
switch (token()) {
- case 8:
- case 9:
- case 13:
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
return parseLiteralNode();
- case 99:
- case 97:
- case 95:
- case 101:
- case 86:
+ case 99 /* ThisKeyword */:
+ case 97 /* SuperKeyword */:
+ case 95 /* NullKeyword */:
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
return parseTokenNode();
- case 19:
+ case 19 /* OpenParenToken */:
return parseParenthesizedExpression();
- case 21:
+ case 21 /* OpenBracketToken */:
return parseArrayLiteralExpression();
- case 17:
+ case 17 /* OpenBraceToken */:
return parseObjectLiteralExpression();
- case 120:
+ case 120 /* AsyncKeyword */:
+ // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
+ // If we encounter `async [no LineTerminator here] function` then this is an async
+ // function; otherwise, its an identifier.
if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
break;
}
return parseFunctionExpression();
- case 75:
+ case 75 /* ClassKeyword */:
return parseClassExpression();
- case 89:
+ case 89 /* FunctionKeyword */:
return parseFunctionExpression();
- case 94:
+ case 94 /* NewKeyword */:
return parseNewExpressionOrNewDotTarget();
- case 41:
- case 63:
- if (reScanSlashToken() === 12) {
+ case 41 /* SlashToken */:
+ case 63 /* SlashEqualsToken */:
+ if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) {
return parseLiteralNode();
}
break;
- case 14:
+ case 14 /* TemplateHead */:
return parseTemplateExpression();
}
return parseIdentifier(ts.Diagnostics.Expression_expected);
}
function parseParenthesizedExpression() {
- var node = createNodeWithJSDoc(191);
- parseExpected(19);
+ var node = createNodeWithJSDoc(191 /* ParenthesizedExpression */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
return finishNode(node);
}
function parseSpreadElement() {
- var node = createNode(204);
- parseExpected(24);
+ var node = createNode(204 /* SpreadElement */);
+ parseExpected(24 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
return finishNode(node);
}
function parseArgumentOrArrayLiteralElement() {
- return token() === 24 ? parseSpreadElement() :
- token() === 26 ? createNode(206) :
+ return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() :
+ token() === 26 /* CommaToken */ ? createNode(206 /* OmittedExpression */) :
parseAssignmentExpressionOrHigher();
}
function parseArgumentExpression() {
return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
}
function parseArrayLiteralExpression() {
- var node = createNode(183);
- parseExpected(21);
+ var node = createNode(183 /* ArrayLiteralExpression */);
+ parseExpected(21 /* OpenBracketToken */);
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
}
- node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement);
- parseExpected(22);
+ node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
+ parseExpected(22 /* CloseBracketToken */);
return finishNode(node);
}
function parseObjectLiteralElement() {
- var node = createNodeWithJSDoc(0);
- if (parseOptionalToken(24)) {
- node.kind = 272;
+ var node = createNodeWithJSDoc(0 /* Unknown */);
+ if (parseOptionalToken(24 /* DotDotDotToken */)) {
+ node.kind = 272 /* SpreadAssignment */;
node.expression = parseAssignmentExpressionOrHigher();
return finishNode(node);
}
node.decorators = parseDecorators();
node.modifiers = parseModifiers();
- if (parseContextualModifier(125)) {
- return parseAccessorDeclaration(node, 156);
+ if (parseContextualModifier(125 /* GetKeyword */)) {
+ return parseAccessorDeclaration(node, 156 /* GetAccessor */);
}
- if (parseContextualModifier(136)) {
- return parseAccessorDeclaration(node, 157);
+ if (parseContextualModifier(136 /* SetKeyword */)) {
+ return parseAccessorDeclaration(node, 157 /* SetAccessor */);
}
- var asteriskToken = parseOptionalToken(39);
+ var asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
var tokenIsIdentifier = isIdentifier();
node.name = parsePropertyName();
- node.questionToken = parseOptionalToken(55);
- if (asteriskToken || token() === 19 || token() === 27) {
+ // Disallowing of optional property assignments happens in the grammar checker.
+ node.questionToken = parseOptionalToken(55 /* QuestionToken */);
+ if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
return parseMethodDeclaration(node, asteriskToken);
}
- var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58);
+ // check if it is short-hand property assignment or normal property assignment
+ // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
+ // CoverInitializedName[Yield] :
+ // IdentifierReference[?Yield] Initializer[In, ?Yield]
+ // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
+ var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */);
if (isShorthandPropertyAssignment) {
- node.kind = 271;
- var equalsToken = parseOptionalToken(58);
+ node.kind = 271 /* ShorthandPropertyAssignment */;
+ var equalsToken = parseOptionalToken(58 /* EqualsToken */);
if (equalsToken) {
node.equalsToken = equalsToken;
node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
}
}
else {
- node.kind = 270;
- parseExpected(56);
+ node.kind = 270 /* PropertyAssignment */;
+ parseExpected(56 /* ColonToken */);
node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
}
return finishNode(node);
}
function parseObjectLiteralExpression() {
- var node = createNode(184);
- parseExpected(17);
+ var node = createNode(184 /* ObjectLiteralExpression */);
+ parseExpected(17 /* OpenBraceToken */);
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
}
- node.properties = parseDelimitedList(12, parseObjectLiteralElement, true);
- parseExpected(18);
+ node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
+ parseExpected(18 /* CloseBraceToken */);
return finishNode(node);
}
function parseFunctionExpression() {
+ // GeneratorExpression:
+ // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
+ //
+ // FunctionExpression:
+ // function BindingIdentifier[opt](FormalParameters){ FunctionBody }
var saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
- setDecoratorContext(false);
+ setDecoratorContext(/*val*/ false);
}
- var node = createNodeWithJSDoc(192);
+ var node = createNodeWithJSDoc(192 /* FunctionExpression */);
node.modifiers = parseModifiers();
- parseExpected(89);
- node.asteriskToken = parseOptionalToken(39);
- var isGenerator = node.asteriskToken ? 1 : 0;
- var isAsync = ts.hasModifier(node, 256) ? 2 : 0;
+ parseExpected(89 /* FunctionKeyword */);
+ node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
+ var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
+ var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
node.name =
isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
isGenerator ? doInYieldContext(parseOptionalIdentifier) :
isAsync ? doInAwaitContext(parseOptionalIdentifier) :
parseOptionalIdentifier();
- fillSignature(56, isGenerator | isAsync, node);
+ fillSignature(56 /* ColonToken */, isGenerator | isAsync, node);
node.body = parseFunctionBlock(isGenerator | isAsync);
if (saveDecoratorContext) {
- setDecoratorContext(true);
+ setDecoratorContext(/*val*/ true);
}
return finishNode(node);
}
@@ -16600,10 +19252,10 @@ var ts;
}
function parseNewExpressionOrNewDotTarget() {
var fullStart = scanner.getStartPos();
- parseExpected(94);
- if (parseOptional(23)) {
- var node_2 = createNode(210, fullStart);
- node_2.keywordToken = 94;
+ parseExpected(94 /* NewKeyword */);
+ if (parseOptional(23 /* DotToken */)) {
+ var node_2 = createNode(210 /* MetaProperty */, fullStart);
+ node_2.keywordToken = 94 /* NewKeyword */;
node_2.name = parseIdentifierName();
return finishNode(node_2);
}
@@ -16619,22 +19271,23 @@ var ts;
}
break;
}
- var node = createNode(188, fullStart);
+ var node = createNode(188 /* NewExpression */, fullStart);
node.expression = expression;
node.typeArguments = typeArguments;
- if (node.typeArguments || token() === 19) {
+ if (node.typeArguments || token() === 19 /* OpenParenToken */) {
node.arguments = parseArgumentList();
}
return finishNode(node);
}
+ // STATEMENTS
function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
- var node = createNode(213);
- if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) {
+ var node = createNode(213 /* Block */);
+ if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
}
- node.statements = parseList(1, parseStatement);
- parseExpected(18);
+ node.statements = parseList(1 /* BlockStatements */, parseStatement);
+ parseExpected(18 /* CloseBraceToken */);
}
else {
node.statements = createMissingList();
@@ -16643,98 +19296,104 @@ var ts;
}
function parseFunctionBlock(flags, diagnosticMessage) {
var savedYieldContext = inYieldContext();
- setYieldContext(!!(flags & 1));
+ setYieldContext(!!(flags & 1 /* Yield */));
var savedAwaitContext = inAwaitContext();
- setAwaitContext(!!(flags & 2));
+ setAwaitContext(!!(flags & 2 /* Await */));
+ // We may be in a [Decorator] context when parsing a function expression or
+ // arrow function. The body of the function is not in [Decorator] context.
var saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
- setDecoratorContext(false);
+ setDecoratorContext(/*val*/ false);
}
- var block = parseBlock(!!(flags & 16), diagnosticMessage);
+ var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
if (saveDecoratorContext) {
- setDecoratorContext(true);
+ setDecoratorContext(/*val*/ true);
}
setYieldContext(savedYieldContext);
setAwaitContext(savedAwaitContext);
return block;
}
function parseEmptyStatement() {
- var node = createNode(215);
- parseExpected(25);
+ var node = createNode(215 /* EmptyStatement */);
+ parseExpected(25 /* SemicolonToken */);
return finishNode(node);
}
function parseIfStatement() {
- var node = createNode(217);
- parseExpected(90);
- parseExpected(19);
+ var node = createNode(217 /* IfStatement */);
+ parseExpected(90 /* IfKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
node.thenStatement = parseStatement();
- node.elseStatement = parseOptional(82) ? parseStatement() : undefined;
+ node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined;
return finishNode(node);
}
function parseDoStatement() {
- var node = createNode(218);
- parseExpected(81);
+ var node = createNode(218 /* DoStatement */);
+ parseExpected(81 /* DoKeyword */);
node.statement = parseStatement();
- parseExpected(106);
- parseExpected(19);
+ parseExpected(106 /* WhileKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
- parseExpected(20);
- parseOptional(25);
+ parseExpected(20 /* CloseParenToken */);
+ // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
+ // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
+ // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
+ // do;while(0)x will have a semicolon inserted before x.
+ parseOptional(25 /* SemicolonToken */);
return finishNode(node);
}
function parseWhileStatement() {
- var node = createNode(219);
- parseExpected(106);
- parseExpected(19);
+ var node = createNode(219 /* WhileStatement */);
+ parseExpected(106 /* WhileKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
node.statement = parseStatement();
return finishNode(node);
}
function parseForOrForInOrForOfStatement() {
var pos = getNodePos();
- parseExpected(88);
- var awaitToken = parseOptionalToken(121);
- parseExpected(19);
+ parseExpected(88 /* ForKeyword */);
+ var awaitToken = parseOptionalToken(121 /* AwaitKeyword */);
+ parseExpected(19 /* OpenParenToken */);
var initializer;
- if (token() !== 25) {
- if (token() === 104 || token() === 110 || token() === 76) {
- initializer = parseVariableDeclarationList(true);
+ if (token() !== 25 /* SemicolonToken */) {
+ if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) {
+ initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
}
else {
initializer = disallowInAnd(parseExpression);
}
}
var forOrForInOrForOfStatement;
- if (awaitToken ? parseExpected(145) : parseOptional(145)) {
- var forOfStatement = createNode(222, pos);
+ if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) {
+ var forOfStatement = createNode(222 /* ForOfStatement */, pos);
forOfStatement.awaitModifier = awaitToken;
forOfStatement.initializer = initializer;
forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
forOrForInOrForOfStatement = forOfStatement;
}
- else if (parseOptional(92)) {
- var forInStatement = createNode(221, pos);
+ else if (parseOptional(92 /* InKeyword */)) {
+ var forInStatement = createNode(221 /* ForInStatement */, pos);
forInStatement.initializer = initializer;
forInStatement.expression = allowInAnd(parseExpression);
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
forOrForInOrForOfStatement = forInStatement;
}
else {
- var forStatement = createNode(220, pos);
+ var forStatement = createNode(220 /* ForStatement */, pos);
forStatement.initializer = initializer;
- parseExpected(25);
- if (token() !== 25 && token() !== 20) {
+ parseExpected(25 /* SemicolonToken */);
+ if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) {
forStatement.condition = allowInAnd(parseExpression);
}
- parseExpected(25);
- if (token() !== 20) {
+ parseExpected(25 /* SemicolonToken */);
+ if (token() !== 20 /* CloseParenToken */) {
forStatement.incrementor = allowInAnd(parseExpression);
}
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
forOrForInOrForOfStatement = forStatement;
}
forOrForInOrForOfStatement.statement = parseStatement();
@@ -16742,7 +19401,7 @@ var ts;
}
function parseBreakOrContinueStatement(kind) {
var node = createNode(kind);
- parseExpected(kind === 224 ? 72 : 77);
+ parseExpected(kind === 224 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */);
if (!canParseSemicolon()) {
node.label = parseIdentifier();
}
@@ -16750,8 +19409,8 @@ var ts;
return finishNode(node);
}
function parseReturnStatement() {
- var node = createNode(225);
- parseExpected(96);
+ var node = createNode(225 /* ReturnStatement */);
+ parseExpected(96 /* ReturnKeyword */);
if (!canParseSemicolon()) {
node.expression = allowInAnd(parseExpression);
}
@@ -16759,92 +19418,106 @@ var ts;
return finishNode(node);
}
function parseWithStatement() {
- var node = createNode(226);
- parseExpected(107);
- parseExpected(19);
+ var node = createNode(226 /* WithStatement */);
+ parseExpected(107 /* WithKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
- parseExpected(20);
- node.statement = doInsideOfContext(8388608, parseStatement);
+ parseExpected(20 /* CloseParenToken */);
+ node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement);
return finishNode(node);
}
function parseCaseClause() {
- var node = createNode(266);
- parseExpected(73);
+ var node = createNode(266 /* CaseClause */);
+ parseExpected(73 /* CaseKeyword */);
node.expression = allowInAnd(parseExpression);
- parseExpected(56);
- node.statements = parseList(3, parseStatement);
+ parseExpected(56 /* ColonToken */);
+ node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
return finishNode(node);
}
function parseDefaultClause() {
- var node = createNode(267);
- parseExpected(79);
- parseExpected(56);
- node.statements = parseList(3, parseStatement);
+ var node = createNode(267 /* DefaultClause */);
+ parseExpected(79 /* DefaultKeyword */);
+ parseExpected(56 /* ColonToken */);
+ node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
return finishNode(node);
}
function parseCaseOrDefaultClause() {
- return token() === 73 ? parseCaseClause() : parseDefaultClause();
+ return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
}
function parseSwitchStatement() {
- var node = createNode(227);
- parseExpected(98);
- parseExpected(19);
+ var node = createNode(227 /* SwitchStatement */);
+ parseExpected(98 /* SwitchKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
- parseExpected(20);
- var caseBlock = createNode(241);
- parseExpected(17);
- caseBlock.clauses = parseList(2, parseCaseOrDefaultClause);
- parseExpected(18);
+ parseExpected(20 /* CloseParenToken */);
+ var caseBlock = createNode(241 /* CaseBlock */);
+ parseExpected(17 /* OpenBraceToken */);
+ caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
+ parseExpected(18 /* CloseBraceToken */);
node.caseBlock = finishNode(caseBlock);
return finishNode(node);
}
function parseThrowStatement() {
- var node = createNode(229);
- parseExpected(100);
+ // ThrowStatement[Yield] :
+ // throw [no LineTerminator here]Expression[In, ?Yield];
+ // Because of automatic semicolon insertion, we need to report error if this
+ // throw could be terminated with a semicolon. Note: we can't call 'parseExpression'
+ // directly as that might consume an expression on the following line.
+ // We just return 'undefined' in that case. The actual error will be reported in the
+ // grammar walker.
+ var node = createNode(229 /* ThrowStatement */);
+ parseExpected(100 /* ThrowKeyword */);
node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
parseSemicolon();
return finishNode(node);
}
+ // TODO: Review for error recovery
function parseTryStatement() {
- var node = createNode(230);
- parseExpected(102);
- node.tryBlock = parseBlock(false);
- node.catchClause = token() === 74 ? parseCatchClause() : undefined;
- if (!node.catchClause || token() === 87) {
- parseExpected(87);
- node.finallyBlock = parseBlock(false);
+ var node = createNode(230 /* TryStatement */);
+ parseExpected(102 /* TryKeyword */);
+ node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
+ node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined;
+ // If we don't have a catch clause, then we must have a finally clause. Try to parse
+ // one out no matter what.
+ if (!node.catchClause || token() === 87 /* FinallyKeyword */) {
+ parseExpected(87 /* FinallyKeyword */);
+ node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
}
return finishNode(node);
}
function parseCatchClause() {
- var result = createNode(269);
- parseExpected(74);
- if (parseOptional(19)) {
+ var result = createNode(269 /* CatchClause */);
+ parseExpected(74 /* CatchKeyword */);
+ if (parseOptional(19 /* OpenParenToken */)) {
result.variableDeclaration = parseVariableDeclaration();
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
}
else {
+ // Keep shape of node to avoid degrading performance.
result.variableDeclaration = undefined;
}
- result.block = parseBlock(false);
+ result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
return finishNode(result);
}
function parseDebuggerStatement() {
- var node = createNode(231);
- parseExpected(78);
+ var node = createNode(231 /* DebuggerStatement */);
+ parseExpected(78 /* DebuggerKeyword */);
parseSemicolon();
return finishNode(node);
}
function parseExpressionOrLabeledStatement() {
- var node = createNodeWithJSDoc(0);
+ // Avoiding having to do the lookahead for a labeled statement by just trying to parse
+ // out an expression, seeing if it is identifier and then seeing if it is followed by
+ // a colon.
+ var node = createNodeWithJSDoc(0 /* Unknown */);
var expression = allowInAnd(parseExpression);
- if (expression.kind === 71 && parseOptional(56)) {
- node.kind = 228;
+ if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) {
+ node.kind = 228 /* LabeledStatement */;
node.label = expression;
node.statement = parseStatement();
}
else {
- node.kind = 216;
+ node.kind = 216 /* ExpressionStatement */;
node.expression = expression;
parseSemicolon();
}
@@ -16856,60 +19529,82 @@ var ts;
}
function nextTokenIsClassKeywordOnSameLine() {
nextToken();
- return token() === 75 && !scanner.hasPrecedingLineBreak();
+ return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
}
function nextTokenIsFunctionKeywordOnSameLine() {
nextToken();
- return token() === 89 && !scanner.hasPrecedingLineBreak();
+ return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
}
function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
nextToken();
- return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak();
+ return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
}
function isDeclaration() {
while (true) {
switch (token()) {
- case 104:
- case 110:
- case 76:
- case 89:
- case 75:
- case 83:
+ case 104 /* VarKeyword */:
+ case 110 /* LetKeyword */:
+ case 76 /* ConstKeyword */:
+ case 89 /* FunctionKeyword */:
+ case 75 /* ClassKeyword */:
+ case 83 /* EnumKeyword */:
return true;
- case 109:
- case 139:
+ // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
+ // however, an identifier cannot be followed by another identifier on the same line. This is what we
+ // count on to parse out the respective declarations. For instance, we exploit this to say that
+ //
+ // namespace n
+ //
+ // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
+ //
+ // namespace
+ // n
+ //
+ // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
+ // We need to look one token ahead to see if it permissible to try parsing a declaration.
+ //
+ // *Note*: 'interface' is actually a strict mode reserved word. So while
+ //
+ // "use strict"
+ // interface
+ // I {}
+ //
+ // could be legal, it would add complexity for very little gain.
+ case 109 /* InterfaceKeyword */:
+ case 139 /* TypeKeyword */:
return nextTokenIsIdentifierOnSameLine();
- case 129:
- case 130:
+ case 129 /* ModuleKeyword */:
+ case 130 /* NamespaceKeyword */:
return nextTokenIsIdentifierOrStringLiteralOnSameLine();
- case 117:
- case 120:
- case 124:
- case 112:
- case 113:
- case 114:
- case 132:
+ case 117 /* AbstractKeyword */:
+ case 120 /* AsyncKeyword */:
+ case 124 /* DeclareKeyword */:
+ case 112 /* PrivateKeyword */:
+ case 113 /* ProtectedKeyword */:
+ case 114 /* PublicKeyword */:
+ case 132 /* ReadonlyKeyword */:
nextToken();
+ // ASI takes effect for this modifier.
if (scanner.hasPrecedingLineBreak()) {
return false;
}
continue;
- case 144:
+ case 144 /* GlobalKeyword */:
nextToken();
- return token() === 17 || token() === 71 || token() === 84;
- case 91:
+ return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */;
+ case 91 /* ImportKeyword */:
nextToken();
- return token() === 9 || token() === 39 ||
- token() === 17 || ts.tokenIsIdentifierOrKeyword(token());
- case 84:
+ return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ ||
+ token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
+ case 84 /* ExportKeyword */:
nextToken();
- if (token() === 58 || token() === 39 ||
- token() === 17 || token() === 79 ||
- token() === 118) {
+ if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ ||
+ token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ ||
+ token() === 118 /* AsKeyword */) {
return true;
}
continue;
- case 115:
+ case 115 /* StaticKeyword */:
nextToken();
continue;
default:
@@ -16922,47 +19617,52 @@ var ts;
}
function isStartOfStatement() {
switch (token()) {
- case 57:
- case 25:
- case 17:
- case 104:
- case 110:
- case 89:
- case 75:
- case 83:
- case 90:
- case 81:
- case 106:
- case 88:
- case 77:
- case 72:
- case 96:
- case 107:
- case 98:
- case 100:
- case 102:
- case 78:
- case 74:
- case 87:
+ case 57 /* AtToken */:
+ case 25 /* SemicolonToken */:
+ case 17 /* OpenBraceToken */:
+ case 104 /* VarKeyword */:
+ case 110 /* LetKeyword */:
+ case 89 /* FunctionKeyword */:
+ case 75 /* ClassKeyword */:
+ case 83 /* EnumKeyword */:
+ case 90 /* IfKeyword */:
+ case 81 /* DoKeyword */:
+ case 106 /* WhileKeyword */:
+ case 88 /* ForKeyword */:
+ case 77 /* ContinueKeyword */:
+ case 72 /* BreakKeyword */:
+ case 96 /* ReturnKeyword */:
+ case 107 /* WithKeyword */:
+ case 98 /* SwitchKeyword */:
+ case 100 /* ThrowKeyword */:
+ case 102 /* TryKeyword */:
+ case 78 /* DebuggerKeyword */:
+ // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
+ // however, we say they are here so that we may gracefully parse them and error later.
+ case 74 /* CatchKeyword */:
+ case 87 /* FinallyKeyword */:
return true;
- case 91:
+ case 91 /* ImportKeyword */:
return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
- case 76:
- case 84:
+ case 76 /* ConstKeyword */:
+ case 84 /* ExportKeyword */:
return isStartOfDeclaration();
- case 120:
- case 124:
- case 109:
- case 129:
- case 130:
- case 139:
- case 144:
+ case 120 /* AsyncKeyword */:
+ case 124 /* DeclareKeyword */:
+ case 109 /* InterfaceKeyword */:
+ case 129 /* ModuleKeyword */:
+ case 130 /* NamespaceKeyword */:
+ case 139 /* TypeKeyword */:
+ case 144 /* GlobalKeyword */:
+ // When these don't start a declaration, they're an identifier in an expression statement
return true;
- case 114:
- case 112:
- case 113:
- case 115:
- case 132:
+ case 114 /* PublicKeyword */:
+ case 112 /* PrivateKeyword */:
+ case 113 /* ProtectedKeyword */:
+ case 115 /* StaticKeyword */:
+ case 132 /* ReadonlyKeyword */:
+ // When these don't start a declaration, they may be the start of a class member if an identifier
+ // immediately follows. Otherwise they're an identifier in an expression statement.
return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
default:
return isStartOfExpression();
@@ -16970,73 +19670,76 @@ var ts;
}
function nextTokenIsIdentifierOrStartOfDestructuring() {
nextToken();
- return isIdentifier() || token() === 17 || token() === 21;
+ return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */;
}
function isLetDeclaration() {
+ // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
+ // or [.
return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
}
function parseStatement() {
switch (token()) {
- case 25:
+ case 25 /* SemicolonToken */:
return parseEmptyStatement();
- case 17:
- return parseBlock(false);
- case 104:
- return parseVariableStatement(createNodeWithJSDoc(232));
- case 110:
+ case 17 /* OpenBraceToken */:
+ return parseBlock(/*ignoreMissingOpenBrace*/ false);
+ case 104 /* VarKeyword */:
+ return parseVariableStatement(createNodeWithJSDoc(232 /* VariableDeclaration */));
+ case 110 /* LetKeyword */:
if (isLetDeclaration()) {
- return parseVariableStatement(createNodeWithJSDoc(232));
+ return parseVariableStatement(createNodeWithJSDoc(232 /* VariableDeclaration */));
}
break;
- case 89:
- return parseFunctionDeclaration(createNodeWithJSDoc(234));
- case 75:
- return parseClassDeclaration(createNodeWithJSDoc(235));
- case 90:
+ case 89 /* FunctionKeyword */:
+ return parseFunctionDeclaration(createNodeWithJSDoc(234 /* FunctionDeclaration */));
+ case 75 /* ClassKeyword */:
+ return parseClassDeclaration(createNodeWithJSDoc(235 /* ClassDeclaration */));
+ case 90 /* IfKeyword */:
return parseIfStatement();
- case 81:
+ case 81 /* DoKeyword */:
return parseDoStatement();
- case 106:
+ case 106 /* WhileKeyword */:
return parseWhileStatement();
- case 88:
+ case 88 /* ForKeyword */:
return parseForOrForInOrForOfStatement();
- case 77:
- return parseBreakOrContinueStatement(223);
- case 72:
- return parseBreakOrContinueStatement(224);
- case 96:
+ case 77 /* ContinueKeyword */:
+ return parseBreakOrContinueStatement(223 /* ContinueStatement */);
+ case 72 /* BreakKeyword */:
+ return parseBreakOrContinueStatement(224 /* BreakStatement */);
+ case 96 /* ReturnKeyword */:
return parseReturnStatement();
- case 107:
+ case 107 /* WithKeyword */:
return parseWithStatement();
- case 98:
+ case 98 /* SwitchKeyword */:
return parseSwitchStatement();
- case 100:
+ case 100 /* ThrowKeyword */:
return parseThrowStatement();
- case 102:
- case 74:
- case 87:
+ case 102 /* TryKeyword */:
+ // Include 'catch' and 'finally' for error recovery.
+ case 74 /* CatchKeyword */:
+ case 87 /* FinallyKeyword */:
return parseTryStatement();
- case 78:
+ case 78 /* DebuggerKeyword */:
return parseDebuggerStatement();
- case 57:
+ case 57 /* AtToken */:
return parseDeclaration();
- case 120:
- case 109:
- case 139:
- case 129:
- case 130:
- case 124:
- case 76:
- case 83:
- case 84:
- case 91:
- case 112:
- case 113:
- case 114:
- case 117:
- case 115:
- case 132:
- case 144:
+ case 120 /* AsyncKeyword */:
+ case 109 /* InterfaceKeyword */:
+ case 139 /* TypeKeyword */:
+ case 129 /* ModuleKeyword */:
+ case 130 /* NamespaceKeyword */:
+ case 124 /* DeclareKeyword */:
+ case 76 /* ConstKeyword */:
+ case 83 /* EnumKeyword */:
+ case 84 /* ExportKeyword */:
+ case 91 /* ImportKeyword */:
+ case 112 /* PrivateKeyword */:
+ case 113 /* ProtectedKeyword */:
+ case 114 /* PublicKeyword */:
+ case 117 /* AbstractKeyword */:
+ case 115 /* StaticKeyword */:
+ case 132 /* ReadonlyKeyword */:
+ case 144 /* GlobalKeyword */:
if (isStartOfDeclaration()) {
return parseDeclaration();
}
@@ -17045,18 +19748,18 @@ var ts;
return parseExpressionOrLabeledStatement();
}
function isDeclareModifier(modifier) {
- return modifier.kind === 124;
+ return modifier.kind === 124 /* DeclareKeyword */;
}
function parseDeclaration() {
- var node = createNodeWithJSDoc(0);
+ var node = createNodeWithJSDoc(0 /* Unknown */);
node.decorators = parseDecorators();
node.modifiers = parseModifiers();
if (ts.some(node.modifiers, isDeclareModifier)) {
for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
var m = _a[_i];
- m.flags |= 4194304;
+ m.flags |= 4194304 /* Ambient */;
}
- return doInsideOfContext(4194304, function () { return parseDeclarationWorker(node); });
+ return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); });
}
else {
return parseDeclarationWorker(node);
@@ -17064,79 +19767,82 @@ var ts;
}
function parseDeclarationWorker(node) {
switch (token()) {
- case 104:
- case 110:
- case 76:
+ case 104 /* VarKeyword */:
+ case 110 /* LetKeyword */:
+ case 76 /* ConstKeyword */:
return parseVariableStatement(node);
- case 89:
+ case 89 /* FunctionKeyword */:
return parseFunctionDeclaration(node);
- case 75:
+ case 75 /* ClassKeyword */:
return parseClassDeclaration(node);
- case 109:
+ case 109 /* InterfaceKeyword */:
return parseInterfaceDeclaration(node);
- case 139:
+ case 139 /* TypeKeyword */:
return parseTypeAliasDeclaration(node);
- case 83:
+ case 83 /* EnumKeyword */:
return parseEnumDeclaration(node);
- case 144:
- case 129:
- case 130:
+ case 144 /* GlobalKeyword */:
+ case 129 /* ModuleKeyword */:
+ case 130 /* NamespaceKeyword */:
return parseModuleDeclaration(node);
- case 91:
+ case 91 /* ImportKeyword */:
return parseImportDeclarationOrImportEqualsDeclaration(node);
- case 84:
+ case 84 /* ExportKeyword */:
nextToken();
switch (token()) {
- case 79:
- case 58:
+ case 79 /* DefaultKeyword */:
+ case 58 /* EqualsToken */:
return parseExportAssignment(node);
- case 118:
+ case 118 /* AsKeyword */:
return parseNamespaceExportDeclaration(node);
default:
return parseExportDeclaration(node);
}
default:
if (node.decorators || node.modifiers) {
- var missing = createMissingNode(253, true, ts.Diagnostics.Declaration_expected);
+ // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
+ // would follow. For recovery and error reporting purposes, return an incomplete declaration.
+ var missing = createMissingNode(253 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
missing.pos = node.pos;
missing.decorators = node.decorators;
missing.modifiers = node.modifiers;
return finishNode(missing);
}
- return undefined;
+ return undefined; // TODO: GH#18217
}
}
function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
nextToken();
- return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9);
+ return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */);
}
function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
- if (token() !== 17 && canParseSemicolon()) {
+ if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) {
parseSemicolon();
return;
}
return parseFunctionBlock(flags, diagnosticMessage);
}
+ // DECLARATIONS
function parseArrayBindingElement() {
- if (token() === 26) {
- return createNode(206);
+ if (token() === 26 /* CommaToken */) {
+ return createNode(206 /* OmittedExpression */);
}
- var node = createNode(182);
- node.dotDotDotToken = parseOptionalToken(24);
+ var node = createNode(182 /* BindingElement */);
+ node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
node.name = parseIdentifierOrPattern();
node.initializer = parseInitializer();
return finishNode(node);
}
function parseObjectBindingElement() {
- var node = createNode(182);
- node.dotDotDotToken = parseOptionalToken(24);
+ var node = createNode(182 /* BindingElement */);
+ node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
var tokenIsIdentifier = isIdentifier();
var propertyName = parsePropertyName();
- if (tokenIsIdentifier && token() !== 56) {
+ if (tokenIsIdentifier && token() !== 56 /* ColonToken */) {
node.name = propertyName;
}
else {
- parseExpected(56);
+ parseExpected(56 /* ColonToken */);
node.propertyName = propertyName;
node.name = parseIdentifierOrPattern();
}
@@ -17144,39 +19850,39 @@ var ts;
return finishNode(node);
}
function parseObjectBindingPattern() {
- var node = createNode(180);
- parseExpected(17);
- node.elements = parseDelimitedList(9, parseObjectBindingElement);
- parseExpected(18);
+ var node = createNode(180 /* ObjectBindingPattern */);
+ parseExpected(17 /* OpenBraceToken */);
+ node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
+ parseExpected(18 /* CloseBraceToken */);
return finishNode(node);
}
function parseArrayBindingPattern() {
- var node = createNode(181);
- parseExpected(21);
- node.elements = parseDelimitedList(10, parseArrayBindingElement);
- parseExpected(22);
+ var node = createNode(181 /* ArrayBindingPattern */);
+ parseExpected(21 /* OpenBracketToken */);
+ node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
+ parseExpected(22 /* CloseBracketToken */);
return finishNode(node);
}
function isIdentifierOrPattern() {
- return token() === 17 || token() === 21 || isIdentifier();
+ return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier();
}
function parseIdentifierOrPattern() {
- if (token() === 21) {
+ if (token() === 21 /* OpenBracketToken */) {
return parseArrayBindingPattern();
}
- if (token() === 17) {
+ if (token() === 17 /* OpenBraceToken */) {
return parseObjectBindingPattern();
}
return parseIdentifier();
}
function parseVariableDeclarationAllowExclamation() {
- return parseVariableDeclaration(true);
+ return parseVariableDeclaration(/*allowExclamation*/ true);
}
function parseVariableDeclaration(allowExclamation) {
- var node = createNode(232);
+ var node = createNode(232 /* VariableDeclaration */);
node.name = parseIdentifierOrPattern();
- if (allowExclamation && node.name.kind === 71 &&
- token() === 51 && !scanner.hasPrecedingLineBreak()) {
+ if (allowExclamation && node.name.kind === 71 /* Identifier */ &&
+ token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
node.exclamationToken = parseTokenNode();
}
node.type = parseTypeAnnotation();
@@ -17186,84 +19892,104 @@ var ts;
return finishNode(node);
}
function parseVariableDeclarationList(inForStatementInitializer) {
- var node = createNode(233);
+ var node = createNode(233 /* VariableDeclarationList */);
switch (token()) {
- case 104:
+ case 104 /* VarKeyword */:
break;
- case 110:
- node.flags |= 1;
+ case 110 /* LetKeyword */:
+ node.flags |= 1 /* Let */;
break;
- case 76:
- node.flags |= 2;
+ case 76 /* ConstKeyword */:
+ node.flags |= 2 /* Const */;
break;
default:
ts.Debug.fail();
}
nextToken();
- if (token() === 145 && lookAhead(canFollowContextualOfKeyword)) {
+ // The user may have written the following:
+ //
+ // for (let of X) { }
+ //
+ // In this case, we want to parse an empty declaration list, and then parse 'of'
+ // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
+ // So we need to look ahead to determine if 'of' should be treated as a keyword in
+ // this context.
+ // The checker will then give an error that there is an empty declaration list.
+ if (token() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
node.declarations = createMissingList();
}
else {
var savedDisallowIn = inDisallowInContext();
setDisallowInContext(inForStatementInitializer);
- node.declarations = parseDelimitedList(8, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
+ node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
setDisallowInContext(savedDisallowIn);
}
return finishNode(node);
}
function canFollowContextualOfKeyword() {
- return nextTokenIsIdentifier() && nextToken() === 20;
+ return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */;
}
function parseVariableStatement(node) {
- node.kind = 214;
- node.declarationList = parseVariableDeclarationList(false);
+ node.kind = 214 /* VariableStatement */;
+ node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
parseSemicolon();
return finishNode(node);
}
function parseFunctionDeclaration(node) {
- node.kind = 234;
- parseExpected(89);
- node.asteriskToken = parseOptionalToken(39);
- node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier();
- var isGenerator = node.asteriskToken ? 1 : 0;
- var isAsync = ts.hasModifier(node, 256) ? 2 : 0;
- fillSignature(56, isGenerator | isAsync, node);
+ node.kind = 234 /* FunctionDeclaration */;
+ parseExpected(89 /* FunctionKeyword */);
+ node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
+ node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier();
+ var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
+ var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
+ fillSignature(56 /* ColonToken */, isGenerator | isAsync, node);
node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
return finishNode(node);
}
function parseConstructorDeclaration(node) {
- node.kind = 155;
- parseExpected(123);
- fillSignature(56, 0, node);
- node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected);
+ node.kind = 155 /* Constructor */;
+ parseExpected(123 /* ConstructorKeyword */);
+ fillSignature(56 /* ColonToken */, 0 /* None */, node);
+ node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
return finishNode(node);
}
function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
- node.kind = 154;
+ node.kind = 154 /* MethodDeclaration */;
node.asteriskToken = asteriskToken;
- var isGenerator = asteriskToken ? 1 : 0;
- var isAsync = ts.hasModifier(node, 256) ? 2 : 0;
- fillSignature(56, isGenerator | isAsync, node);
+ var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
+ var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
+ fillSignature(56 /* ColonToken */, isGenerator | isAsync, node);
node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
return finishNode(node);
}
function parsePropertyDeclaration(node) {
- node.kind = 152;
- if (!node.questionToken && token() === 51 && !scanner.hasPrecedingLineBreak()) {
+ node.kind = 152 /* PropertyDeclaration */;
+ if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
node.exclamationToken = parseTokenNode();
}
node.type = parseTypeAnnotation();
- node.initializer = ts.hasModifier(node, 32)
+ // For instance properties specifically, since they are evaluated inside the constructor,
+ // we do *not * want to parse yield expressions, so we specifically turn the yield context
+ // off. The grammar would look something like this:
+ //
+ // MemberVariableDeclaration[Yield]:
+ // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In];
+ // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield];
+ //
+ // The checker may still error in the static case to explicitly disallow the yield expression.
+ node.initializer = ts.hasModifier(node, 32 /* Static */)
? allowInAnd(parseInitializer)
- : doOutsideOfContext(4096 | 2048, parseInitializer);
+ : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer);
parseSemicolon();
return finishNode(node);
}
function parsePropertyOrMethodDeclaration(node) {
- var asteriskToken = parseOptionalToken(39);
+ var asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
node.name = parsePropertyName();
- node.questionToken = parseOptionalToken(55);
- if (asteriskToken || token() === 19 || token() === 27) {
+ // Note: this is not legal as per the grammar. But we allow it in the parser and
+ // report an error in the grammar checker.
+ node.questionToken = parseOptionalToken(55 /* QuestionToken */);
+ if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
}
return parsePropertyDeclaration(node);
@@ -17271,45 +19997,64 @@ var ts;
function parseAccessorDeclaration(node, kind) {
node.kind = kind;
node.name = parsePropertyName();
- fillSignature(56, 0, node);
- node.body = parseFunctionBlockOrSemicolon(0);
+ fillSignature(56 /* ColonToken */, 0 /* None */, node);
+ node.body = parseFunctionBlockOrSemicolon(0 /* None */);
return finishNode(node);
}
function isClassMemberStart() {
var idToken;
- if (token() === 57) {
+ if (token() === 57 /* AtToken */) {
return true;
}
+ // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
while (ts.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
+ // Example:
+ // public foo() ... // true
+ // public @dec blah ... // true; we will then report an error later
+ // export public ... // true; we will then report an error later
if (ts.isClassMemberModifier(idToken)) {
return true;
}
nextToken();
}
- if (token() === 39) {
+ if (token() === 39 /* AsteriskToken */) {
return true;
}
+ // Try to get the first property-like token following all modifiers.
+ // This can either be an identifier or the 'get' or 'set' keywords.
if (isLiteralPropertyName()) {
idToken = token();
nextToken();
}
- if (token() === 21) {
+ // Index signatures and computed properties are class members; we can parse.
+ if (token() === 21 /* OpenBracketToken */) {
return true;
}
+ // If we were able to get any potential identifier...
if (idToken !== undefined) {
- if (!ts.isKeyword(idToken) || idToken === 136 || idToken === 125) {
+ // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
+ if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) {
return true;
}
+ // If it *is* a keyword, but not an accessor, check a little farther along
+ // to see if it should actually be parsed as a class member.
switch (token()) {
- case 19:
- case 27:
- case 51:
- case 56:
- case 58:
- case 55:
+ case 19 /* OpenParenToken */: // Method declaration
+ case 27 /* LessThanToken */: // Generic Method declaration
+ case 51 /* ExclamationToken */: // Non-null assertion on property name
+ case 56 /* ColonToken */: // Type Annotation for declaration
+ case 58 /* EqualsToken */: // Initializer for declaration
+ case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
return true;
default:
+ // Covers
+ // - Semicolons (declaration termination)
+ // - Closing braces (end-of-class, must be declaration)
+ // - End-of-files (not valid, but permitted so that it gets caught later on)
+ // - Line-breaks (enabling *automatic semicolon insertion*)
return canParseSemicolon();
}
}
@@ -17320,23 +20065,32 @@ var ts;
var listPos = getNodePos();
while (true) {
var decoratorStart = getNodePos();
- if (!parseOptional(57)) {
+ if (!parseOptional(57 /* AtToken */)) {
break;
}
- var decorator = createNode(150, decoratorStart);
+ var decorator = createNode(150 /* Decorator */, decoratorStart);
decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
finishNode(decorator);
(list || (list = [])).push(decorator);
}
return list && createNodeArray(list, listPos);
}
+ /*
+ * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
+ * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
+ * and turns it into a standalone declaration), then it is better to parse it and report an error later.
+ *
+ * In such situations, 'permitInvalidConstAsModifier' should be set to true.
+ */
function parseModifiers(permitInvalidConstAsModifier) {
var list;
var listPos = getNodePos();
while (true) {
var modifierStart = scanner.getStartPos();
var modifierKind = token();
- if (token() === 76 && permitInvalidConstAsModifier) {
+ if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) {
+ // We need to ensure that any subsequent modifiers appear on the same line
+ // so that when 'const' is a standalone declaration, we don't issue an error.
if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
break;
}
@@ -17353,7 +20107,7 @@ var ts;
}
function parseModifiersForArrowFunction() {
var modifiers;
- if (token() === 120) {
+ if (token() === 120 /* AsyncKeyword */) {
var modifierStart = scanner.getStartPos();
var modifierKind = token();
nextToken();
@@ -17363,54 +20117,60 @@ var ts;
return modifiers;
}
function parseClassElement() {
- if (token() === 25) {
- var result = createNode(212);
+ if (token() === 25 /* SemicolonToken */) {
+ var result = createNode(212 /* SemicolonClassElement */);
nextToken();
return finishNode(result);
}
- var node = createNodeWithJSDoc(0);
+ var node = createNodeWithJSDoc(0 /* Unknown */);
node.decorators = parseDecorators();
- node.modifiers = parseModifiers(true);
- if (parseContextualModifier(125)) {
- return parseAccessorDeclaration(node, 156);
+ node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
+ if (parseContextualModifier(125 /* GetKeyword */)) {
+ return parseAccessorDeclaration(node, 156 /* GetAccessor */);
}
- if (parseContextualModifier(136)) {
- return parseAccessorDeclaration(node, 157);
+ if (parseContextualModifier(136 /* SetKeyword */)) {
+ return parseAccessorDeclaration(node, 157 /* SetAccessor */);
}
- if (token() === 123) {
+ if (token() === 123 /* ConstructorKeyword */) {
return parseConstructorDeclaration(node);
}
if (isIndexSignature()) {
return parseIndexSignatureDeclaration(node);
}
+ // It is very important that we check this *after* checking indexers because
+ // the [ token can start an index signature or a computed property name
if (ts.tokenIsIdentifierOrKeyword(token()) ||
- token() === 9 ||
- token() === 8 ||
- token() === 39 ||
- token() === 21) {
+ token() === 9 /* StringLiteral */ ||
+ token() === 8 /* NumericLiteral */ ||
+ token() === 39 /* AsteriskToken */ ||
+ token() === 21 /* OpenBracketToken */) {
return parsePropertyOrMethodDeclaration(node);
}
if (node.decorators || node.modifiers) {
- node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected);
+ // treat this as a property declaration with a missing name.
+ node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
return parsePropertyDeclaration(node);
}
+ // 'isClassMemberStart' should have hinted not to attempt parsing.
return ts.Debug.fail("Should not have attempted to parse class member declaration.");
}
function parseClassExpression() {
- return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 205);
+ return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 205 /* ClassExpression */);
}
function parseClassDeclaration(node) {
- return parseClassDeclarationOrExpression(node, 235);
+ return parseClassDeclarationOrExpression(node, 235 /* ClassDeclaration */);
}
function parseClassDeclarationOrExpression(node, kind) {
node.kind = kind;
- parseExpected(75);
+ parseExpected(75 /* ClassKeyword */);
node.name = parseNameOfClassDeclarationOrExpression();
node.typeParameters = parseTypeParameters();
node.heritageClauses = parseHeritageClauses();
- if (parseExpected(17)) {
+ if (parseExpected(17 /* OpenBraceToken */)) {
+ // ClassTail[Yield,Await] : (Modified) See 14.5
+ // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
node.members = parseClassMembers();
- parseExpected(18);
+ parseExpected(18 /* CloseBraceToken */);
}
else {
node.members = createMissingList();
@@ -17418,48 +20178,55 @@ var ts;
return finishNode(node);
}
function parseNameOfClassDeclarationOrExpression() {
+ // 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
return isIdentifier() && !isImplementsClause()
? parseIdentifier()
: undefined;
}
function isImplementsClause() {
- return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword);
+ return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
}
function parseHeritageClauses() {
+ // ClassTail[Yield,Await] : (Modified) See 14.5
+ // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
if (isHeritageClause()) {
- return parseList(21, parseHeritageClause);
+ return parseList(21 /* HeritageClauses */, parseHeritageClause);
}
return undefined;
}
function parseHeritageClause() {
var tok = token();
- ts.Debug.assert(tok === 85 || tok === 108);
- var node = createNode(268);
+ ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this.
+ var node = createNode(268 /* HeritageClause */);
node.token = tok;
nextToken();
- node.types = parseDelimitedList(7, parseExpressionWithTypeArguments);
+ node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
return finishNode(node);
}
function parseExpressionWithTypeArguments() {
- var node = createNode(207);
+ var node = createNode(207 /* ExpressionWithTypeArguments */);
node.expression = parseLeftHandSideExpressionOrHigher();
node.typeArguments = tryParseTypeArguments();
return finishNode(node);
}
function tryParseTypeArguments() {
- return token() === 27
- ? parseBracketedList(19, parseType, 27, 29)
+ return token() === 27 /* LessThanToken */
+ ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */)
: undefined;
}
function isHeritageClause() {
- return token() === 85 || token() === 108;
+ return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */;
}
function parseClassMembers() {
- return parseList(5, parseClassElement);
+ return parseList(5 /* ClassMembers */, parseClassElement);
}
function parseInterfaceDeclaration(node) {
- node.kind = 236;
- parseExpected(109);
+ node.kind = 236 /* InterfaceDeclaration */;
+ parseExpected(109 /* InterfaceKeyword */);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
node.heritageClauses = parseHeritageClauses();
@@ -17467,28 +20234,32 @@ var ts;
return finishNode(node);
}
function parseTypeAliasDeclaration(node) {
- node.kind = 237;
- parseExpected(139);
+ node.kind = 237 /* TypeAliasDeclaration */;
+ parseExpected(139 /* TypeKeyword */);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
- parseExpected(58);
+ parseExpected(58 /* EqualsToken */);
node.type = parseType();
parseSemicolon();
return finishNode(node);
}
+ // In an ambient declaration, the grammar only allows integer literals as initializers.
+ // In a non-ambient declaration, the grammar allows uninitialized members only in a
+ // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
+ // or any time an integer literal initializer is encountered.
function parseEnumMember() {
- var node = createNodeWithJSDoc(273);
+ var node = createNodeWithJSDoc(273 /* EnumMember */);
node.name = parsePropertyName();
node.initializer = allowInAnd(parseInitializer);
return finishNode(node);
}
function parseEnumDeclaration(node) {
- node.kind = 238;
- parseExpected(83);
+ node.kind = 238 /* EnumDeclaration */;
+ parseExpected(83 /* EnumKeyword */);
node.name = parseIdentifier();
- if (parseExpected(17)) {
- node.members = parseDelimitedList(6, parseEnumMember);
- parseExpected(18);
+ if (parseExpected(17 /* OpenBraceToken */)) {
+ node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember);
+ parseExpected(18 /* CloseBraceToken */);
}
else {
node.members = createMissingList();
@@ -17496,10 +20267,10 @@ var ts;
return finishNode(node);
}
function parseModuleBlock() {
- var node = createNode(240);
- if (parseExpected(17)) {
- node.statements = parseList(1, parseStatement);
- parseExpected(18);
+ var node = createNode(240 /* ModuleBlock */);
+ if (parseExpected(17 /* OpenBraceToken */)) {
+ node.statements = parseList(1 /* BlockStatements */, parseStatement);
+ parseExpected(18 /* CloseBraceToken */);
}
else {
node.statements = createMissingList();
@@ -17507,26 +20278,29 @@ var ts;
return finishNode(node);
}
function parseModuleOrNamespaceDeclaration(node, flags) {
- node.kind = 239;
- var namespaceFlag = flags & 16;
+ node.kind = 239 /* ModuleDeclaration */;
+ // If we are parsing a dotted namespace name, we want to
+ // propagate the 'Namespace' flag across the names if set.
+ var namespaceFlag = flags & 16 /* Namespace */;
node.flags |= flags;
node.name = parseIdentifier();
- node.body = parseOptional(23)
- ? parseModuleOrNamespaceDeclaration(createNode(0), 4 | namespaceFlag)
+ node.body = parseOptional(23 /* DotToken */)
+ ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
: parseModuleBlock();
return finishNode(node);
}
function parseAmbientExternalModuleDeclaration(node) {
- node.kind = 239;
- if (token() === 144) {
+ node.kind = 239 /* ModuleDeclaration */;
+ if (token() === 144 /* GlobalKeyword */) {
+ // parse 'global' as name of global scope augmentation
node.name = parseIdentifier();
- node.flags |= 512;
+ node.flags |= 512 /* GlobalAugmentation */;
}
else {
node.name = parseLiteralNode();
node.name.text = internIdentifier(node.name.text);
}
- if (token() === 17) {
+ if (token() === 17 /* OpenBraceToken */) {
node.body = parseModuleBlock();
}
else {
@@ -17536,128 +20310,161 @@ var ts;
}
function parseModuleDeclaration(node) {
var flags = 0;
- if (token() === 144) {
+ if (token() === 144 /* GlobalKeyword */) {
+ // global augmentation
return parseAmbientExternalModuleDeclaration(node);
}
- else if (parseOptional(130)) {
- flags |= 16;
+ else if (parseOptional(130 /* NamespaceKeyword */)) {
+ flags |= 16 /* Namespace */;
}
else {
- parseExpected(129);
- if (token() === 9) {
+ parseExpected(129 /* ModuleKeyword */);
+ if (token() === 9 /* StringLiteral */) {
return parseAmbientExternalModuleDeclaration(node);
}
}
return parseModuleOrNamespaceDeclaration(node, flags);
}
function isExternalModuleReference() {
- return token() === 133 &&
+ return token() === 133 /* RequireKeyword */ &&
lookAhead(nextTokenIsOpenParen);
}
function nextTokenIsOpenParen() {
- return nextToken() === 19;
+ return nextToken() === 19 /* OpenParenToken */;
}
function nextTokenIsSlash() {
- return nextToken() === 41;
+ return nextToken() === 41 /* SlashToken */;
}
function parseNamespaceExportDeclaration(node) {
- node.kind = 242;
- parseExpected(118);
- parseExpected(130);
+ node.kind = 242 /* NamespaceExportDeclaration */;
+ parseExpected(118 /* AsKeyword */);
+ parseExpected(130 /* NamespaceKeyword */);
node.name = parseIdentifier();
parseSemicolon();
return finishNode(node);
}
function parseImportDeclarationOrImportEqualsDeclaration(node) {
- parseExpected(91);
+ parseExpected(91 /* ImportKeyword */);
var afterImportPos = scanner.getStartPos();
var identifier;
if (isIdentifier()) {
identifier = parseIdentifier();
- if (token() !== 26 && token() !== 143) {
+ if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) {
return parseImportEqualsDeclaration(node, identifier);
}
}
- node.kind = 244;
- if (identifier ||
- token() === 39 ||
- token() === 17) {
+ // Import statement
+ node.kind = 244 /* ImportDeclaration */;
+ // ImportDeclaration:
+ // import ImportClause from ModuleSpecifier ;
+ // import ModuleSpecifier;
+ if (identifier || // import id
+ token() === 39 /* AsteriskToken */ || // import *
+ token() === 17 /* OpenBraceToken */) { // import {
node.importClause = parseImportClause(identifier, afterImportPos);
- parseExpected(143);
+ parseExpected(143 /* FromKeyword */);
}
node.moduleSpecifier = parseModuleSpecifier();
parseSemicolon();
return finishNode(node);
}
function parseImportEqualsDeclaration(node, identifier) {
- node.kind = 243;
+ node.kind = 243 /* ImportEqualsDeclaration */;
node.name = identifier;
- parseExpected(58);
+ parseExpected(58 /* EqualsToken */);
node.moduleReference = parseModuleReference();
parseSemicolon();
return finishNode(node);
}
function parseImportClause(identifier, fullStart) {
- var importClause = createNode(245, fullStart);
+ // ImportClause:
+ // ImportedDefaultBinding
+ // NameSpaceImport
+ // NamedImports
+ // ImportedDefaultBinding, NameSpaceImport
+ // ImportedDefaultBinding, NamedImports
+ var importClause = createNode(245 /* ImportClause */, fullStart);
if (identifier) {
+ // ImportedDefaultBinding:
+ // ImportedBinding
importClause.name = identifier;
}
+ // If there was no default import or if there is comma token after default import
+ // parse namespace or named imports
if (!importClause.name ||
- parseOptional(26)) {
- importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(247);
+ parseOptional(26 /* CommaToken */)) {
+ importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(247 /* NamedImports */);
}
return finishNode(importClause);
}
function parseModuleReference() {
return isExternalModuleReference()
? parseExternalModuleReference()
- : parseEntityName(false);
+ : parseEntityName(/*allowReservedWords*/ false);
}
function parseExternalModuleReference() {
- var node = createNode(254);
- parseExpected(133);
- parseExpected(19);
+ var node = createNode(254 /* ExternalModuleReference */);
+ parseExpected(133 /* RequireKeyword */);
+ parseExpected(19 /* OpenParenToken */);
node.expression = parseModuleSpecifier();
- parseExpected(20);
+ parseExpected(20 /* CloseParenToken */);
return finishNode(node);
}
function parseModuleSpecifier() {
- if (token() === 9) {
+ if (token() === 9 /* StringLiteral */) {
var result = parseLiteralNode();
result.text = 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();
}
}
function parseNamespaceImport() {
- var namespaceImport = createNode(246);
- parseExpected(39);
- parseExpected(118);
+ // NameSpaceImport:
+ // * as ImportedBinding
+ var namespaceImport = createNode(246 /* NamespaceImport */);
+ parseExpected(39 /* AsteriskToken */);
+ parseExpected(118 /* AsKeyword */);
namespaceImport.name = parseIdentifier();
return finishNode(namespaceImport);
}
function parseNamedImportsOrExports(kind) {
var node = createNode(kind);
- node.elements = parseBracketedList(22, kind === 247 ? parseImportSpecifier : parseExportSpecifier, 17, 18);
+ // NamedImports:
+ // { }
+ // { ImportsList }
+ // { ImportsList, }
+ // ImportsList:
+ // ImportSpecifier
+ // ImportsList, ImportSpecifier
+ node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 247 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */);
return finishNode(node);
}
function parseExportSpecifier() {
- return parseImportOrExportSpecifier(252);
+ return parseImportOrExportSpecifier(252 /* ExportSpecifier */);
}
function parseImportSpecifier() {
- return parseImportOrExportSpecifier(248);
+ return parseImportOrExportSpecifier(248 /* ImportSpecifier */);
}
function parseImportOrExportSpecifier(kind) {
var node = createNode(kind);
+ // ImportSpecifier:
+ // BindingIdentifier
+ // IdentifierName as BindingIdentifier
+ // ExportSpecifier:
+ // IdentifierName
+ // IdentifierName as IdentifierName
var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
var checkIdentifierStart = scanner.getTokenPos();
var checkIdentifierEnd = scanner.getTextPos();
var identifierName = parseIdentifierName();
- if (token() === 118) {
+ if (token() === 118 /* AsKeyword */) {
node.propertyName = identifierName;
- parseExpected(118);
+ parseExpected(118 /* AsKeyword */);
checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
checkIdentifierStart = scanner.getTokenPos();
checkIdentifierEnd = scanner.getTextPos();
@@ -17666,21 +20473,24 @@ var ts;
else {
node.name = identifierName;
}
- if (kind === 248 && checkIdentifierIsKeyword) {
+ if (kind === 248 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
}
return finishNode(node);
}
function parseExportDeclaration(node) {
- node.kind = 250;
- if (parseOptional(39)) {
- parseExpected(143);
+ node.kind = 250 /* ExportDeclaration */;
+ if (parseOptional(39 /* AsteriskToken */)) {
+ parseExpected(143 /* FromKeyword */);
node.moduleSpecifier = parseModuleSpecifier();
}
else {
- node.exportClause = parseNamedImportsOrExports(251);
- if (token() === 143 || (token() === 9 && !scanner.hasPrecedingLineBreak())) {
- parseExpected(143);
+ node.exportClause = parseNamedImportsOrExports(251 /* NamedExports */);
+ // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
+ // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
+ // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
+ if (token() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
+ parseExpected(143 /* FromKeyword */);
node.moduleSpecifier = parseModuleSpecifier();
}
}
@@ -17688,33 +20498,35 @@ var ts;
return finishNode(node);
}
function parseExportAssignment(node) {
- node.kind = 249;
- if (parseOptional(58)) {
+ node.kind = 249 /* ExportAssignment */;
+ if (parseOptional(58 /* EqualsToken */)) {
node.isExportEquals = true;
}
else {
- parseExpected(79);
+ parseExpected(79 /* DefaultKeyword */);
}
node.expression = parseAssignmentExpressionOrHigher();
parseSemicolon();
return finishNode(node);
}
function setExternalModuleIndicator(sourceFile) {
+ // Try to use the first top-level import/export when available, then
+ // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
sourceFile.externalModuleIndicator =
ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
getImportMetaIfNecessary(sourceFile);
}
function isAnExternalModuleIndicatorNode(node) {
- return ts.hasModifier(node, 1)
- || node.kind === 243 && node.moduleReference.kind === 254
- || node.kind === 244
- || node.kind === 249
- || node.kind === 250
+ return ts.hasModifier(node, 1 /* Export */)
+ || node.kind === 243 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 254 /* ExternalModuleReference */
+ || node.kind === 244 /* ImportDeclaration */
+ || node.kind === 249 /* ExportAssignment */
+ || node.kind === 250 /* ExportDeclaration */
? node
: undefined;
}
function getImportMetaIfNecessary(sourceFile) {
- return sourceFile.flags & 1048576 ?
+ return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ?
walkTreeForExternalModuleIndicators(sourceFile) :
undefined;
}
@@ -17722,7 +20534,7 @@ var ts;
return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
}
function isImportMeta(node) {
- return ts.isMetaProperty(node) && node.keywordToken === 91 && node.name.escapedText === "meta";
+ return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta";
}
var ParsingContext;
(function (ParsingContext) {
@@ -17749,7 +20561,7 @@ var ts;
ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes";
ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses";
ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers";
- ParsingContext[ParsingContext["Count"] = 23] = "Count";
+ ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts
})(ParsingContext || (ParsingContext = {}));
var Tristate;
(function (Tristate) {
@@ -17760,8 +20572,8 @@ var ts;
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6, undefined, 1);
- sourceFile = createSourceFile("file.js", 6, 1, false);
+ initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -17770,20 +20582,21 @@ var ts;
return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
}
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
+ // Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(278, scanner.getTokenPos());
- var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17);
- result.type = doInsideOfContext(2097152, parseJSDocType);
+ var result = createNode(278 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */);
+ result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
- parseExpected(18);
+ parseExpected(18 /* CloseBraceToken */);
}
fixupParentReferences(result);
return finishNode(result);
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6, undefined, 1);
- sourceFile = { languageVariant: 0, text: content };
+ initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
clearState();
@@ -17799,7 +20612,7 @@ var ts;
if (comment) {
comment.parent = parent;
}
- if (contextFlags & 65536) {
+ if (contextFlags & 65536 /* JavaScriptFile */) {
if (!sourceFile.jsDocDiagnostics) {
sourceFile.jsDocDiagnostics = [];
}
@@ -17836,12 +20649,17 @@ var ts;
var tagsEnd;
var comments = [];
var result;
+ // Check for /** (JSDoc opening part)
if (!isJSDocLikeText(content, start)) {
return result;
}
+ // + 3 for leading /**, - 5 in total for /** */
scanner.scanRange(start + 3, length - 5, function () {
- var state = 1;
+ // Initially we can parse out a tag. We also have seen a starting asterisk.
+ // This is so that /** * @type */ doesn't parse.
+ var state = 1 /* SawAsterisk */;
var margin;
+ // + 4 for leading '/** '
var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
function pushComment(text) {
if (!margin) {
@@ -17851,19 +20669,22 @@ var ts;
indent += text.length;
}
nextJSDocToken();
- while (parseOptionalJsdoc(5))
+ while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
;
- if (parseOptionalJsdoc(4)) {
- state = 0;
+ if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
+ state = 0 /* BeginningOfLine */;
indent = 0;
}
loop: while (true) {
switch (token()) {
- case 57:
- if (state === 0 || state === 1) {
+ case 57 /* AtToken */:
+ if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
removeTrailingNewlines(comments);
addTag(parseTag(indent));
- state = 0;
+ // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
+ // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
+ // for malformed examples like `/** @param {string} x @returns {number} the length */`
+ state = 0 /* BeginningOfLine */;
margin = undefined;
indent++;
}
@@ -17871,29 +20692,35 @@ var ts;
pushComment(scanner.getTokenText());
}
break;
- case 4:
+ case 4 /* NewLineTrivia */:
comments.push(scanner.getTokenText());
- state = 0;
+ state = 0 /* BeginningOfLine */;
indent = 0;
break;
- case 39:
+ case 39 /* AsteriskToken */:
var asterisk = scanner.getTokenText();
- if (state === 1 || state === 2) {
- state = 2;
+ if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
+ // If we've already seen an asterisk, then we can no longer parse a tag on this line
+ state = 2 /* SavingComments */;
pushComment(asterisk);
}
else {
- state = 1;
+ // Ignore the first asterisk on a line
+ state = 1 /* SawAsterisk */;
indent += asterisk.length;
}
break;
- case 71:
+ case 71 /* Identifier */:
+ // Anything else is doc comment text. We just save it. Because it
+ // wasn't a tag, we can no longer parse a tag on this line until we hit the next
+ // line break.
pushComment(scanner.getTokenText());
- state = 2;
+ state = 2 /* SavingComments */;
break;
- case 5:
+ case 5 /* WhitespaceTrivia */:
+ // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
var whitespace = scanner.getTokenText();
- if (state === 2) {
+ if (state === 2 /* SavingComments */) {
comments.push(whitespace);
}
else if (margin !== undefined && indent + whitespace.length > margin) {
@@ -17901,10 +20728,11 @@ var ts;
}
indent += whitespace.length;
break;
- case 1:
+ case 1 /* EndOfFileToken */:
break loop;
default:
- state = 2;
+ // anything other than whitespace or asterisk at the beginning of the line starts the comment text
+ state = 2 /* SavingComments */;
pushComment(scanner.getTokenText());
break;
}
@@ -17926,35 +20754,36 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(286, start);
+ var result = createNode(286 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
}
function isNextNonwhitespaceTokenEndOfFile() {
+ // We must use infinite lookahead, as there could be any number of newlines :(
while (true) {
nextJSDocToken();
- if (token() === 1) {
+ if (token() === 1 /* EndOfFileToken */) {
return true;
}
- if (!(token() === 5 || token() === 4)) {
+ if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
return false;
}
}
}
function skipWhitespace() {
- if (token() === 5 || token() === 4) {
+ if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
- return;
+ return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
}
}
- while (token() === 5 || token() === 4) {
+ while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
nextJSDocToken();
}
}
function parseTag(indent) {
- ts.Debug.assert(token() === 57);
- var atToken = createNode(57, scanner.getTokenPos());
+ ts.Debug.assert(token() === 57 /* AtToken */);
+ var atToken = createNode(57 /* AtToken */, scanner.getTokenPos());
atToken.end = scanner.getTextPos();
nextJSDocToken();
var tagName = parseJSDocIdentifierName();
@@ -17975,7 +20804,7 @@ var ts;
case "arg":
case "argument":
case "param":
- return parseParameterOrPropertyTag(atToken, tagName, 2, indent);
+ return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent);
case "return":
case "returns":
tag = parseReturnTag(atToken, tagName);
@@ -17997,13 +20826,14 @@ var ts;
break;
}
if (!tag.comment) {
+ // some tags, like typedef and callback, have already parsed their comments earlier
tag.comment = parseTagComments(indent + tag.end - tag.pos);
}
return tag;
}
function parseTagComments(indent) {
var comments = [];
- var state = 0;
+ var state = 0 /* BeginningOfLine */;
var margin;
function pushComment(text) {
if (!margin) {
@@ -18015,37 +20845,43 @@ var ts;
var tok = token();
loop: while (true) {
switch (tok) {
- case 4:
- if (state >= 1) {
- state = 0;
+ case 4 /* NewLineTrivia */:
+ if (state >= 1 /* SawAsterisk */) {
+ state = 0 /* BeginningOfLine */;
comments.push(scanner.getTokenText());
}
indent = 0;
break;
- case 57:
+ case 57 /* AtToken */:
scanner.setTextPos(scanner.getTextPos() - 1);
- case 1:
+ // falls through
+ case 1 /* EndOfFileToken */:
+ // Done
break loop;
- case 5:
- if (state === 2) {
+ case 5 /* WhitespaceTrivia */:
+ if (state === 2 /* SavingComments */) {
pushComment(scanner.getTokenText());
}
else {
var whitespace = scanner.getTokenText();
+ // if the whitespace crosses the margin, take only the whitespace that passes the margin
if (margin !== undefined && indent + whitespace.length > margin) {
comments.push(whitespace.slice(margin - indent - 1));
}
indent += whitespace.length;
}
break;
- case 39:
- if (state === 0) {
- state = 1;
+ case 39 /* AsteriskToken */:
+ if (state === 0 /* BeginningOfLine */) {
+ // leading asterisks start recording on the *next* (non-whitespace) token
+ state = 1 /* SawAsterisk */;
indent += 1;
break;
}
+ // record the * as a comment
+ // falls through
default:
- state = 2;
+ state = 2 /* SavingComments */; // leading identifiers start recording as well
pushComment(scanner.getTokenText());
break;
}
@@ -18056,7 +20892,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(289, atToken.pos);
+ var result = createNode(289 /* JSDocTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
@@ -18076,28 +20912,31 @@ var ts;
}
function tryParseTypeExpression() {
skipWhitespace();
- return token() === 17 ? parseJSDocTypeExpression() : undefined;
+ return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
}
function parseBracketNameInPropertyAndParamTag() {
- if (token() === 13) {
- return { name: createIdentifier(true), isBracketed: false };
+ if (token() === 13 /* NoSubstitutionTemplateLiteral */) {
+ // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
+ return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false };
}
- var isBracketed = parseOptional(21);
+ // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
+ var isBracketed = parseOptional(21 /* OpenBracketToken */);
var name = parseJSDocEntityName();
if (isBracketed) {
skipWhitespace();
- if (parseOptionalToken(58)) {
+ // May have an optional default, e.g. '[foo = 42]'
+ if (parseOptionalToken(58 /* EqualsToken */)) {
parseExpression();
}
- parseExpected(22);
+ parseExpected(22 /* CloseBracketToken */);
}
return { name: name, isBracketed: isBracketed };
}
function isObjectOrObjectArrayTypeReference(node) {
switch (node.kind) {
- case 135:
+ case 135 /* ObjectKeyword */:
return true;
- case 167:
+ case 167 /* ArrayType */:
return isObjectOrObjectArrayTypeReference(node.elementType);
default:
return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object";
@@ -18112,13 +20951,13 @@ var ts;
if (isNameFirst) {
typeExpression = tryParseTypeExpression();
}
- var result = target === 1 ?
- createNode(299, atToken.pos) :
- createNode(293, atToken.pos);
+ var result = target === 1 /* Property */ ?
+ createNode(299 /* JSDocPropertyTag */, atToken.pos) :
+ createNode(293 /* JSDocParameterTag */, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
- var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target);
+ var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target);
if (nestedTypeLiteral) {
typeExpression = nestedTypeLiteral;
isNameFirst = true;
@@ -18134,20 +20973,20 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(278, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(278 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) {
- if (child.kind === 293 || child.kind === 299) {
+ if (child.kind === 293 /* JSDocParameterTag */ || child.kind === 299 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(287, start_2);
+ jsdocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
- if (typeExpression.type.kind === 167) {
+ if (typeExpression.type.kind === 167 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
}
typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
@@ -18156,47 +20995,47 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 294; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(294, atToken.pos);
+ var result = createNode(294 /* JSDocReturnTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 296; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 296 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(296, atToken.pos);
+ var result = createNode(296 /* JSDocTypeTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
- result.typeExpression = parseJSDocTypeExpression(true);
+ result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(290, atToken.pos);
+ var result = createNode(290 /* JSDocAugmentsTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
}
function parseExpressionWithTypeArgumentsForAugments() {
- var usedBrace = parseOptional(17);
- var node = createNode(207);
+ var usedBrace = parseOptional(17 /* OpenBraceToken */);
+ var node = createNode(207 /* ExpressionWithTypeArguments */);
node.expression = parsePropertyAccessEntityNameExpression();
node.typeArguments = tryParseTypeArguments();
var res = finishNode(node);
if (usedBrace) {
- parseExpected(18);
+ parseExpected(18 /* CloseBraceToken */);
}
return res;
}
function parsePropertyAccessEntityNameExpression() {
var node = parseJSDocIdentifierName();
- while (parseOptional(23)) {
- var prop = createNode(185, node.pos);
+ while (parseOptional(23 /* DotToken */)) {
+ var prop = createNode(185 /* PropertyAccessExpression */, node.pos);
prop.expression = node;
prop.name = parseJSDocIdentifierName();
node = finishNode(prop);
@@ -18204,23 +21043,23 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(291, atToken.pos);
+ var tag = createNode(291 /* JSDocClassTag */, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(atToken, tagName) {
- var tag = createNode(295, atToken.pos);
+ var tag = createNode(295 /* JSDocThisTag */, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
- tag.typeExpression = parseJSDocTypeExpression(true);
+ tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseTypedefTag(atToken, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(298, atToken.pos);
+ var typedefTag = createNode(298 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
@@ -18236,9 +21075,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(287, start_3);
+ jsdocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, start_3);
}
- if (child.kind === 296) {
+ if (child.kind === 296 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -18251,7 +21090,7 @@ var ts;
}
}
if (jsdocTypeLiteral) {
- if (typeExpression && typeExpression.type.kind === 167) {
+ if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
}
typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
@@ -18260,6 +21099,7 @@ var ts;
end = typedefTag.typeExpression.end;
}
}
+ // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
}
function parseJSDocTypeNameWithNamespace(nested) {
@@ -18268,13 +21108,13 @@ var ts;
return undefined;
}
var typeNameOrNamespaceName = parseJSDocIdentifierName();
- if (parseOptional(23)) {
- var jsDocNamespaceNode = createNode(239, pos);
+ if (parseOptional(23 /* DotToken */)) {
+ var jsDocNamespaceNode = createNode(239 /* ModuleDeclaration */, pos);
if (nested) {
- jsDocNamespaceNode.flags |= 4;
+ jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
}
jsDocNamespaceNode.name = typeNameOrNamespaceName;
- jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(true);
+ jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
return finishNode(jsDocNamespaceNode);
}
if (nested) {
@@ -18283,7 +21123,7 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(atToken, tagName, indent) {
- var callbackTag = createNode(292, atToken.pos);
+ var callbackTag = createNode(292 /* JSDocCallbackTag */, atToken.pos);
callbackTag.atToken = atToken;
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
@@ -18292,15 +21132,15 @@ var ts;
callbackTag.comment = parseTagComments(indent);
var child;
var start = scanner.getStartPos();
- var jsdocSignature = createNode(288, start);
+ var jsdocSignature = createNode(288 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
- while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) {
+ while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
}
var returnTag = tryParse(function () {
- if (parseOptionalJsdoc(57)) {
+ if (parseOptionalJsdoc(57 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 294) {
+ if (tag && tag.kind === 294 /* JSDocReturnTag */) {
return tag;
}
}
@@ -18335,46 +21175,46 @@ var ts;
return a.escapedText === b.escapedText;
}
function parseChildPropertyTag() {
- return parseChildParameterOrPropertyTag(1);
+ return parseChildParameterOrPropertyTag(1 /* Property */);
}
function parseChildParameterOrPropertyTag(target, name) {
var canParseTag = true;
var seenAsterisk = false;
while (true) {
switch (nextJSDocToken()) {
- case 57:
+ case 57 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 293 &&
- target !== 4 &&
- (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
+ if (child && child.kind === 293 /* JSDocParameterTag */ &&
+ target !== 4 /* CallbackParameter */ &&
+ (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { // TODO: GH#18217
return false;
}
return child;
}
seenAsterisk = false;
break;
- case 4:
+ case 4 /* NewLineTrivia */:
canParseTag = true;
seenAsterisk = false;
break;
- case 39:
+ case 39 /* AsteriskToken */:
if (seenAsterisk) {
canParseTag = false;
}
seenAsterisk = true;
break;
- case 71:
+ case 71 /* Identifier */:
canParseTag = false;
break;
- case 1:
+ case 1 /* EndOfFileToken */:
return false;
}
}
}
function tryParseChildTag(target) {
- ts.Debug.assert(token() === 57);
- var atToken = createNode(57);
+ ts.Debug.assert(token() === 57 /* AtToken */);
+ var atToken = createNode(57 /* AtToken */);
atToken.end = scanner.getTextPos();
nextJSDocToken();
var tagName = parseJSDocIdentifierName();
@@ -18382,15 +21222,15 @@ var ts;
var t;
switch (tagName.escapedText) {
case "type":
- return target === 1 && parseTypeTag(atToken, tagName);
+ return target === 1 /* Property */ && parseTypeTag(atToken, tagName);
case "prop":
case "property":
- t = 1;
+ t = 1 /* Property */;
break;
case "arg":
case "argument":
case "param":
- t = 2 | 4;
+ t = 2 /* Parameter */ | 4 /* CallbackParameter */;
break;
default:
return false;
@@ -18398,29 +21238,30 @@ var ts;
if (!(target & t)) {
return false;
}
- var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined);
+ var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined);
tag.comment = parseTagComments(tag.end - tag.pos);
return tag;
}
function parseTemplateTag(atToken, tagName) {
+ // the template tag looks like '@template {Constraint} T,U,V'
var constraint;
- if (token() === 17) {
+ if (token() === 17 /* OpenBraceToken */) {
constraint = parseJSDocTypeExpression();
}
var typeParameters = [];
var typeParametersPos = getNodePos();
do {
skipWhitespace();
- var typeParameter = createNode(148);
+ var typeParameter = createNode(148 /* TypeParameter */);
typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
skipWhitespace();
finishNode(typeParameter);
typeParameters.push(typeParameter);
- } while (parseOptionalJsdoc(26));
+ } while (parseOptionalJsdoc(26 /* CommaToken */));
if (constraint) {
ts.first(typeParameters).constraint = constraint.type;
}
- var result = createNode(297, atToken.pos);
+ var result = createNode(297 /* JSDocTemplateTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -18439,13 +21280,16 @@ var ts;
}
function parseJSDocEntityName() {
var entity = parseJSDocIdentifierName();
- if (parseOptional(21)) {
- parseExpected(22);
+ if (parseOptional(21 /* OpenBracketToken */)) {
+ parseExpected(22 /* CloseBracketToken */);
+ // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
+ // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
+ // but it's not worth it to enforce that restriction.
}
- while (parseOptional(23)) {
+ while (parseOptional(23 /* DotToken */)) {
var name = parseJSDocIdentifierName();
- if (parseOptional(21)) {
- parseExpected(22);
+ if (parseOptional(21 /* OpenBracketToken */)) {
+ parseExpected(22 /* CloseBracketToken */);
}
entity = createQualifiedName(entity, name);
}
@@ -18453,11 +21297,11 @@ var ts;
}
function parseJSDocIdentifierName(message) {
if (!ts.tokenIsIdentifierOrKeyword(token())) {
- return createMissingNode(71, !message, message || ts.Diagnostics.Identifier_expected);
+ return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
}
var pos = scanner.getTokenPos();
var end = scanner.getTextPos();
- var result = createNode(71, pos);
+ var result = createNode(71 /* Identifier */, pos);
result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText());
finishNode(result, end);
nextJSDocToken();
@@ -18470,27 +21314,72 @@ var ts;
var IncrementalParser;
(function (IncrementalParser) {
function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
- aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2);
+ aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
+ // if the text didn't change, then we can just return our current source file as-is.
return sourceFile;
}
if (sourceFile.statements.length === 0) {
- return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind);
+ // 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, /*setParentNodes*/ true, sourceFile.scriptKind);
}
+ // Make sure we're not trying to incrementally update a source file more than once. Once
+ // we do an update the original source file is considered unusable from that point onwards.
+ //
+ // This is because we do incremental parsing in-place. i.e. we take nodes from the old
+ // tree and give them new positions and parents. From that point on, trusting the old
+ // tree at all is not possible as far too much of it may violate invariants.
var incrementalSourceFile = sourceFile;
ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
incrementalSourceFile.hasBeenIncrementallyParsed = true;
var oldText = sourceFile.text;
var syntaxCursor = createSyntaxCursor(sourceFile);
+ // Make the actual change larger so that we know to reparse anything whose lookahead
+ // might have intersected the change.
var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
+ // Ensure that extending the affected range only moved the start of the change range
+ // earlier in the file.
ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
+ // The is the amount the nodes after the edit range need to be adjusted. It can be
+ // positive (if the edit added characters), negative (if the edit deleted characters)
+ // or zero (if this was a pure overwrite with nothing added/removed).
var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
+ // If we added or removed characters during the edit, then we need to go and adjust all
+ // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they
+ // may move backward (if we deleted chars).
+ //
+ // Doing this helps us out in two ways. First, it means that any nodes/tokens we want
+ // to reuse are already at the appropriate position in the new text. That way when we
+ // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes
+ // it very easy to determine if we can reuse a node. If the node's position is at where
+ // we are in the text, then we can reuse it. Otherwise we can't. If the node's position
+ // is ahead of us, then we'll need to rescan tokens. If the node's position is behind
+ // us, then we'll need to skip it or crumble it as appropriate
+ //
+ // We will also adjust the positions of nodes that intersect the change range as well.
+ // By doing this, we ensure that all the positions in the old tree are consistent, not
+ // just the positions of nodes entirely before/after the change range. By being
+ // consistent, we can then easily map from positions to nodes in the old tree easily.
+ //
+ // Also, mark any syntax elements that intersect the changed span. We know, up front,
+ // that we cannot reuse these elements.
updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
- var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind);
+ // Now that we've set up our internal incremental state just proceed and parse the
+ // source file in the normal fashion. When possible the parser will retrieve and
+ // reuse nodes from the old tree.
+ //
+ // Note: passing in 'true' for setNodeParents is very important. When incrementally
+ // parsing, we will be reusing nodes from the old tree, and placing it into new
+ // parents. If we don't set the parents now, we'll end up with an observably
+ // 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.
+ var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
return result;
}
IncrementalParser.updateSourceFile = updateSourceFile;
@@ -18507,6 +21396,8 @@ var ts;
if (aggressiveChecks && shouldCheckNode(node)) {
text = oldText.substring(node.pos, node.end);
}
+ // Ditch any existing LS children we may have created. This way we can avoid
+ // moving them forward.
if (node._children) {
node._children = undefined;
}
@@ -18536,9 +21427,9 @@ var ts;
}
function shouldCheckNode(node) {
switch (node.kind) {
- case 9:
- case 8:
- case 71:
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 71 /* Identifier */:
return true;
}
return false;
@@ -18547,11 +21438,63 @@ var ts;
ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
ts.Debug.assert(element.pos <= element.end);
+ // We have an element that intersects the change range in some way. It may have its
+ // start, or its end (or both) in the changed range. We want to adjust any part
+ // that intersects such that the final tree is in a consistent state. i.e. all
+ // children have spans within the span of their parent, and all siblings are ordered
+ // properly.
+ // We may need to update both the 'pos' and the 'end' of the element.
+ // If the 'pos' is before the start of the change, then we don't need to touch it.
+ // If it isn't, then the 'pos' must be inside the change. How we update it will
+ // depend if delta is positive or negative. If delta is positive then we have
+ // something like:
+ //
+ // -------------------AAA-----------------
+ // -------------------BBBCCCCCCC-----------------
+ //
+ // In this case, we consider any node that started in the change range to still be
+ // starting at the same position.
+ //
+ // however, if the delta is negative, then we instead have something like this:
+ //
+ // -------------------XXXYYYYYYY-----------------
+ // -------------------ZZZ-----------------
+ //
+ // In this case, any element that started in the 'X' range will keep its position.
+ // However any element that started after that will have their pos adjusted to be
+ // at the end of the new range. i.e. any node that started in the 'Y' range will
+ // be adjusted to have their start at the end of the 'Z' range.
+ //
+ // The element will keep its position if possible. Or Move backward to the new-end
+ // if it's in the 'Y' range.
element.pos = Math.min(element.pos, changeRangeNewEnd);
+ // If the 'end' is after the change range, then we always adjust it by the delta
+ // amount. However, if the end is in the change range, then how we adjust it
+ // will depend on if delta is positive or negative. If delta is positive then we
+ // have something like:
+ //
+ // -------------------AAA-----------------
+ // -------------------BBBCCCCCCC-----------------
+ //
+ // In this case, we consider any node that ended inside the change range to keep its
+ // end position.
+ //
+ // however, if the delta is negative, then we instead have something like this:
+ //
+ // -------------------XXXYYYYYYY-----------------
+ // -------------------ZZZ-----------------
+ //
+ // In this case, any element that ended in the 'X' range will keep its position.
+ // However any element that ended after that will have their pos adjusted to be
+ // at the end of the new range. i.e. any node that ended in the 'Y' range will
+ // be adjusted to have their end at the end of the 'Z' range.
if (element.end >= changeRangeOldEnd) {
+ // Element ends after the change range. Always adjust the end pos.
element.end += delta;
}
else {
+ // Element ends in the change range. The element will keep its position if
+ // possible. Or Move backward to the new-end if it's in the 'Y' range.
element.end = Math.min(element.end, changeRangeNewEnd);
}
ts.Debug.assert(element.pos <= element.end);
@@ -18583,13 +21526,19 @@ var ts;
function visitNode(child) {
ts.Debug.assert(child.pos <= child.end);
if (child.pos > changeRangeOldEnd) {
- moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks);
+ // Node is entirely past the change range. We need to move both its pos and
+ // end, forward or backward appropriately.
+ moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
return;
}
+ // Check if the element intersects the change range. If it does, then it is not
+ // reusable. Also, we'll need to recurse to see what constituent portions we may
+ // be able to use.
var fullEnd = child.end;
if (fullEnd >= changeStart) {
child.intersectsChange = true;
child._children = undefined;
+ // Adjust the pos or end (or both) of the intersecting element accordingly.
adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
forEachChild(child, visitNode, visitArray);
if (ts.hasJSDocNodes(child)) {
@@ -18601,18 +21550,25 @@ var ts;
checkNodePositions(child, aggressiveChecks);
return;
}
+ // Otherwise, the node is entirely before the change range. No need to do anything with it.
ts.Debug.assert(fullEnd < changeStart);
}
function visitArray(array) {
ts.Debug.assert(array.pos <= array.end);
if (array.pos > changeRangeOldEnd) {
- moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks);
+ // Array is entirely after the change range. We need to move it, and move any of
+ // its children.
+ moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
return;
}
+ // Check if the element intersects the change range. If it does, then it is not
+ // reusable. Also, we'll need to recurse to see what constituent portions we may
+ // be able to use.
var fullEnd = array.end;
if (fullEnd >= changeStart) {
array.intersectsChange = true;
array._children = undefined;
+ // Adjust the pos or end (or both) of the intersecting array accordingly.
adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
var node = array_9[_i];
@@ -18620,12 +21576,26 @@ var ts;
}
return;
}
+ // Otherwise, the array is entirely before the change range. No need to do anything with it.
ts.Debug.assert(fullEnd < changeStart);
}
}
function extendToAffectedRange(sourceFile, changeRange) {
+ // Consider the following code:
+ // void foo() { /; }
+ //
+ // If the text changes with an insertion of / just before the semicolon then we end up with:
+ // void foo() { //; }
+ //
+ // If we were to just use the changeRange a is, then we would not rescan the { token
+ // (as it does not intersect the actual original change range). Because an edit may
+ // change the token touching it, we actually need to look back *at least* one token so
+ // that the prior token sees that change.
var maxLookahead = 1;
var start = changeRange.span.start;
+ // the first iteration aligns us with the change start. subsequent iteration move us to
+ // the left by maxLookahead tokens. We only need to do this as long as we're not at the
+ // start of the tree.
for (var i = 0; start > 0 && i <= maxLookahead; i++) {
var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
ts.Debug.assert(nearestNode.pos <= start);
@@ -18660,23 +21630,54 @@ var ts;
}
function visit(child) {
if (ts.nodeIsMissing(child)) {
+ // Missing nodes are effectively invisible to us. We never even consider them
+ // When trying to find the nearest node before us.
return;
}
+ // If the child intersects this position, then this node is currently the nearest
+ // node that starts before the position.
if (child.pos <= position) {
if (child.pos >= bestResult.pos) {
+ // This node starts before the position, and is closer to the position than
+ // the previous best node we found. It is now the new best node.
bestResult = child;
}
+ // Now, the node may overlap the position, or it may end entirely before the
+ // position. If it overlaps with the position, then either it, or one of its
+ // children must be the nearest node before the position. So we can just
+ // recurse into this child to see if we can find something better.
if (position < child.end) {
+ // The nearest node is either this child, or one of the children inside
+ // of it. We've already marked this child as the best so far. Recurse
+ // in case one of the children is better.
forEachChild(child, visit);
+ // Once we look at the children of this node, then there's no need to
+ // continue any further.
return true;
}
else {
ts.Debug.assert(child.end <= position);
+ // The child ends entirely before this position. Say you have the following
+ // (where $ is the position)
+ //
+ // ? $ : <...> <...>
+ //
+ // We would want to find the nearest preceding node in "complex expr 2".
+ // To support that, we keep track of this node, and once we're done searching
+ // for a best node, we recurse down this node to see if we can find a good
+ // result in it.
+ //
+ // This approach allows us to quickly skip over nodes that are entirely
+ // before the position, while still allowing us to find any nodes in the
+ // last one that might be what we want.
lastNodeEntirelyBeforePosition = child;
}
}
else {
ts.Debug.assert(child.pos > position);
+ // We're now at a node that is entirely past the position we're searching for.
+ // This node (and all following nodes) could never contribute to the result,
+ // so just skip them by returning 'true' here.
return true;
}
}
@@ -18685,7 +21686,7 @@ var ts;
var oldText = sourceFile.text;
if (textChangeRange) {
ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
- if (aggressiveChecks || ts.Debug.shouldAssert(3)) {
+ if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
var newTextPrefix = newText.substr(0, textChangeRange.span.start);
ts.Debug.assert(oldTextPrefix === newTextPrefix);
@@ -18700,42 +21701,68 @@ var ts;
var currentArrayIndex = 0;
ts.Debug.assert(currentArrayIndex < currentArray.length);
var current = currentArray[currentArrayIndex];
- var lastQueriedPosition = -1;
+ var lastQueriedPosition = -1 /* Value */;
return {
currentNode: function (position) {
+ // Only compute the current node if the position is different than the last time
+ // we were asked. The parser commonly asks for the node at the same position
+ // twice. Once to know if can read an appropriate list element at a certain point,
+ // and then to actually read and consume the node.
if (position !== lastQueriedPosition) {
+ // Much of the time the parser will need the very next node in the array that
+ // we just returned a node from.So just simply check for that case and move
+ // forward in the array instead of searching for the node again.
if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
currentArrayIndex++;
current = currentArray[currentArrayIndex];
}
+ // If we don't have a node, or the node we have isn't in the right position,
+ // then try to find a viable node at the position requested.
if (!current || current.pos !== position) {
findHighestListElementThatStartsAtPosition(position);
}
}
+ // Cache this query so that we don't do any extra work if the parser calls back
+ // into us. Note: this is very common as the parser will make pairs of calls like
+ // 'isListElement -> parseListElement'. If we were unable to find a node when
+ // called with 'isListElement', we don't want to redo the work when parseListElement
+ // is called immediately after.
lastQueriedPosition = position;
+ // Either we don'd have a node, or we have a node at the position being asked for.
ts.Debug.assert(!current || current.pos === position);
return current;
}
};
+ // Finds the highest element in the tree we can find that starts at the provided position.
+ // The element must be a direct child of some node list in the tree. This way after we
+ // return it, we can easily return its next sibling in the list.
function findHighestListElementThatStartsAtPosition(position) {
+ // Clear out any cached state about the last node we found.
currentArray = undefined;
- currentArrayIndex = -1;
+ currentArrayIndex = -1 /* Value */;
current = undefined;
+ // Recurse into the source file to find the highest node at this position.
forEachChild(sourceFile, visitNode, visitArray);
return;
function visitNode(node) {
if (position >= node.pos && position < node.end) {
+ // Position was within this node. Keep searching deeper to find the node.
forEachChild(node, visitNode, visitArray);
+ // don't proceed any further in the search.
return true;
}
+ // position wasn't in this node, have to keep searching.
return false;
}
function visitArray(array) {
if (position >= array.pos && position < array.end) {
+ // position was in this array. Search through this array to see if we find a
+ // viable element.
for (var i = 0; i < array.length; i++) {
var child = array[i];
if (child) {
if (child.pos === position) {
+ // Found the right node. We're done.
currentArray = array;
currentArrayIndex = i;
current = child;
@@ -18743,6 +21770,8 @@ var ts;
}
else {
if (child.pos < position && position < child.end) {
+ // Position in somewhere within this child. Search in it and
+ // stop searching in this array.
forEachChild(child, visitNode, visitArray);
return true;
}
@@ -18750,6 +21779,7 @@ var ts;
}
}
}
+ // position wasn't in this array, have to keep searching.
return false;
}
}
@@ -18760,11 +21790,15 @@ var ts;
})(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
function isDeclarationFileName(fileName) {
- return ts.fileExtensionIs(fileName, ".d.ts");
+ return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
}
+ /*@internal*/
function processCommentPragmas(context, sourceText) {
- var triviaScanner = ts.createScanner(context.languageVersion, false, 0, sourceText);
+ var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText);
var pragmas = [];
+ // Keep scanning all the leading trivia in the file until we get to something that
+ // isn't trivia. Any single line comment will be analyzed to see if it is a
+ // reference comment.
while (true) {
var kind = triviaScanner.scan();
if (!ts.isTrivia(kind)) {
@@ -18781,7 +21815,7 @@ var ts;
context.pragmas = ts.createMap();
for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) {
var pragma = pragmas_1[_i];
- if (context.pragmas.has(pragma.name)) {
+ if (context.pragmas.has(pragma.name)) { // TODO: GH#18217
var currentValue = context.pragmas.get(pragma.name);
if (currentValue instanceof Array) {
currentValue.push(pragma.args);
@@ -18795,6 +21829,7 @@ var ts;
}
}
ts.processCommentPragmas = processCommentPragmas;
+ /*@internal*/
function processPragmasIntoFields(context, reportDiagnostic) {
context.checkJsDirective = undefined;
context.referencedFiles = [];
@@ -18803,12 +21838,15 @@ var ts;
context.amdDependencies = [];
context.hasNoDefaultLib = false;
context.pragmas.forEach(function (entryOrList, key) {
+ // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
+ // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
switch (key) {
case "reference": {
var referencedFiles_1 = context.referencedFiles;
var typeReferenceDirectives_1 = context.typeReferenceDirectives;
var libReferenceDirectives_1 = context.libReferenceDirectives;
ts.forEach(ts.toArray(entryOrList), function (arg) {
+ // TODO: GH#18217
if (arg.arguments["no-default-lib"]) {
context.hasNoDefaultLib = true;
}
@@ -18828,7 +21866,7 @@ var ts;
break;
}
case "amd-dependency": {
- context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
+ context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217
break;
}
case "amd-module": {
@@ -18836,6 +21874,7 @@ var ts;
for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
var entry = entryOrList_1[_i];
if (context.moduleName) {
+ // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
}
context.moduleName = entry.arguments.name;
@@ -18848,8 +21887,9 @@ var ts;
}
case "ts-nocheck":
case "ts-check": {
+ // _last_ of either nocheck or check in a file is the "winner"
ts.forEach(ts.toArray(entryOrList), function (entry) {
- if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
+ if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217
context.checkJsDirective = {
enabled: key === "ts-check",
end: entry.range.end,
@@ -18859,8 +21899,8 @@ var ts;
});
break;
}
- case "jsx": return;
- default: ts.Debug.fail("Unhandled pragma kind");
+ case "jsx": return; // Accessed directly
+ default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
}
});
}
@@ -18877,11 +21917,11 @@ var ts;
var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
function extractPragmas(pragmas, range, text) {
- var tripleSlash = range.kind === 2 && tripleSlashXMLCommentStartRegEx.exec(text);
+ var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
if (tripleSlash) {
- var name = tripleSlash[1].toLowerCase();
+ var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
var pragma = ts.commentPragmas[name];
- if (!pragma || !(pragma.kind & 1)) {
+ if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
return;
}
if (pragma.args) {
@@ -18891,7 +21931,7 @@ var ts;
var matcher = getNamedArgRegEx(arg.name);
var matchResult = matcher.exec(text);
if (!matchResult && !arg.optional) {
- return;
+ return; // Missing required argument, don't parse
}
else if (matchResult) {
if (arg.captureSpan) {
@@ -18914,30 +21954,30 @@ var ts;
}
return;
}
- var singleLine = range.kind === 2 && singleLinePragmaRegEx.exec(text);
+ var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
if (singleLine) {
- return addPragmaForMatch(pragmas, range, 2, singleLine);
+ return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
}
- if (range.kind === 3) {
- var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim;
+ if (range.kind === 3 /* MultiLineCommentTrivia */) {
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
var multiLineMatch = void 0;
while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
- addPragmaForMatch(pragmas, range, 4, multiLineMatch);
+ addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
}
}
}
function addPragmaForMatch(pragmas, range, kind, match) {
if (!match)
return;
- var name = match[1].toLowerCase();
+ var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
var pragma = ts.commentPragmas[name];
if (!pragma || !(pragma.kind & kind)) {
return;
}
- var args = match[2];
+ var args = match[2]; // Split on spaces and match up positionally with definition
var argument = getNamedPragmaArguments(pragma, args);
if (argument === "fail")
- return;
+ return; // Missing required argument, fail to parse it
pragmas.push({ name: name, args: { arguments: argument, range: range } });
return;
}
@@ -18960,16 +22000,20 @@ var ts;
}
return argMap;
}
+ /** @internal */
function tagNamesAreEquivalent(lhs, rhs) {
if (lhs.kind !== rhs.kind) {
return false;
}
- if (lhs.kind === 71) {
+ if (lhs.kind === 71 /* Identifier */) {
return lhs.escapedText === rhs.escapedText;
}
- if (lhs.kind === 99) {
+ if (lhs.kind === 99 /* ThisKeyword */) {
return true;
}
+ // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
+ // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
+ // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
return lhs.name.escapedText === rhs.name.escapedText &&
tagNamesAreEquivalent(lhs.expression, rhs.expression);
}
@@ -18977,8 +22021,14 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ /* @internal */
ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
+ // NOTE: The order here is important to default lib ordering as entries will have the same
+ // order in the generated program (see `getDefaultLibPriority` in program.ts). This
+ // order also affects overload resolution when a type declared in one lib is
+ // augmented in another lib.
var libEntries = [
+ // JavaScript only
["es5", "lib.es5.d.ts"],
["es6", "lib.es2015.d.ts"],
["es2015", "lib.es2015.d.ts"],
@@ -18987,11 +22037,13 @@ var ts;
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
["esnext", "lib.esnext.d.ts"],
+ // Host only
["dom", "lib.dom.d.ts"],
["dom.iterable", "lib.dom.iterable.d.ts"],
["webworker", "lib.webworker.d.ts"],
["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
["scripthost", "lib.scripthost.d.ts"],
+ // ES2015 Or ESNext By-feature options
["es2015.core", "lib.es2015.core.d.ts"],
["es2015.collection", "lib.es2015.collection.d.ts"],
["es2015.generator", "lib.es2015.generator.d.ts"],
@@ -19014,9 +22066,22 @@ var ts;
["esnext.symbol", "lib.esnext.symbol.d.ts"],
["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
];
+ /**
+ * An array of supported "lib" reference file names used to determine the order for inclusion
+ * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
+ * overload resolution when a type declared in one lib is extended by another.
+ */
+ /* @internal */
ts.libs = libEntries.map(function (entry) { return entry[0]; });
+ /**
+ * A map of lib names to lib files. This map is used both for parsing the "lib" command line
+ * option as well as for resolving lib reference directives.
+ */
+ /* @internal */
ts.libMap = ts.createMapFromEntries(libEntries);
+ /* @internal */
ts.optionDeclarations = [
+ // CommandLine only options
{
name: "help",
shortName: "h",
@@ -19092,18 +22157,19 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Watch_input_files,
},
+ // Basic
{
name: "target",
shortName: "t",
type: ts.createMapFromTemplate({
- es3: 0,
- es5: 1,
- es6: 2,
- es2015: 2,
- es2016: 3,
- es2017: 4,
- es2018: 5,
- esnext: 6,
+ es3: 0 /* ES3 */,
+ es5: 1 /* ES5 */,
+ es6: 2 /* ES2015 */,
+ es2015: 2 /* ES2015 */,
+ es2016: 3 /* ES2016 */,
+ es2017: 4 /* ES2017 */,
+ es2018: 5 /* ES2018 */,
+ esnext: 6 /* ESNext */,
}),
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
@@ -19155,9 +22221,9 @@ var ts;
{
name: "jsx",
type: ts.createMapFromTemplate({
- "preserve": 1,
- "react-native": 3,
- "react": 2
+ "preserve": 1 /* Preserve */,
+ "react-native": 3 /* ReactNative */,
+ "react": 2 /* React */
}),
paramType: ts.Diagnostics.KIND,
showInSimplifiedHelpView: true,
@@ -19257,6 +22323,7 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule
},
+ // Strict Type Checks
{
name: "strict",
type: "boolean",
@@ -19306,6 +22373,7 @@ var ts;
category: ts.Diagnostics.Strict_Type_Checking_Options,
description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
},
+ // Additional Checks
{
name: "noUnusedLocals",
type: "boolean",
@@ -19334,6 +22402,7 @@ var ts;
category: ts.Diagnostics.Additional_Checks,
description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
},
+ // Module Resolution
{
name: "moduleResolution",
type: ts.createMapFromTemplate({
@@ -19352,6 +22421,8 @@ var ts;
description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
},
{
+ // this option can only be specified in tsconfig.json
+ // use type = object to copy the value as-is
name: "paths",
type: "object",
isTSConfigOnly: true,
@@ -19359,6 +22430,8 @@ var ts;
description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl
},
{
+ // this option can only be specified in tsconfig.json
+ // use type = object to copy the value as-is
name: "rootDirs",
type: "list",
isTSConfigOnly: true,
@@ -19411,6 +22484,7 @@ var ts;
category: ts.Diagnostics.Module_Resolution_Options,
description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
},
+ // Source Maps
{
name: "sourceRoot",
type: "string",
@@ -19437,6 +22511,7 @@ var ts;
category: ts.Diagnostics.Source_Map_Options,
description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
},
+ // Experimental
{
name: "experimentalDecorators",
type: "boolean",
@@ -19449,6 +22524,7 @@ var ts;
category: ts.Diagnostics.Experimental_Options,
description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
},
+ // Advanced
{
name: "jsxFactory",
type: "string",
@@ -19495,6 +22571,7 @@ var ts;
name: "out",
type: "string",
isFilePath: false,
+ // for correct behaviour, please use outFile
category: ts.Diagnostics.Advanced_Options,
paramType: ts.Diagnostics.FILE,
description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
@@ -19532,8 +22609,8 @@ var ts;
{
name: "newLine",
type: ts.createMapFromTemplate({
- crlf: 0,
- lf: 1
+ crlf: 0 /* CarriageReturnLineFeed */,
+ lf: 1 /* LineFeed */
}),
paramType: ts.Diagnostics.NEWLINE,
category: ts.Diagnostics.Advanced_Options,
@@ -19656,6 +22733,7 @@ var ts;
description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
},
{
+ // A list of plugins to load in the language service
name: "plugins",
type: "list",
isTSConfigOnly: true,
@@ -19666,8 +22744,12 @@ var ts;
description: ts.Diagnostics.List_of_language_service_plugins
}
];
+ /* @internal */
ts.typeAcquisitionDeclarations = [
{
+ /* @deprecated typingOptions.enableAutoDiscovery
+ * Use typeAcquisition.enable instead.
+ */
name: "enableAutoDiscovery",
type: "boolean",
},
@@ -19692,14 +22774,17 @@ var ts;
}
}
];
+ /* @internal */
ts.defaultInitCompilerOptions = {
module: ts.ModuleKind.CommonJS,
- target: 1,
+ target: 1 /* ES5 */,
strict: true,
esModuleInterop: true
};
var optionNameMapCache;
+ /* @internal */
function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
+ // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
return {
enable: typeAcquisition.enableAutoDiscovery,
@@ -19725,6 +22810,7 @@ var ts;
optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
return optionNameMapCache;
}
+ /* @internal */
function createCompilerDiagnosticForInvalidCustomType(opt) {
return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
}
@@ -19733,10 +22819,12 @@ var ts;
var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
}
+ /* @internal */
function parseCustomTypeOption(opt, value, errors) {
return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
}
ts.parseCustomTypeOption = parseCustomTypeOption;
+ /* @internal */
function parseListTypeOption(opt, value, errors) {
if (value === void 0) { value = ""; }
value = trimString(value);
@@ -19774,16 +22862,17 @@ var ts;
while (i < args.length) {
var s = args[i];
i++;
- if (s.charCodeAt(0) === 64) {
+ if (s.charCodeAt(0) === 64 /* at */) {
parseResponseFile(s.slice(1));
}
- else if (s.charCodeAt(0) === 45) {
- var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true);
+ else if (s.charCodeAt(0) === 45 /* minus */) {
+ var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true);
if (opt) {
if (opt.isTSConfigOnly) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
}
else {
+ // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
}
@@ -19793,8 +22882,10 @@ var ts;
i++;
break;
case "boolean":
+ // boolean flag has optional value true, false, others
var optValue = args[i];
options[opt.name] = optValue !== "false";
+ // consume next argument as boolean flag value
if (optValue === "false" || optValue === "true") {
i++;
}
@@ -19810,6 +22901,7 @@ var ts;
i++;
}
break;
+ // If not a primitive, the possible types are specified in what is effectively a map of options.
default:
options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
i++;
@@ -19835,14 +22927,14 @@ var ts;
var args = [];
var pos = 0;
while (true) {
- while (pos < text.length && text.charCodeAt(pos) <= 32)
+ while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
pos++;
if (pos >= text.length)
break;
var start = pos;
- if (text.charCodeAt(start) === 34) {
+ if (text.charCodeAt(start) === 34 /* doubleQuote */) {
pos++;
- while (pos < text.length && text.charCodeAt(pos) !== 34)
+ while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
pos++;
if (pos < text.length) {
args.push(text.substring(start + 1, pos));
@@ -19853,7 +22945,7 @@ var ts;
}
}
else {
- while (text.charCodeAt(pos) > 32)
+ while (text.charCodeAt(pos) > 32 /* space */)
pos++;
args.push(text.substring(start, pos));
}
@@ -19862,10 +22954,12 @@ var ts;
}
}
ts.parseCommandLine = parseCommandLine;
+ /** @internal */
function getOptionFromName(optionName, allowShort) {
if (allowShort === void 0) { allowShort = false; }
optionName = optionName.toLowerCase();
var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames;
+ // Try to translate short option names to their full equivalents.
if (allowShort) {
var short = shortOptionNames.get(optionName);
if (short !== undefined) {
@@ -19883,20 +22977,25 @@ var ts;
var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
return diagnostic.messageText;
}
+ /* @internal */
function printVersion() {
ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine);
}
ts.printVersion = printVersion;
+ /* @internal */
function printHelp(optionsList, syntaxPrefix) {
if (syntaxPrefix === void 0) { syntaxPrefix = ""; }
var output = [];
+ // We want to align our "syntax" and "examples" commands to a certain margin.
var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length;
var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length;
var marginLength = Math.max(syntaxLength, examplesLength);
+ // Build up the syntactic skeleton.
var syntax = makePadding(marginLength - syntaxLength);
syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]";
output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax));
output.push(ts.sys.newLine + ts.sys.newLine);
+ // Build up the list of examples.
var padding = makePadding(marginLength);
output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine);
output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine);
@@ -19904,12 +23003,16 @@ var ts;
output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine);
output.push(ts.sys.newLine);
output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine);
+ // We want our descriptions to align at the same column in our output,
+ // so we keep track of the longest option usage string.
marginLength = 0;
- var usageColumn = [];
+ var usageColumn = []; // Things like "-d, --declaration" go in here.
var descriptionColumn = [];
- var optionsDescriptionMap = ts.createMap();
+ var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind
for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) {
var option = optionsList_1[_i];
+ // If an option lacks a description,
+ // it is not officially supported.
if (!option.description) {
continue;
}
@@ -19933,12 +23036,15 @@ var ts;
description = getDiagnosticText(option.description);
}
descriptionColumn.push(description);
+ // Set the new margin for the description column if necessary.
marginLength = Math.max(usageText_1.length, marginLength);
}
+ // Special case that can't fit in the loop.
var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">";
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file));
marginLength = Math.max(usageText.length, marginLength);
+ // Print out each row, aligning all the descriptions on the same column.
for (var i = 0; i < usageColumn.length; i++) {
var usage = usageColumn[i];
var description = descriptionColumn[i];
@@ -19969,6 +23075,9 @@ var ts;
}
}
ts.printHelp = printHelp;
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
var configFileText;
try {
@@ -19989,11 +23098,20 @@ var ts;
return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
}
ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
+ /**
+ * Read tsconfig.json file
+ * @param fileName The path to the config file
+ */
function readConfigFile(fileName, readFile) {
var textOrDiagnostic = tryReadFile(fileName, readFile);
return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
}
ts.readConfigFile = readConfigFile;
+ /**
+ * Parse the text of the tsconfig.json file
+ * @param fileName The path to the config file
+ * @param jsonText The text of the config file
+ */
function parseConfigFileTextToJson(fileName, jsonText) {
var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
return {
@@ -20002,6 +23120,10 @@ var ts;
};
}
ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
+ /**
+ * Read tsconfig.json file
+ * @param fileName The path to the config file
+ */
function readJsonConfigFile(fileName, readFile) {
var textOrDiagnostic = tryReadFile(fileName, readFile);
return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
@@ -20087,10 +23209,19 @@ var ts;
}
return _tsconfigRootOptions;
}
+ /**
+ * Convert the json syntax tree into the json value
+ */
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, true, undefined, undefined);
+ return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
}
ts.convertToObject = convertToObject;
+ /**
+ * Convert the json syntax tree into the json value and report errors
+ * This returns the json value (apart from checking errors) only if returnValue provided is true.
+ * Otherwise it just checks the errors and returns undefined
+ */
+ /*@internal*/
function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
if (!sourceFile.statements.length) {
return returnValue ? {} : undefined;
@@ -20103,7 +23234,7 @@ var ts;
var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
- if (element.kind !== 270) {
+ if (element.kind !== 270 /* PropertyAssignment */) {
errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
continue;
}
@@ -20123,19 +23254,24 @@ var ts;
if (returnValue) {
result[keyText] = value;
}
+ // Notify key value set, if user asked for it
if (jsonConversionNotifier &&
+ // Current callbacks are only on known parent option or if we are setting values in the root
(parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
+ // Notify option set in the parent if its a valid option value
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
+ // Notify about the valid root key value being set
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
}
else if (!option) {
+ // Notify about the unknown root key value being set
jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
}
}
@@ -20149,16 +23285,16 @@ var ts;
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
- case 101:
+ case 101 /* TrueKeyword */:
reportInvalidOptionValue(option && option.type !== "boolean");
return true;
- case 86:
+ case 86 /* FalseKeyword */:
reportInvalidOptionValue(option && option.type !== "boolean");
return false;
- case 95:
- reportInvalidOptionValue(option && option.name === "extends");
- return null;
- case 9:
+ case 95 /* NullKeyword */:
+ reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
+ return null; // tslint:disable-line:no-null-keyword
+ case 9 /* StringLiteral */:
if (!isDoubleQuotedString(valueExpression)) {
errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
}
@@ -20166,36 +23302,45 @@ var ts;
var text = valueExpression.text;
if (option && !ts.isString(option.type)) {
var customOption = option;
+ // Validate custom option type
if (!customOption.type.has(text.toLowerCase())) {
errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
}
}
return text;
- case 8:
+ case 8 /* NumericLiteral */:
reportInvalidOptionValue(option && option.type !== "number");
return Number(valueExpression.text);
- case 198:
- if (valueExpression.operator !== 38 || valueExpression.operand.kind !== 8) {
- break;
+ case 198 /* PrefixUnaryExpression */:
+ if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
+ break; // not valid JSON syntax
}
reportInvalidOptionValue(option && option.type !== "number");
return -Number(valueExpression.operand.text);
- case 184:
+ case 184 /* ObjectLiteralExpression */:
reportInvalidOptionValue(option && option.type !== "object");
var objectLiteralExpression = valueExpression;
+ // Currently having element option declaration in the tsconfig with type "object"
+ // determines if it needs onSetValidOptionKeyValueInParent callback or not
+ // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
+ // that satifies it and need it to modify options set in them (for normalizing file paths)
+ // vs what we set in the json
+ // If need arises, we can modify this interface and callbacks as needed
if (option) {
var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name;
return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName);
}
else {
- return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined);
+ return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
+ /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
}
- case 183:
+ case 183 /* ArrayLiteralExpression */:
reportInvalidOptionValue(option && option.type !== "list");
return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
}
+ // Not in expected format
if (option) {
- reportInvalidOptionValue(true);
+ reportInvalidOptionValue(/*isError*/ true);
}
else {
errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal));
@@ -20220,7 +23365,7 @@ var ts;
function isCompilerOptionsValue(option, value) {
if (option) {
if (isNullOrUndefined(value))
- return true;
+ return true; // All options are undefinable/nullable
if (option.type === "list") {
return ts.isArray(value);
}
@@ -20229,12 +23374,19 @@ var ts;
}
return false;
}
+ /**
+ * Generate tsconfig configuration when running command line "--init"
+ * @param options commandlineOptions to be generated into tsconfig.json
+ * @param fileNames array of filenames to be generated into tsconfig.json
+ */
+ /* @internal */
function generateTSConfig(options, fileNames, newLine) {
var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
return writeConfigurations();
function getCustomTypeMapOfCommandLineOption(optionDefinition) {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
+ // this is of a type CommandLineOptionOfPrimitiveType
return undefined;
}
else if (optionDefinition.type === "list") {
@@ -20245,6 +23397,7 @@ var ts;
}
}
function getNameOfCompilerOptionValue(value, customTypeMap) {
+ // There is a typeMap associated with this command-line option so use it to map value back to its name
return ts.forEachEntry(customTypeMap, function (mapValue, key) {
if (mapValue === value) {
return key;
@@ -20256,6 +23409,8 @@ var ts;
var optionsNameMap = getOptionNameMap().optionNameMap;
var _loop_3 = function (name) {
if (ts.hasProperty(options, name)) {
+ // tsconfig only options cannot be specified via command line,
+ // so we can assume that only types that can appear here string | number | boolean
if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
return "continue";
}
@@ -20264,13 +23419,16 @@ var ts;
if (optionDefinition) {
var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
if (!customTypeMap_1) {
+ // There is no map associated with this compiler option then use the value as-is
+ // This is the case if the value is expect to be string, number, boolean or list of string
result.set(name, value);
}
else {
if (optionDefinition.type === "list") {
- result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); }));
+ result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
}
else {
+ // There is a typeMap associated with this command-line option so use it to map value back to its name
result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
}
}
@@ -20303,11 +23461,14 @@ var ts;
}
function isAllowedOption(_a) {
var category = _a.category, name = _a.name;
+ // Skip options which do not have a category or have category `Command_line_Options`
+ // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
return category !== undefined
&& category !== ts.Diagnostics.Command_line_Options
&& (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
}
function writeConfigurations() {
+ // Filter applicable options to place in the file
var categorizedOptions = ts.createMultiMap();
for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
var option = optionDeclarations_1[_i];
@@ -20316,6 +23477,7 @@ var ts;
categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
}
}
+ // Serialize all options and their descriptions
var marginLength = 0;
var seenKnownKeys = 0;
var nameColumn = [];
@@ -20341,10 +23503,12 @@ var ts;
marginLength = Math.max(optionName.length, marginLength);
}
});
+ // Write the output
var tab = makePadding(2);
var result = [];
result.push("{");
result.push(tab + "\"compilerOptions\": {");
+ // Print out each row, aligning all the descriptions on the same column.
for (var i = 0; i < nameColumn.length; i++) {
var optionName = nameColumn[i];
var description = descriptionColumn[i];
@@ -20366,14 +23530,29 @@ var ts;
}
}
ts.generateTSConfig = generateTSConfig;
+ /**
+ * Parse the contents of a config file (tsconfig.json).
+ * @param json The contents of the config file to parse
+ * @param host Instance of ParseConfigHost used to enumerate files in folder.
+ * @param basePath A root directory to resolve relative path entries in the config
+ * file to. e.g. outDir
+ */
function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
- return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
+ return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
}
ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
+ /**
+ * Parse the contents of a config file (tsconfig.json).
+ * @param jsonNode The contents of the config file to parse
+ * @param host Instance of ParseConfigHost used to enumerate files in folder.
+ * @param basePath A root directory to resolve relative path entries in the config
+ * file to. e.g. outDir
+ */
function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
- return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
+ return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
}
ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
+ /*@internal*/
function setConfigFileInOptions(options, configFile) {
if (configFile) {
Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
@@ -20381,11 +23560,23 @@ var ts;
}
ts.setConfigFileInOptions = setConfigFileInOptions;
function isNullOrUndefined(x) {
+ // tslint:disable-next-line:no-null-keyword
return x === undefined || x === null;
}
function directoryOfCombinedPath(fileName, basePath) {
+ // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
+ // until consistient casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
+ /**
+ * Parse the contents of a config file from json or json source file (tsconfig.json).
+ * @param json The contents of the config file to parse
+ * @param sourceFile sourceFile corresponding to the Json
+ * @param host Instance of ParseConfigHost used to enumerate files in folder.
+ * @param basePath A root directory to resolve relative path entries in the config
+ * file to. e.g. outDir
+ * @param resolutionStack Only present for backwards-compatibility. Should be empty.
+ */
function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
if (existingOptions === void 0) { existingOptions = {}; }
if (resolutionStack === void 0) { resolutionStack = []; }
@@ -20485,10 +23676,12 @@ var ts;
}
}
}
+ /*@internal*/
function isErrorNoInputFiles(error) {
return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
}
ts.isErrorNoInputFiles = isErrorNoInputFiles;
+ /*@internal*/
function getErrorForNoInputFiles(_a, configFileName) {
var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []));
@@ -20497,6 +23690,10 @@ var ts;
function isSuccessfulParsedTsconfig(value) {
return !!value.options;
}
+ /**
+ * This *just* extracts options/include/exclude/files out of a config file.
+ * It does *not* resolve the included files.
+ */
function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) {
basePath = ts.normalizeSlashes(basePath);
var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
@@ -20508,6 +23705,7 @@ var ts;
parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
if (ownConfig.extendedConfigPath) {
+ // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = resolutionStack.concat([resolvedPath]);
var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors);
if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
@@ -20526,6 +23724,7 @@ var ts;
raw_1.compileOnSave = baseRaw_1.compileOnSave;
}
ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
+ // TODO extend type typeAcquisition
}
}
return ownConfig;
@@ -20535,6 +23734,8 @@ var ts;
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
+ // typingOptions has been deprecated and is only supported for backward compatibility purposes.
+ // It should be removed in future releases - use typeAcquisition instead.
var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
var extendedConfigPath;
@@ -20584,7 +23785,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -20603,12 +23804,13 @@ var ts;
}
function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
extendedConfig = ts.normalizeSlashes(extendedConfig);
+ // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future)
if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) {
errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
return undefined;
}
var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
- if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) {
+ if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
extendedConfigPath = extendedConfigPath + ".json";
if (!host.fileExists(extendedConfigPath)) {
errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig));
@@ -20628,11 +23830,12 @@ var ts;
return undefined;
}
var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
- var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors);
+ var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors);
if (sourceFile) {
(_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
}
if (isSuccessfulParsedTsconfig(extendedConfig)) {
+ // Update the paths to reflect base path
var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
var mapPropertiesInRawIfNotUndefined = function (propertyName) {
@@ -20761,31 +23964,118 @@ var ts;
function trimString(s) {
return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
}
+ /**
+ * Tests for a path that ends in a recursive directory wildcard.
+ * Matches **, \**, **\, and \**\, but not a**b.
+ *
+ * NOTE: used \ in place of / above to avoid issues with multiline comments.
+ *
+ * Breakdown:
+ * (^|\/) # matches either the beginning of the string or a directory separator.
+ * \*\* # matches the recursive directory wildcard "**".
+ * \/?$ # matches an optional trailing directory separator at the end of the string.
+ */
var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
+ /**
+ * Tests for a path where .. appears after a recursive directory wildcard.
+ * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
+ *
+ * NOTE: used \ in place of / above to avoid issues with multiline comments.
+ *
+ * Breakdown:
+ * (^|\/) # matches either the beginning of the string or a directory separator.
+ * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator.
+ * (.*\/)? # optionally matches any number of characters followed by a directory separator.
+ * \.\. # matches a parent directory path component ".."
+ * ($|\/) # matches either the end of the string or a directory separator.
+ */
var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
+ /**
+ * Tests for a path containing a wildcard character in a directory component of the path.
+ * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
+ *
+ * NOTE: used \ in place of / above to avoid issues with multiline comments.
+ *
+ * Breakdown:
+ * \/ # matches a directory separator.
+ * [^/]*? # matches any number of characters excluding directory separators (non-greedy).
+ * [*?] # matches either a wildcard character (* or ?)
+ * [^/]* # matches any number of characters excluding directory separators (greedy).
+ * \/ # matches a directory separator.
+ */
var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
+ /**
+ * Matches the portion of a wildcard path that does not contain wildcards.
+ * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
+ *
+ * NOTE: used \ in place of / above to avoid issues with multiline comments.
+ *
+ * Breakdown:
+ * ^ # matches the beginning of the string
+ * [^*?]* # matches any number of non-wildcard characters
+ * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by
+ * # a path component that contains at least one wildcard character (* or ?).
+ */
var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
+ /**
+ * Expands an array of file specifications.
+ *
+ * @param filesSpecs The literal file names to include.
+ * @param includeSpecs The wildcard file specifications to include.
+ * @param excludeSpecs The wildcard file specifications to exclude.
+ * @param basePath The base path for any relative file specifications.
+ * @param options Compiler options.
+ * @param host The host used to resolve files and directories.
+ * @param errors An array for diagnostic reporting.
+ */
function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
basePath = ts.normalizePath(basePath);
var validatedIncludeSpecs, validatedExcludeSpecs;
+ // The exclude spec list is converted into a regular expression, which allows us to quickly
+ // test whether a file or directory should be excluded before recursively traversing the
+ // file system.
if (includeSpecs) {
- validatedIncludeSpecs = validateSpecs(includeSpecs, errors, false, jsonSourceFile, "include");
+ validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
}
if (excludeSpecs) {
- validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude");
+ validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
}
+ // Wildcard directories (provided as part of a wildcard path) are stored in a
+ // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
+ // or a recursive directory. This information is used by filesystem watchers to monitor for
+ // new entries in these paths.
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
+ /**
+ * Gets the file names from the provided config file specs that contain, files, include, exclude and
+ * other properties needed to resolve the file names
+ * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
+ * @param basePath The base path for any relative file specifications.
+ * @param options Compiler options.
+ * @param host The host used to resolve files and directories.
+ * @param extraFileExtensions optionaly file extra file extension information from host
+ */
+ /* @internal */
function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
if (extraFileExtensions === void 0) { extraFileExtensions = []; }
basePath = ts.normalizePath(basePath);
var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase;
+ // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
+ // file map with a possibly case insensitive key. We use this map later when when including
+ // wildcard paths.
var literalFileMap = ts.createMap();
+ // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
+ // file map with a possibly case insensitive key. We use this map to store paths matched
+ // via wildcard, and to handle extension priority.
var wildcardFileMap = ts.createMap();
var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
+ // Rather than requery this for each file and filespec, we query the supported extensions
+ // once and store it on the expansion context.
var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
+ // Literal files are always included verbatim. An "include" or "exclude" specification cannot
+ // remove a literal file.
if (filesSpecs) {
for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
var fileName = filesSpecs_1[_i];
@@ -20794,11 +24084,21 @@ var ts;
}
}
if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
- for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) {
+ for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
var file = _b[_a];
+ // If we have already included a literal or wildcard path with a
+ // higher priority extension, we should skip this file.
+ //
+ // This handles cases where we may encounter both .ts and
+ // .d.ts (or .js if "allowJs" is enabled) in the same
+ // directory when they are compilation outputs.
if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
continue;
}
+ // We may have included a wildcard path with a lower priority
+ // extension due to the user-defined order of entries in the
+ // "include" array. If there is a lower priority extension in the
+ // same directory, we should remove it.
removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
var key = keyMapper(file);
if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
@@ -20842,7 +24142,22 @@ var ts;
return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
}
}
+ /**
+ * Gets directories in a set of include patterns that should be watched for changes.
+ */
function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
+ // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
+ // of the pattern:
+ //
+ // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively
+ // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
+ // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler
+ //
+ // We watch a directory without recursion if it contains a wildcard in the file segment of
+ // the pattern:
+ //
+ // /a/b/* - Watch /a/b directly to catch any new file
+ // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
var wildcardDirectories = {};
@@ -20860,12 +24175,13 @@ var ts;
var existingFlags = wildcardDirectories[key];
if (existingFlags === undefined || existingFlags < flags) {
wildcardDirectories[key] = flags;
- if (flags === 1) {
+ if (flags === 1 /* Recursive */) {
recursiveKeys.push(key);
}
}
}
}
+ // Remove any subpaths under an existing recursively watched directory.
for (var key in wildcardDirectories) {
if (ts.hasProperty(wildcardDirectories, key)) {
for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
@@ -20884,18 +24200,26 @@ var ts;
if (match) {
return {
key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(),
- flags: watchRecursivePattern.test(spec) ? 1 : 0
+ flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
};
}
if (ts.isImplicitGlob(spec)) {
- return { key: spec, flags: 1 };
+ return { key: spec, flags: 1 /* Recursive */ };
}
return undefined;
}
+ /**
+ * Determines whether a literal or wildcard file has already been included that has a higher
+ * extension priority.
+ *
+ * @param file The path to the file.
+ * @param extensionPriority The priority of the extension.
+ * @param context The expansion context.
+ */
function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
var extensionPriority = ts.getExtensionPriority(file, extensions);
var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
- for (var i = 0; i < adjustedExtensionPriority; i++) {
+ for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
var higherPriorityExtension = extensions[i];
var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
@@ -20904,6 +24228,14 @@ var ts;
}
return false;
}
+ /**
+ * Removes files included via wildcard expansion with a lower extension priority that have
+ * already been included.
+ *
+ * @param file The path to the file.
+ * @param extensionPriority The priority of the extension.
+ * @param context The expansion context.
+ */
function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
var extensionPriority = ts.getExtensionPriority(file, extensions);
var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
@@ -20913,12 +24245,17 @@ var ts;
wildcardFiles.delete(lowerPriorityPath);
}
}
+ /**
+ * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed.
+ * Also converts enum values back to strings.
+ */
+ /* @internal */
function convertCompilerOptionsForTelemetry(opts) {
var out = {};
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
var type = getOptionFromName(key);
- if (type !== undefined) {
+ if (type !== undefined) { // Ignore unknown options
out[key] = getOptionValueWithEmptyStrings(opts[key], type);
}
}
@@ -20928,11 +24265,11 @@ var ts;
ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
function getOptionValueWithEmptyStrings(value, option) {
switch (option.type) {
- case "object":
+ case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
return "";
- case "string":
+ case "string": // Could be any arbitrary string -- use empty string instead.
return "";
- case "number":
+ case "number": // Allow numbers, but be sure to check it's actually a number.
return typeof value === "number" ? value : "";
case "boolean":
return typeof value === "boolean" ? value : "";
@@ -20944,7 +24281,7 @@ var ts;
if (optionEnumValue === value) {
return optionStringValue;
}
- });
+ }); // TODO: GH#18217
}
}
})(ts || (ts = {}));
@@ -20954,6 +24291,7 @@ var ts;
host.trace(ts.formatMessage.apply(undefined, arguments));
}
ts.trace = trace;
+ /* @internal */
function isTraceEnabled(compilerOptions, host) {
return !!compilerOptions.traceResolution && host.trace !== undefined;
}
@@ -20962,15 +24300,20 @@ var ts;
return r && { path: r.path, extension: r.ext, packageId: packageId };
}
function noPackageId(r) {
- return withPackageId(undefined, r);
+ return withPackageId(/*packageId*/ undefined, r);
}
+ /**
+ * Kinds of file that we are currently looking for.
+ * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
+ */
var Extensions;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
Extensions[Extensions["Json"] = 2] = "Json";
- Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */
})(Extensions || (Extensions = {}));
+ /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved) {
if (!resolved) {
return undefined;
@@ -20984,6 +24327,7 @@ var ts;
failedLookupLocations: failedLookupLocations
};
}
+ /** Reads from "main" or "types"/"typings" depending on `extensions`. */
function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) {
return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main");
function tryReadFromField(fieldName) {
@@ -21007,6 +24351,7 @@ var ts;
return path;
}
}
+ /* @internal */
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
@@ -21019,6 +24364,7 @@ var ts;
return result.config;
}
catch (e) {
+ // gracefully handle if readFile fails or returns not JSON
return {};
}
}
@@ -21039,9 +24385,14 @@ var ts;
}
}
ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ /**
+ * Returns the path to every node_modules/@types directory from some ancestor directory.
+ * Returns undefined if there are none.
+ */
function getDefaultTypeRoots(currentDirectory, host) {
if (!host.directoryExists) {
return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ // And if it doesn't exist, tough.
}
var typeRoots;
ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
@@ -21054,6 +24405,11 @@ var ts;
return typeRoots;
}
var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ /**
+ * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
+ * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
+ * is assumed to be the same as root directory of the project.
+ */
function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
var traceEnabled = isTraceEnabled(options, host);
var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled };
@@ -21095,6 +24451,7 @@ var ts;
}
return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
function primaryLookup() {
+ // Check primary library paths
if (typeRoots && typeRoots.length) {
if (traceEnabled) {
trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
@@ -21118,10 +24475,11 @@ var ts;
function secondaryLookup() {
var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
if (initialLocationForSecondaryLookup !== undefined) {
+ // check secondary locations
if (traceEnabled) {
trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
- var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined);
+ var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined);
var resolvedFile = resolvedTypeScriptOnly(result && result.value);
if (!resolvedFile && traceEnabled) {
trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
@@ -21136,10 +24494,20 @@ var ts;
}
}
ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
+ /**
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
function getAutomaticTypeDirectiveNames(options, host) {
+ // Use explicit type list from tsconfig.json
if (options.types) {
return options.types;
}
+ // Walk the primary type lookup locations
var result = [];
if (host.directoryExists && host.getDirectories) {
var typeRoots = getEffectiveTypeRoots(options, host);
@@ -21151,8 +24519,12 @@ var ts;
var typeDirectivePath = _b[_a];
var normalized = ts.normalizePath(typeDirectivePath);
var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized));
+ // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
+ // See `createNotNeededPackageJSON` in the types-publisher` repo.
+ // tslint:disable-next-line:no-null-keyword
var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
if (!isNotNeededPackage) {
+ // Return just the type directive names
result.push(ts.getBaseFileName(normalized));
}
}
@@ -21167,6 +24539,7 @@ var ts;
return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
}
ts.createModuleResolutionCache = createModuleResolutionCache;
+ /*@internal*/
function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
@@ -21180,7 +24553,7 @@ var ts;
}
function getOrCreateCacheForModuleName(nonRelativeModuleName) {
if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) {
- return undefined;
+ return undefined; // TODO: GH#18217
}
var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName);
if (!perModuleNameCache) {
@@ -21195,13 +24568,29 @@ var ts;
function get(directory) {
return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
}
+ /**
+ * At first this function add entry directory -> module resolution result to the table.
+ * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
+ * and for every parent folder in set it adds entry: parent -> module resolution. .
+ * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
+ * Set of parent folders that should have the same result will be:
+ * [
+ * /a/b/c/d, /a/b/c, /a/b
+ * ]
+ * this means that request for module resolution from file in any of these folder will be immediately found in cache.
+ */
function set(directory, result) {
var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
+ // if entry is already in cache do nothing
if (directoryPathMap.has(path)) {
return;
}
directoryPathMap.set(path, result);
var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName;
+ // find common prefix between directory and resolved file name
+ // this common prefix should be the shorted path that has the same resolution
+ // directory: /a/b/c/d/e
+ // resolvedFileName: /a/b/foo.d.ts
var commonPrefix = getCommonPrefix(path, resolvedFileName);
var current = path;
while (true) {
@@ -21221,10 +24610,12 @@ var ts;
return undefined;
}
var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
+ // find first position where directory and resolution differs
var i = 0;
while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
i++;
}
+ // find last directory separator before position i
var sep = directory.lastIndexOf(ts.directorySeparator, i);
if (sep < 0) {
return undefined;
@@ -21278,6 +24669,7 @@ var ts;
}
if (perFolderCache) {
perFolderCache.set(moduleName, result);
+ // put result in per-module name cache
var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName);
if (perModuleNameCache) {
perModuleNameCache.set(containingDirectory, result);
@@ -21295,6 +24687,66 @@ var ts;
return result;
}
ts.resolveModuleName = resolveModuleName;
+ /**
+ * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
+ * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
+ * can be resolved successfully by TypeScript compiler and runtime module loader.
+ * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
+ * fallback to standard resolution routine.
+ *
+ * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
+ * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
+ * be '/a/b/c/d'
+ * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
+ * will be resolved based on the content of the module name.
+ * Structure of 'paths' compiler options
+ * 'paths': {
+ * pattern-1: [...substitutions],
+ * pattern-2: [...substitutions],
+ * ...
+ * pattern-n: [...substitutions]
+ * }
+ * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
+ * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
+ * If pattern contains '*' then to match pattern "*" module name must start with the and end with .
+ * denotes part of the module name between and .
+ * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
+ * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
+ * from the candidate location.
+ * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
+ * substitution in the list and replace '*' with string. If candidate location is not rooted it
+ * will be converted to absolute using baseUrl.
+ * For example:
+ * baseUrl: /a/b/c
+ * "paths": {
+ * // match all module names
+ * "*": [
+ * "*", // use matched name as is,
+ * // will be looked as /a/b/c/
+ *
+ * "folder1/*" // substitution will convert matched name to 'folder1/',
+ * // since it is not rooted then final candidate location will be /a/b/c/folder1/
+ * ],
+ * // match module names that start with 'components/'
+ * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/