X-Git-Url: https://git.josue.xyz/?a=blobdiff_plain;f=.config%2Fcoc%2Fextensions%2Fnode_modules%2Fcoc-tsserver%2Fnode_modules%2Ftypescript%2Flib%2Ftsserverlibrary.js;h=362c8ed2f4b241901de89e84fddbd5d926945565;hb=3be0a9efc698a9570a44456009afc6014812625a;hp=6c6a3e40b5ac9a8930bf90ece3de90ec10243eaf;hpb=3aba54c891969552833dbc350b3139e944e17a97;p=dotfiles%2F.git
diff --git a/.config/coc/extensions/node_modules/coc-tsserver/node_modules/typescript/lib/tsserverlibrary.js b/.config/coc/extensions/node_modules/coc-tsserver/node_modules/typescript/lib/tsserverlibrary.js
index 6c6a3e40..362c8ed2 100644
--- a/.config/coc/extensions/node_modules/coc-tsserver/node_modules/typescript/lib/tsserverlibrary.js
+++ b/.config/coc/extensions/node_modules/coc-tsserver/node_modules/typescript/lib/tsserverlibrary.js
@@ -14,12 +14,14 @@ and limitations under the License.
***************************************************************************** */
"use strict";
-var __spreadArrays = (this && this.__spreadArrays) || function () {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
+var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
};
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
@@ -32,6 +34,10 @@ var __assign = (this && this.__assign) || function () {
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
@@ -59,10 +65,6 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
-var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
-};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -78,10 +80,12 @@ var __extends = (this && this.__extends) || (function () {
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]; };
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
@@ -90,178 +94,207 @@ var __extends = (this && this.__extends) || (function () {
/* @internal */
var ts;
(function (ts) {
- function createMapShim() {
- /** Create a MapLike with good performance. */
- function createDictionaryObject() {
- var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
- // 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;
+ function createMapData() {
+ var sentinel = {};
+ sentinel.prev = sentinel;
+ return { head: sentinel, tail: sentinel, size: 0 };
+ }
+ function createMapEntry(key, value) {
+ return { key: key, value: value, next: undefined, prev: undefined };
+ }
+ function sameValueZero(x, y) {
+ // Treats -0 === 0 and NaN === NaN
+ return x === y || x !== x && y !== y;
+ }
+ function getPrev(entry) {
+ var prev = entry.prev;
+ // Entries without a 'prev' have been removed from the map.
+ // An entry whose 'prev' points to itself is the head of the list and is invalid here.
+ if (!prev || prev === entry)
+ throw new Error("Illegal state");
+ return prev;
+ }
+ function getNext(entry) {
+ while (entry) {
+ // Entries without a 'prev' have been removed from the map. Their 'next'
+ // pointer should point to the previous entry prior to deletion and
+ // that entry should be skipped to resume iteration.
+ var skipNext = !entry.prev;
+ entry = entry.next;
+ if (skipNext) {
+ continue;
+ }
+ return entry;
}
- var MapIterator = /** @class */ (function () {
- function MapIterator(currentEntry, selector) {
- this.currentEntry = currentEntry;
- this.selector = selector;
- }
- MapIterator.prototype.next = function () {
- // Navigate to the next entry.
- while (this.currentEntry) {
- var skipNext = !!this.currentEntry.skipNext;
- this.currentEntry = this.currentEntry.nextEntry;
- if (!skipNext) {
- break;
- }
- }
- if (this.currentEntry) {
- return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
- }
- else {
- return { value: undefined, done: true };
- }
- };
- return MapIterator;
- }());
- return /** @class */ (function () {
- function class_1() {
- this.data = createDictionaryObject();
- this.size = 0;
- // Create a first (stub) map entry that will not contain a key
- // and value but serves as starting point for iterators.
- this.firstEntry = {};
- // When the map is empty, the last entry is the same as the
- // first one.
- this.lastEntry = this.firstEntry;
- }
- class_1.prototype.get = function (key) {
- var entry = this.data[key];
- return entry && entry.value;
- };
- class_1.prototype.set = function (key, value) {
- if (!this.has(key)) {
- this.size++;
- // Create a new entry that will be appended at the
- // end of the linked list.
- var newEntry = {
- key: key,
- value: value
- };
- this.data[key] = newEntry;
- // Adjust the references.
- var previousLastEntry = this.lastEntry;
- previousLastEntry.nextEntry = newEntry;
- newEntry.previousEntry = previousLastEntry;
- this.lastEntry = newEntry;
+ }
+ function getEntry(data, key) {
+ // We walk backwards from 'tail' to prioritize recently added entries.
+ // We skip 'head' because it is an empty entry used to track iteration start.
+ for (var entry = data.tail; entry !== data.head; entry = getPrev(entry)) {
+ if (sameValueZero(entry.key, key)) {
+ return entry;
+ }
+ }
+ }
+ function addOrUpdateEntry(data, key, value) {
+ var existing = getEntry(data, key);
+ if (existing) {
+ existing.value = value;
+ return;
+ }
+ var entry = createMapEntry(key, value);
+ entry.prev = data.tail;
+ data.tail.next = entry;
+ data.tail = entry;
+ data.size++;
+ return entry;
+ }
+ function deleteEntry(data, key) {
+ // We walk backwards from 'tail' to prioritize recently added entries.
+ // We skip 'head' because it is an empty entry used to track iteration start.
+ for (var entry = data.tail; entry !== data.head; entry = getPrev(entry)) {
+ // all entries in the map should have a 'prev' pointer.
+ if (entry.prev === undefined)
+ throw new Error("Illegal state");
+ if (sameValueZero(entry.key, key)) {
+ if (entry.next) {
+ entry.next.prev = entry.prev;
}
else {
- this.data[key].value = value;
+ // an entry in the map without a 'next' pointer must be the 'tail'.
+ if (data.tail !== entry)
+ throw new Error("Illegal state");
+ data.tail = entry.prev;
}
- return this;
- };
- class_1.prototype.has = function (key) {
- // eslint-disable-next-line no-in-operator
- return key in this.data;
- };
- class_1.prototype.delete = function (key) {
- if (this.has(key)) {
- this.size--;
- var entry = this.data[key];
- delete this.data[key];
- // Adjust the linked list references of the neighbor entries.
- var previousEntry = entry.previousEntry;
- previousEntry.nextEntry = entry.nextEntry;
- if (entry.nextEntry) {
- entry.nextEntry.previousEntry = previousEntry;
- }
- // When the deleted entry was the last one, we need to
- // adjust the lastEntry reference.
- if (this.lastEntry === entry) {
- this.lastEntry = previousEntry;
- }
- // Adjust the forward reference of the deleted entry
- // in case an iterator still references it. This allows us
- // to throw away the entry, but when an active iterator
- // (which points to the current entry) continues, it will
- // navigate to the entry that originally came before the
- // current one and skip it.
- entry.previousEntry = undefined;
- entry.nextEntry = previousEntry;
- entry.skipNext = true;
- return true;
+ entry.prev.next = entry.next;
+ entry.next = entry.prev;
+ entry.prev = undefined;
+ data.size--;
+ return entry;
+ }
+ }
+ }
+ function clearEntries(data) {
+ var node = data.tail;
+ while (node !== data.head) {
+ var prev = getPrev(node);
+ node.next = data.head;
+ node.prev = undefined;
+ node = prev;
+ }
+ data.head.next = undefined;
+ data.tail = data.head;
+ data.size = 0;
+ }
+ function forEachEntry(data, action) {
+ var entry = data.head;
+ while (entry) {
+ entry = getNext(entry);
+ if (entry) {
+ action(entry.value, entry.key);
+ }
+ }
+ }
+ function forEachIteration(iterator, action) {
+ if (iterator) {
+ for (var step = iterator.next(); !step.done; step = iterator.next()) {
+ action(step.value);
+ }
+ }
+ }
+ function createIteratorData(data, selector) {
+ return { current: data.head, selector: selector };
+ }
+ function iteratorNext(data) {
+ // Navigate to the next entry.
+ data.current = getNext(data.current);
+ if (data.current) {
+ return { value: data.selector(data.current.key, data.current.value), done: false };
+ }
+ else {
+ return { value: undefined, done: true };
+ }
+ }
+ /* @internal */
+ var ShimCollections;
+ (function (ShimCollections) {
+ function createMapShim(getIterator) {
+ var MapIterator = /** @class */ (function () {
+ function MapIterator(data, selector) {
+ this._data = createIteratorData(data, selector);
+ }
+ MapIterator.prototype.next = function () { return iteratorNext(this._data); };
+ return MapIterator;
+ }());
+ return /** @class */ (function () {
+ function Map(iterable) {
+ var _this = this;
+ this._mapData = createMapData();
+ forEachIteration(getIterator(iterable), function (_a) {
+ var key = _a[0], value = _a[1];
+ return _this.set(key, value);
+ });
}
- return false;
- };
- class_1.prototype.clear = function () {
- this.data = createDictionaryObject();
- this.size = 0;
- // Reset the linked list. Note that we must adjust the forward
- // references of the deleted entries to ensure iterators stuck
- // in the middle of the list don't continue with deleted entries,
- // but can continue with new entries added after the clear()
- // operation.
- var firstEntry = this.firstEntry;
- var currentEntry = firstEntry.nextEntry;
- while (currentEntry) {
- var nextEntry = currentEntry.nextEntry;
- currentEntry.previousEntry = undefined;
- currentEntry.nextEntry = firstEntry;
- currentEntry.skipNext = true;
- currentEntry = nextEntry;
- }
- firstEntry.nextEntry = undefined;
- this.lastEntry = firstEntry;
- };
- class_1.prototype.keys = function () {
- return new MapIterator(this.firstEntry, function (key) { return key; });
- };
- class_1.prototype.values = function () {
- return new MapIterator(this.firstEntry, function (_key, value) { return value; });
- };
- class_1.prototype.entries = function () {
- return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
- };
- class_1.prototype.forEach = function (action) {
- var iterator = this.entries();
- while (true) {
- var iterResult = iterator.next();
- if (iterResult.done) {
- break;
- }
- var _a = iterResult.value, key = _a[0], value = _a[1];
- action(value, key);
+ Object.defineProperty(Map.prototype, "size", {
+ get: function () { return this._mapData.size; },
+ enumerable: false,
+ configurable: true
+ });
+ Map.prototype.get = function (key) { var _a; return (_a = getEntry(this._mapData, key)) === null || _a === void 0 ? void 0 : _a.value; };
+ Map.prototype.set = function (key, value) { return addOrUpdateEntry(this._mapData, key, value), this; };
+ Map.prototype.has = function (key) { return !!getEntry(this._mapData, key); };
+ Map.prototype.delete = function (key) { return !!deleteEntry(this._mapData, key); };
+ Map.prototype.clear = function () { clearEntries(this._mapData); };
+ Map.prototype.keys = function () { return new MapIterator(this._mapData, function (key, _value) { return key; }); };
+ Map.prototype.values = function () { return new MapIterator(this._mapData, function (_key, value) { return value; }); };
+ Map.prototype.entries = function () { return new MapIterator(this._mapData, function (key, value) { return [key, value]; }); };
+ Map.prototype.forEach = function (action) { forEachEntry(this._mapData, action); };
+ return Map;
+ }());
+ }
+ ShimCollections.createMapShim = createMapShim;
+ function createSetShim(getIterator) {
+ var SetIterator = /** @class */ (function () {
+ function SetIterator(data, selector) {
+ this._data = createIteratorData(data, selector);
}
- };
- return class_1;
- }());
- }
- ts.createMapShim = createMapShim;
+ SetIterator.prototype.next = function () { return iteratorNext(this._data); };
+ return SetIterator;
+ }());
+ return /** @class */ (function () {
+ function Set(iterable) {
+ var _this = this;
+ this._mapData = createMapData();
+ forEachIteration(getIterator(iterable), function (value) { return _this.add(value); });
+ }
+ Object.defineProperty(Set.prototype, "size", {
+ get: function () { return this._mapData.size; },
+ enumerable: false,
+ configurable: true
+ });
+ Set.prototype.add = function (value) { return addOrUpdateEntry(this._mapData, value, value), this; };
+ Set.prototype.has = function (value) { return !!getEntry(this._mapData, value); };
+ Set.prototype.delete = function (value) { return !!deleteEntry(this._mapData, value); };
+ Set.prototype.clear = function () { clearEntries(this._mapData); };
+ Set.prototype.keys = function () { return new SetIterator(this._mapData, function (key, _value) { return key; }); };
+ Set.prototype.values = function () { return new SetIterator(this._mapData, function (_key, value) { return value; }); };
+ Set.prototype.entries = function () { return new SetIterator(this._mapData, function (key, value) { return [key, value]; }); };
+ Set.prototype.forEach = function (action) { forEachEntry(this._mapData, action); };
+ return Set;
+ }());
+ }
+ ShimCollections.createSetShim = createSetShim;
+ })(ShimCollections = ts.ShimCollections || (ts.ShimCollections = {}));
})(ts || (ts = {}));
var ts;
(function (ts) {
// WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
// If changing the text in this section, be sure to test `configurePrerelease` too.
- ts.versionMajorMinor = "3.9";
+ ts.versionMajorMinor = "4.5";
+ // The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
- ts.version = "3.9.5";
- /**
- * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
- */
- /* @internal */
- function tryGetNativeMap() {
- // eslint-disable-next-line no-in-operator
- return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
- }
- ts.tryGetNativeMap = tryGetNativeMap;
- /* @internal */
- ts.Map = tryGetNativeMap() || (function () {
- // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
- if (typeof ts.createMapShim === "function") {
- return ts.createMapShim();
- }
- throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
- })();
+ // eslint-disable-next-line @typescript-eslint/no-inferrable-types
+ ts.version = "4.5.2";
/* @internal */
var Comparison;
(function (Comparison) {
@@ -269,27 +302,68 @@ var ts;
Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
})(Comparison = ts.Comparison || (ts.Comparison = {}));
+ /* @internal */
+ var NativeCollections;
+ (function (NativeCollections) {
+ /**
+ * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
+ */
+ function tryGetNativeMap() {
+ // Internet Explorer's Map doesn't support iteration, so don't use it.
+ // eslint-disable-next-line no-in-operator
+ return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined;
+ }
+ NativeCollections.tryGetNativeMap = tryGetNativeMap;
+ /**
+ * Returns the native Set implementation if it is available and compatible (i.e. supports iteration).
+ */
+ function tryGetNativeSet() {
+ // Internet Explorer's Set doesn't support iteration, so don't use it.
+ // eslint-disable-next-line no-in-operator
+ return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined;
+ }
+ NativeCollections.tryGetNativeSet = tryGetNativeSet;
+ })(NativeCollections || (NativeCollections = {}));
+ /* @internal */
+ ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
+ /* @internal */
+ ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
+ /* @internal */
+ function getCollectionImplementation(name, nativeFactory, shimFactory) {
+ var _a;
+ // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
+ var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator);
+ if (constructor)
+ return constructor;
+ throw new Error("TypeScript requires an environment that provides a compatible native ".concat(name, " implementation."));
+ }
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
+ function getIterator(iterable) {
+ if (iterable) {
+ if (isArray(iterable))
+ return arrayIterator(iterable);
+ if (iterable instanceof ts.Map)
+ return iterable.entries();
+ if (iterable instanceof ts.Set)
+ return iterable.values();
+ throw new Error("Iteration not supported.");
+ }
+ }
+ ts.getIterator = getIterator;
ts.emptyArray = [];
- /** Create a new map. */
+ ts.emptyMap = new ts.Map();
+ ts.emptySet = new ts.Set();
function createMap() {
return new ts.Map();
}
ts.createMap = createMap;
- /** Create a new map from an array of entries. */
- function createMapFromEntries(entries) {
- var map = createMap();
- for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
- var _a = entries_1[_i], key = _a[0], value = _a[1];
- map.set(key, value);
- }
- return map;
- }
- ts.createMapFromEntries = createMapFromEntries;
- /** Create a new map from a template object is provided, the map will copy entries from it. */
+ /**
+ * Create a new map from a template object is provided, the map will copy entries from it.
+ * @deprecated Use `new Map(getEntries(template))` instead.
+ */
function createMapFromTemplate(template) {
var map = new ts.Map();
// Copies keys/values from template. Note that for..in will not throw if
@@ -365,6 +439,16 @@ var ts;
}
}
ts.firstDefinedIterator = firstDefinedIterator;
+ function reduceLeftIterator(iterator, f, initial) {
+ var result = initial;
+ if (iterator) {
+ for (var step = iterator.next(), pos = 0; !step.done; step = iterator.next(), pos++) {
+ result = f(result, step.value, pos);
+ }
+ }
+ return result;
+ }
+ ts.reduceLeftIterator = reduceLeftIterator;
function zipWith(arrayA, arrayB, callback) {
var result = [];
ts.Debug.assertEqual(arrayA.length, arrayB.length);
@@ -390,13 +474,30 @@ var ts;
ts.zipToIterator = zipToIterator;
function zipToMap(keys, values) {
ts.Debug.assert(keys.length === values.length);
- var map = createMap();
+ var map = new ts.Map();
for (var i = 0; i < keys.length; ++i) {
map.set(keys[i], values[i]);
}
return map;
}
ts.zipToMap = zipToMap;
+ /**
+ * Creates a new array with `element` interspersed in between each element of `input`
+ * if there is more than 1 value in `input`. Otherwise, returns the existing array.
+ */
+ function intersperse(input, element) {
+ if (input.length <= 1) {
+ return input;
+ }
+ var result = [];
+ for (var i = 0, n = input.length; i < n; i++) {
+ if (i)
+ result.push(element);
+ result.push(input[i]);
+ }
+ return result;
+ }
+ ts.intersperse = intersperse;
/**
* Iterates through `array` by index and performs the callback on each element of array until the callback
* returns a falsey value, then returns false.
@@ -735,18 +836,53 @@ var ts;
};
}
ts.mapDefinedIterator = mapDefinedIterator;
- function mapDefinedMap(map, mapValue, mapKey) {
- if (mapKey === void 0) { mapKey = identity; }
- var result = createMap();
+ function mapDefinedEntries(map, f) {
+ if (!map) {
+ return undefined;
+ }
+ var result = new ts.Map();
map.forEach(function (value, key) {
- var mapped = mapValue(value, key);
- if (mapped !== undefined) {
- result.set(mapKey(key), mapped);
+ var entry = f(key, value);
+ if (entry !== undefined) {
+ var newKey = entry[0], newValue = entry[1];
+ if (newKey !== undefined && newValue !== undefined) {
+ result.set(newKey, newValue);
+ }
}
});
return result;
}
- ts.mapDefinedMap = mapDefinedMap;
+ ts.mapDefinedEntries = mapDefinedEntries;
+ function mapDefinedValues(set, f) {
+ if (set) {
+ var result_1 = new ts.Set();
+ set.forEach(function (value) {
+ var newValue = f(value);
+ if (newValue !== undefined) {
+ result_1.add(newValue);
+ }
+ });
+ return result_1;
+ }
+ }
+ ts.mapDefinedValues = mapDefinedValues;
+ function getOrUpdate(map, key, callback) {
+ if (map.has(key)) {
+ return map.get(key);
+ }
+ var value = callback();
+ map.set(key, value);
+ return value;
+ }
+ ts.getOrUpdate = getOrUpdate;
+ function tryAddToSet(set, value) {
+ if (!set.has(value)) {
+ set.add(value);
+ return true;
+ }
+ return false;
+ }
+ ts.tryAddToSet = tryAddToSet;
ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
function singleIterator(value) {
var done = false;
@@ -798,7 +934,7 @@ var ts;
if (!map) {
return undefined;
}
- var result = createMap();
+ var result = new ts.Map();
map.forEach(function (value, key) {
var _a = f(key, value), newKey = _a[0], newValue = _a[1];
result.set(newKey, newValue);
@@ -846,7 +982,7 @@ var ts;
return array1;
if (!some(array1))
return array2;
- return __spreadArrays(array1, array2);
+ return __spreadArray(__spreadArray([], array1, true), array2, true);
}
ts.concatenate = concatenate;
function selectIndex(_, i) {
@@ -936,6 +1072,20 @@ var ts;
return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
}
ts.sortAndDeduplicate = sortAndDeduplicate;
+ function arrayIsSorted(array, comparer) {
+ if (array.length < 2)
+ return true;
+ var prevElement = array[0];
+ for (var _i = 0, _a = array.slice(1); _i < _a.length; _i++) {
+ var element = _a[_i];
+ if (comparer(prevElement, element) === 1 /* GreaterThan */) {
+ return false;
+ }
+ prevElement = element;
+ }
+ return true;
+ }
+ ts.arrayIsSorted = arrayIsSorted;
function arrayIsEqualTo(array1, array2, equalityComparer) {
if (equalityComparer === void 0) { equalityComparer = equateValues; }
if (!array1 || !array2) {
@@ -1240,7 +1390,7 @@ var ts;
var high = array.length - 1;
while (low <= high) {
var middle = low + ((high - low) >> 1);
- var midKey = keySelector(array[middle]);
+ var midKey = keySelector(array[middle], middle);
switch (keyComparer(midKey, key)) {
case -1 /* LessThan */:
low = middle + 1;
@@ -1335,6 +1485,26 @@ var ts;
return values;
}
ts.getOwnValues = getOwnValues;
+ var _entries = Object.entries || (function (obj) {
+ var keys = getOwnKeys(obj);
+ var result = Array(keys.length);
+ for (var i = 0; i < keys.length; i++) {
+ result[i] = [keys[i], obj[keys[i]]];
+ }
+ return result;
+ });
+ function getEntries(obj) {
+ return obj ? _entries(obj) : [];
+ }
+ ts.getEntries = getEntries;
+ function arrayOf(count, f) {
+ var result = new Array(count);
+ for (var i = 0; i < count; i++) {
+ result[i] = f(i);
+ }
+ return result;
+ }
+ ts.arrayOf = arrayOf;
function arrayFrom(iterator, map) {
var result = [];
for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
@@ -1392,7 +1562,7 @@ var ts;
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
if (makeValue === void 0) { makeValue = identity; }
- var result = createMap();
+ var result = new ts.Map();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
var key = makeKey(value);
@@ -1469,14 +1639,8 @@ var ts;
return fn ? fn.bind(obj) : undefined;
}
ts.maybeBind = maybeBind;
- function mapMap(map, f) {
- var result = createMap();
- map.forEach(function (t, key) { return result.set.apply(result, (f(t, key))); });
- return result;
- }
- ts.mapMap = mapMap;
function createMultiMap() {
- var map = createMap();
+ var map = new ts.Map();
map.add = multiMapAdd;
map.remove = multiMapRemove;
return map;
@@ -1534,26 +1698,36 @@ var ts;
function cast(value, test) {
if (value !== undefined && test(value))
return value;
- return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
+ return ts.Debug.fail("Invalid cast. The supplied value ".concat(value, " did not pass the test '").concat(ts.Debug.getFunctionName(test), "'."));
}
ts.cast = cast;
/** Does nothing. */
function noop(_) { }
ts.noop = noop;
/** Do nothing and return false */
- function returnFalse() { return false; }
+ function returnFalse() {
+ return false;
+ }
ts.returnFalse = returnFalse;
/** Do nothing and return true */
- function returnTrue() { return true; }
+ function returnTrue() {
+ return true;
+ }
ts.returnTrue = returnTrue;
/** Do nothing and return undefined */
- function returnUndefined() { return undefined; }
+ function returnUndefined() {
+ return undefined;
+ }
ts.returnUndefined = returnUndefined;
/** Returns its argument. */
- function identity(x) { return x; }
+ function identity(x) {
+ return x;
+ }
ts.identity = identity;
/** Returns lower case string */
- function toLowerCase(x) { return x.toLowerCase(); }
+ function toLowerCase(x) {
+ return x.toLowerCase();
+ }
ts.toLowerCase = toLowerCase;
// We convert the file names to lower case as key for file name on case insensitive file system
// While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
@@ -1564,7 +1738,7 @@ var ts;
// | 1. | i | 105 | Ascii i |
// | 2. | I | 73 | Ascii I |
// |-------- Special characters ------------------------------------------------------------------------|
- // | 3. | \u0130 | 304 | Uppper case I with dot above |
+ // | 3. | \u0130 | 304 | Upper case I with dot above |
// | 4. | i,\u0307 | 105,775 | i, followed by 775: Lower case of (3rd item) |
// | 5. | I,\u0307 | 73,775 | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
// | 6. | \u0131 | 305 | Lower case i without dot, upper case is I (2nd item) |
@@ -1611,6 +1785,20 @@ var ts;
};
}
ts.memoize = memoize;
+ /** A version of `memoize` that supports a single primitive argument */
+ function memoizeOne(callback) {
+ var map = new ts.Map();
+ return function (arg) {
+ var key = "".concat(typeof arg, ":").concat(arg);
+ var value = map.get(key);
+ if (value === undefined && !map.has(key)) {
+ value = callback(arg);
+ map.set(key, value);
+ }
+ return value;
+ };
+ }
+ ts.memoizeOne = memoizeOne;
function compose(a, b, c, d, e) {
if (!!e) {
var args_2 = [];
@@ -1708,7 +1896,7 @@ var ts;
* 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)).
+ * lowercase (such as `áº` (German sharp capital s)).
*/
function compareStringsCaseInsensitive(a, b) {
if (a === b)
@@ -1780,7 +1968,7 @@ var ts;
//
// 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)).
+ // 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);
@@ -1860,11 +2048,9 @@ var ts;
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.
+ * Names less than length 3 only check for case-insensitive equality.
*
- * 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,
+ * find 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.
@@ -1874,42 +2060,27 @@ var ts;
*/
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; // If the best result isn't better than this, don't bother.
+ var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother.
var bestCandidate;
- var justCheckExactMatches = false;
- var nameLowerCase = name.toLowerCase();
for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
var candidate = candidates_1[_i];
var candidateName = getName(candidate);
- if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
- var candidateNameLowerCase = candidateName.toLowerCase();
- if (candidateNameLowerCase === nameLowerCase) {
- if (candidateName === name) {
- continue;
- }
- return candidate;
- }
- if (justCheckExactMatches) {
+ if (candidateName !== undefined && Math.abs(candidateName.length - name.length) <= maximumLengthDifference) {
+ if (candidateName === name) {
continue;
}
- if (candidateName.length < 3) {
- // Don't bother, user would have noticed a 2-character name having an extra character
+ // Only consider candidates less than 3 characters long when they differ by case.
+ // Otherwise, don't bother, since a user would usually notice differences of a 2-character name.
+ if (candidateName.length < 3 && candidateName.toLowerCase() !== name.toLowerCase()) {
continue;
}
- // Only care about a result better than the best so far.
- var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
+ var distance = levenshteinWithMax(name, candidateName, bestDistance - 0.1);
if (distance === undefined) {
continue;
}
- if (distance < 3) {
- justCheckExactMatches = true;
- bestCandidate = candidate;
- }
- else {
- ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
- bestDistance = distance;
- bestCandidate = candidate;
- }
+ ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
+ bestDistance = distance;
+ bestCandidate = candidate;
}
}
return bestCandidate;
@@ -1919,14 +2090,14 @@ var ts;
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;
+ var big = max + 0.01;
for (var i = 0; i <= s2.length; i++) {
previous[i] = i;
}
for (var i = 1; i <= s1.length; i++) {
var c1 = s1.charCodeAt(i - 1);
- var minJ = i > max ? i - max : 1;
- var maxJ = s2.length > max + i ? max + i : s2.length;
+ var minJ = Math.ceil(i > max ? i - max : 1);
+ var maxJ = Math.floor(s2.length > max + i ? max + i : s2.length);
current[0] = i;
/** Smallest value of the matrix in the ith column. */
var colMin = i;
@@ -1934,9 +2105,13 @@ var ts;
current[j] = big;
}
for (var j = minJ; j <= maxJ; j++) {
+ // case difference should be significantly cheaper than other differences
+ var substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase()
+ ? (previous[j - 1] + 0.1)
+ : (previous[j - 1] + 2);
var dist = c1 === s2.charCodeAt(j - 1)
? previous[j - 1]
- : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
+ : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ substitutionDistance);
current[j] = dist;
colMin = Math.min(colMin, dist);
}
@@ -1975,10 +2150,46 @@ var ts;
* 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, "");
+ // We used to use the regex /[.-]((min)|(\d+(\.\d+)*))$/ and would just .replace it twice.
+ // Unfortunately, that regex has O(n^2) performance because v8 doesn't match from the end of the string.
+ // Instead, we now essentially scan the filename (backwards) ourselves.
+ var end = fileName.length;
+ for (var pos = end - 1; pos > 0; pos--) {
+ var ch = fileName.charCodeAt(pos);
+ if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
+ // Match a \d+ segment
+ do {
+ --pos;
+ ch = fileName.charCodeAt(pos);
+ } while (pos > 0 && ch >= 48 /* _0 */ && ch <= 57 /* _9 */);
+ }
+ else if (pos > 4 && (ch === 110 /* n */ || ch === 78 /* N */)) {
+ // Looking for "min" or "min"
+ // Already matched the 'n'
+ --pos;
+ ch = fileName.charCodeAt(pos);
+ if (ch !== 105 /* i */ && ch !== 73 /* I */) {
+ break;
+ }
+ --pos;
+ ch = fileName.charCodeAt(pos);
+ if (ch !== 109 /* m */ && ch !== 77 /* M */) {
+ break;
+ }
+ --pos;
+ ch = fileName.charCodeAt(pos);
+ }
+ else {
+ // This character is not part of either suffix pattern
+ break;
+ }
+ if (ch !== 45 /* minus */ && ch !== 46 /* dot */) {
+ break;
+ }
+ end = pos;
+ }
+ // end might be fileName.length, in which case this should internally no-op
+ return end === fileName.length ? fileName : fileName.slice(0, end);
}
ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
/** Remove an item from an array, moving everything to its right one space left. */
@@ -2028,7 +2239,7 @@ var ts;
ts.createGetCanonicalFileName = createGetCanonicalFileName;
function patternText(_a) {
var prefix = _a.prefix, suffix = _a.suffix;
- return prefix + "*" + suffix;
+ return "".concat(prefix, "*").concat(suffix);
}
ts.patternText = patternText;
/**
@@ -2121,6 +2332,7 @@ var ts;
var oldIndex = 0;
var newLen = newItems.length;
var oldLen = oldItems.length;
+ var hasChanges = false;
while (newIndex < newLen && oldIndex < oldLen) {
var newItem = newItems[newIndex];
var oldItem = oldItems[oldIndex];
@@ -2128,10 +2340,12 @@ var ts;
if (compareResult === -1 /* LessThan */) {
inserted(newItem);
newIndex++;
+ hasChanges = true;
}
else if (compareResult === 1 /* GreaterThan */) {
deleted(oldItem);
oldIndex++;
+ hasChanges = true;
}
else {
unchanged(oldItem, newItem);
@@ -2141,10 +2355,13 @@ var ts;
}
while (newIndex < newLen) {
inserted(newItems[newIndex++]);
+ hasChanges = true;
}
while (oldIndex < oldLen) {
deleted(oldItems[oldIndex++]);
+ hasChanges = true;
}
+ return hasChanges;
}
ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
function fill(length, cb) {
@@ -2180,29 +2397,120 @@ var ts;
}
}
}
- function padLeft(s, length) {
- while (s.length < length) {
- s = " " + s;
- }
- return s;
+ /**
+ * Returns string left-padded with spaces or zeros until it reaches the given length.
+ *
+ * @param s String to pad.
+ * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
+ * @param padString Character to use as padding (default " ").
+ */
+ function padLeft(s, length, padString) {
+ if (padString === void 0) { padString = " "; }
+ return length <= s.length ? s : padString.repeat(length - s.length) + s;
}
ts.padLeft = padLeft;
- function padRight(s, length) {
- while (s.length < length) {
- s = s + " ";
- }
- return s;
+ /**
+ * Returns string right-padded with spaces until it reaches the given length.
+ *
+ * @param s String to pad.
+ * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
+ * @param padString Character to use as padding (default " ").
+ */
+ function padRight(s, length, padString) {
+ if (padString === void 0) { padString = " "; }
+ return length <= s.length ? s : s + padString.repeat(length - s.length);
}
ts.padRight = padRight;
+ function takeWhile(array, predicate) {
+ var len = array.length;
+ var index = 0;
+ while (index < len && predicate(array[index])) {
+ index++;
+ }
+ return array.slice(0, index);
+ }
+ ts.takeWhile = takeWhile;
+ /**
+ * Removes the leading and trailing white space and line terminator characters from a string.
+ */
+ ts.trimString = !!String.prototype.trim ? (function (s) { return s.trim(); }) : function (s) { return ts.trimStringEnd(ts.trimStringStart(s)); };
+ /**
+ * Returns a copy with trailing whitespace removed.
+ */
+ ts.trimStringEnd = !!String.prototype.trimEnd ? (function (s) { return s.trimEnd(); }) : trimEndImpl;
+ /**
+ * Returns a copy with leading whitespace removed.
+ */
+ ts.trimStringStart = !!String.prototype.trimStart ? (function (s) { return s.trimStart(); }) : function (s) { return s.replace(/^\s+/g, ""); };
+ /**
+ * https://jsbench.me/gjkoxld4au/1
+ * The simple regex for this, /\s+$/g is O(n^2) in v8.
+ * The native .trimEnd method is by far best, but since that's technically ES2019,
+ * we provide a (still much faster than the simple regex) fallback.
+ */
+ function trimEndImpl(s) {
+ var end = s.length - 1;
+ while (end >= 0) {
+ if (!ts.isWhiteSpaceLike(s.charCodeAt(end)))
+ break;
+ end--;
+ }
+ return s.slice(0, end + 1);
+ }
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
+ var LogLevel;
+ (function (LogLevel) {
+ LogLevel[LogLevel["Off"] = 0] = "Off";
+ LogLevel[LogLevel["Error"] = 1] = "Error";
+ LogLevel[LogLevel["Warning"] = 2] = "Warning";
+ LogLevel[LogLevel["Info"] = 3] = "Info";
+ LogLevel[LogLevel["Verbose"] = 4] = "Verbose";
+ })(LogLevel = ts.LogLevel || (ts.LogLevel = {}));
var Debug;
(function (Debug) {
+ var typeScriptVersion;
+ /* eslint-disable prefer-const */
var currentAssertionLevel = 0 /* None */;
- // eslint-disable-next-line prefer-const
+ Debug.currentLogLevel = LogLevel.Warning;
Debug.isDebugging = false;
+ function getTypeScriptVersion() {
+ return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version));
+ }
+ Debug.getTypeScriptVersion = getTypeScriptVersion;
+ function shouldLog(level) {
+ return Debug.currentLogLevel <= level;
+ }
+ Debug.shouldLog = shouldLog;
+ function logMessage(level, s) {
+ if (Debug.loggingHost && shouldLog(level)) {
+ Debug.loggingHost.log(level, s);
+ }
+ }
+ function log(s) {
+ logMessage(LogLevel.Info, s);
+ }
+ Debug.log = log;
+ (function (log_1) {
+ function error(s) {
+ logMessage(LogLevel.Error, s);
+ }
+ log_1.error = error;
+ function warn(s) {
+ logMessage(LogLevel.Warning, s);
+ }
+ log_1.warn = warn;
+ function log(s) {
+ logMessage(LogLevel.Info, s);
+ }
+ log_1.log = log;
+ function trace(s) {
+ logMessage(LogLevel.Verbose, s);
+ }
+ log_1.trace = trace;
+ })(log = Debug.log || (Debug.log = {}));
var assertionCache = {};
function getAssertionLevel() {
return currentAssertionLevel;
@@ -2244,7 +2552,7 @@ var ts;
}
function fail(message, stackCrawlMark) {
debugger;
- var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
+ var e = new Error(message ? "Debug Failure. ".concat(message) : "Debug Failure.");
if (Error.captureStackTrace) {
Error.captureStackTrace(e, stackCrawlMark || fail);
}
@@ -2252,12 +2560,12 @@ var ts;
}
Debug.fail = fail;
function failBadSyntaxKind(node, message, stackCrawlMark) {
- return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
+ return fail("".concat(message || "Unexpected node.", "\r\nNode ").concat(formatSyntaxKind(node.kind), " was unexpected."), stackCrawlMark || failBadSyntaxKind);
}
Debug.failBadSyntaxKind = failBadSyntaxKind;
function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
if (!expression) {
- message = message ? "False expression: " + message : "False expression.";
+ message = message ? "False expression: ".concat(message) : "False expression.";
if (verboseDebugInfo) {
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
}
@@ -2267,26 +2575,26 @@ var ts;
Debug.assert = assert;
function assertEqual(a, b, msg, msg2, stackCrawlMark) {
if (a !== b) {
- var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
- fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
+ var message = msg ? msg2 ? "".concat(msg, " ").concat(msg2) : msg : "";
+ fail("Expected ".concat(a, " === ").concat(b, ". ").concat(message), stackCrawlMark || assertEqual);
}
}
Debug.assertEqual = assertEqual;
function assertLessThan(a, b, msg, stackCrawlMark) {
if (a >= b) {
- fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
+ fail("Expected ".concat(a, " < ").concat(b, ". ").concat(msg || ""), stackCrawlMark || assertLessThan);
}
}
Debug.assertLessThan = assertLessThan;
function assertLessThanOrEqual(a, b, stackCrawlMark) {
if (a > b) {
- fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
+ fail("Expected ".concat(a, " <= ").concat(b), stackCrawlMark || assertLessThanOrEqual);
}
}
Debug.assertLessThanOrEqual = assertLessThanOrEqual;
function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
if (a < b) {
- fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
+ fail("Expected ".concat(a, " >= ").concat(b), stackCrawlMark || assertGreaterThanOrEqual);
}
}
Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
@@ -2327,45 +2635,47 @@ var ts;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
- return fail(message + " " + detail, stackCrawlMark || assertNever);
+ return fail("".concat(message, " ").concat(detail), stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
function assertEachNode(nodes, test, message, stackCrawlMark) {
if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
- assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
+ assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '".concat(getFunctionName(test), "'."); }, stackCrawlMark || assertEachNode);
}
}
Debug.assertEachNode = assertEachNode;
function assertNode(node, test, message, stackCrawlMark) {
if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
- assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
+ assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " did not pass test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertNode);
}
}
Debug.assertNode = assertNode;
function assertNotNode(node, test, message, stackCrawlMark) {
if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
- assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNotNode);
+ assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node.kind), " should not have passed test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertNotNode);
}
}
Debug.assertNotNode = assertNotNode;
function assertOptionalNode(node, test, message, stackCrawlMark) {
if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
- assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
+ assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " did not pass test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertOptionalNode);
}
}
Debug.assertOptionalNode = assertOptionalNode;
function assertOptionalToken(node, kind, message, stackCrawlMark) {
if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
- assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, stackCrawlMark || assertOptionalToken);
+ assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " was not a '").concat(formatSyntaxKind(kind), "' token."); }, stackCrawlMark || assertOptionalToken);
}
}
Debug.assertOptionalToken = assertOptionalToken;
function assertMissingNode(node, message, stackCrawlMark) {
if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
- assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
+ assert(node === undefined, message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node.kind), " was unexpected'."); }, stackCrawlMark || assertMissingNode);
}
}
Debug.assertMissingNode = assertMissingNode;
+ function type(_value) { }
+ Debug.type = type;
function getFunctionName(func) {
if (typeof func !== "function") {
return "";
@@ -2381,7 +2691,7 @@ var ts;
}
Debug.getFunctionName = getFunctionName;
function formatSymbol(symbol) {
- return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
+ return "{ name: ".concat(ts.unescapeLeadingUnderscores(symbol.escapedName), "; flags: ").concat(formatSymbolFlags(symbol.flags), "; declarations: ").concat(ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }), " }");
}
Debug.formatSymbol = formatSymbol;
/**
@@ -2402,7 +2712,7 @@ var ts;
break;
}
if (enumValue !== 0 && enumValue & value) {
- result = "" + result + (result ? "|" : "") + enumName;
+ result = "".concat(result).concat(result ? "|" : "").concat(enumName);
remainingFlags &= ~enumValue;
}
}
@@ -2435,6 +2745,10 @@ var ts;
return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
}
Debug.formatSyntaxKind = formatSyntaxKind;
+ function formatSnippetKind(kind) {
+ return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false);
+ }
+ Debug.formatSnippetKind = formatSnippetKind;
function formatNodeFlags(flags) {
return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
}
@@ -2459,10 +2773,18 @@ var ts;
return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
}
Debug.formatTypeFlags = formatTypeFlags;
+ function formatSignatureFlags(flags) {
+ return formatEnum(flags, ts.SignatureFlags, /*isFlags*/ true);
+ }
+ Debug.formatSignatureFlags = formatSignatureFlags;
function formatObjectFlags(flags) {
return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
}
Debug.formatObjectFlags = formatObjectFlags;
+ function formatFlowFlags(flags) {
+ return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true);
+ }
+ Debug.formatFlowFlags = formatFlowFlags;
var isDebugInfoEnabled = false;
var extendedDebugModule;
function extendedDebug() {
@@ -2480,31 +2802,174 @@ var ts;
return extendedDebug().formatControlFlowGraph(flowNode);
}
Debug.formatControlFlowGraph = formatControlFlowGraph;
+ var flowNodeProto;
+ function attachFlowNodeDebugInfoWorker(flowNode) {
+ if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
+ Object.defineProperties(flowNode, {
+ // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
+ __tsDebuggerDisplay: {
+ value: function () {
+ var flowHeader = this.flags & 2 /* Start */ ? "FlowStart" :
+ this.flags & 4 /* BranchLabel */ ? "FlowBranchLabel" :
+ this.flags & 8 /* LoopLabel */ ? "FlowLoopLabel" :
+ this.flags & 16 /* Assignment */ ? "FlowAssignment" :
+ this.flags & 32 /* TrueCondition */ ? "FlowTrueCondition" :
+ this.flags & 64 /* FalseCondition */ ? "FlowFalseCondition" :
+ this.flags & 128 /* SwitchClause */ ? "FlowSwitchClause" :
+ this.flags & 256 /* ArrayMutation */ ? "FlowArrayMutation" :
+ this.flags & 512 /* Call */ ? "FlowCall" :
+ this.flags & 1024 /* ReduceLabel */ ? "FlowReduceLabel" :
+ this.flags & 1 /* Unreachable */ ? "FlowUnreachable" :
+ "UnknownFlow";
+ var remainingFlags = this.flags & ~(2048 /* Referenced */ - 1);
+ return "".concat(flowHeader).concat(remainingFlags ? " (".concat(formatFlowFlags(remainingFlags), ")") : "");
+ }
+ },
+ __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
+ __debugToString: { value: function () { return formatControlFlowGraph(this); } }
+ });
+ }
+ }
function attachFlowNodeDebugInfo(flowNode) {
if (isDebugInfoEnabled) {
- if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
- Object.defineProperties(flowNode, {
- __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
- __debugToString: { value: function () { return formatControlFlowGraph(this); } }
- });
+ if (typeof Object.setPrototypeOf === "function") {
+ // if we're in es2015, attach the method to a shared prototype for `FlowNode`
+ // so the method doesn't show up in the watch window.
+ if (!flowNodeProto) {
+ flowNodeProto = Object.create(Object.prototype);
+ attachFlowNodeDebugInfoWorker(flowNodeProto);
+ }
+ Object.setPrototypeOf(flowNode, flowNodeProto);
+ }
+ else {
+ // not running in an es2015 environment, attach the method directly.
+ attachFlowNodeDebugInfoWorker(flowNode);
}
}
}
Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
+ var nodeArrayProto;
+ function attachNodeArrayDebugInfoWorker(array) {
+ if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator
+ Object.defineProperties(array, {
+ __tsDebuggerDisplay: {
+ value: function (defaultValue) {
+ // An `Array` with extra properties is rendered as `[A, B, prop1: 1, prop2: 2]`. Most of
+ // these aren't immediately useful so we trim off the `prop1: ..., prop2: ...` part from the
+ // formatted string.
+ // This regex can trigger slow backtracking because of overlapping potential captures.
+ // We don't care, this is debug code that's only enabled with a debugger attached -
+ // we're just taking note of it for anyone checking regex performance in the future.
+ defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]");
+ return "NodeArray ".concat(defaultValue);
+ }
+ }
+ });
+ }
+ }
+ function attachNodeArrayDebugInfo(array) {
+ if (isDebugInfoEnabled) {
+ if (typeof Object.setPrototypeOf === "function") {
+ // if we're in es2015, attach the method to a shared prototype for `NodeArray`
+ // so the method doesn't show up in the watch window.
+ if (!nodeArrayProto) {
+ nodeArrayProto = Object.create(Array.prototype);
+ attachNodeArrayDebugInfoWorker(nodeArrayProto);
+ }
+ Object.setPrototypeOf(array, nodeArrayProto);
+ }
+ else {
+ // not running in an es2015 environment, attach the method directly.
+ attachNodeArrayDebugInfoWorker(array);
+ }
+ }
+ }
+ Debug.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo;
/**
* Injects debug information into frequently used types.
*/
function enableDebugInfo() {
if (isDebugInfoEnabled)
return;
+ // avoid recomputing
+ var weakTypeTextMap;
+ var weakNodeTextMap;
+ function getWeakTypeTextMap() {
+ if (weakTypeTextMap === undefined) {
+ if (typeof WeakMap === "function")
+ weakTypeTextMap = new WeakMap();
+ }
+ return weakTypeTextMap;
+ }
+ function getWeakNodeTextMap() {
+ if (weakNodeTextMap === undefined) {
+ if (typeof WeakMap === "function")
+ weakNodeTextMap = new WeakMap();
+ }
+ return weakNodeTextMap;
+ }
// Add additional properties in debug mode to assist with debugging.
Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
+ // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
+ __tsDebuggerDisplay: {
+ value: function () {
+ var symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" :
+ "Symbol";
+ var remainingSymbolFlags = this.flags & ~33554432 /* Transient */;
+ return "".concat(symbolHeader, " '").concat(ts.symbolName(this), "'").concat(remainingSymbolFlags ? " (".concat(formatSymbolFlags(remainingSymbolFlags), ")") : "");
+ }
+ },
__debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
});
Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
+ // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
+ __tsDebuggerDisplay: {
+ value: function () {
+ var typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" :
+ this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType ".concat(JSON.stringify(this.value)) :
+ this.flags & 2048 /* BigIntLiteral */ ? "LiteralType ".concat(this.value.negative ? "-" : "").concat(this.value.base10Value, "n") :
+ this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" :
+ this.flags & 32 /* Enum */ ? "EnumType" :
+ this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType ".concat(this.intrinsicName) :
+ this.flags & 1048576 /* Union */ ? "UnionType" :
+ this.flags & 2097152 /* Intersection */ ? "IntersectionType" :
+ this.flags & 4194304 /* Index */ ? "IndexType" :
+ this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" :
+ this.flags & 16777216 /* Conditional */ ? "ConditionalType" :
+ this.flags & 33554432 /* Substitution */ ? "SubstitutionType" :
+ this.flags & 262144 /* TypeParameter */ ? "TypeParameter" :
+ this.flags & 524288 /* Object */ ?
+ this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" :
+ this.objectFlags & 4 /* Reference */ ? "TypeReference" :
+ this.objectFlags & 8 /* Tuple */ ? "TupleType" :
+ this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" :
+ this.objectFlags & 32 /* Mapped */ ? "MappedType" :
+ this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" :
+ this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" :
+ "ObjectType" :
+ "Type";
+ var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0;
+ return "".concat(typeHeader).concat(this.symbol ? " '".concat(ts.symbolName(this.symbol), "'") : "").concat(remainingObjectFlags ? " (".concat(formatObjectFlags(remainingObjectFlags), ")") : "");
+ }
+ },
__debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
__debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
- __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
+ __debugTypeToString: {
+ value: function () {
+ // avoid recomputing
+ var map = getWeakTypeTextMap();
+ var text = map === null || map === void 0 ? void 0 : map.get(this);
+ if (text === undefined) {
+ text = this.checker.typeToString(this);
+ map === null || map === void 0 ? void 0 : map.set(this, text);
+ }
+ return text;
+ }
+ },
+ });
+ Object.defineProperties(ts.objectAllocator.getSignatureConstructor().prototype, {
+ __debugFlags: { get: function () { return formatSignatureFlags(this.flags); } },
+ __debugSignatureToString: { value: function () { var _a; return (_a = this.checker) === null || _a === void 0 ? void 0 : _a.signatureToString(this); } }
});
var nodeConstructors = [
ts.objectAllocator.getNodeConstructor(),
@@ -2516,9 +2981,52 @@ var ts;
var ctor = nodeConstructors_1[_i];
if (!ctor.prototype.hasOwnProperty("__debugKind")) {
Object.defineProperties(ctor.prototype, {
+ // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
+ __tsDebuggerDisplay: {
+ value: function () {
+ var nodeHeader = ts.isGeneratedIdentifier(this) ? "GeneratedIdentifier" :
+ ts.isIdentifier(this) ? "Identifier '".concat(ts.idText(this), "'") :
+ ts.isPrivateIdentifier(this) ? "PrivateIdentifier '".concat(ts.idText(this), "'") :
+ ts.isStringLiteral(this) ? "StringLiteral ".concat(JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...")) :
+ ts.isNumericLiteral(this) ? "NumericLiteral ".concat(this.text) :
+ ts.isBigIntLiteral(this) ? "BigIntLiteral ".concat(this.text, "n") :
+ ts.isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" :
+ ts.isParameter(this) ? "ParameterDeclaration" :
+ ts.isConstructorDeclaration(this) ? "ConstructorDeclaration" :
+ ts.isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" :
+ ts.isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" :
+ ts.isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" :
+ ts.isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" :
+ ts.isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" :
+ ts.isTypePredicateNode(this) ? "TypePredicateNode" :
+ ts.isTypeReferenceNode(this) ? "TypeReferenceNode" :
+ ts.isFunctionTypeNode(this) ? "FunctionTypeNode" :
+ ts.isConstructorTypeNode(this) ? "ConstructorTypeNode" :
+ ts.isTypeQueryNode(this) ? "TypeQueryNode" :
+ ts.isTypeLiteralNode(this) ? "TypeLiteralNode" :
+ ts.isArrayTypeNode(this) ? "ArrayTypeNode" :
+ ts.isTupleTypeNode(this) ? "TupleTypeNode" :
+ ts.isOptionalTypeNode(this) ? "OptionalTypeNode" :
+ ts.isRestTypeNode(this) ? "RestTypeNode" :
+ ts.isUnionTypeNode(this) ? "UnionTypeNode" :
+ ts.isIntersectionTypeNode(this) ? "IntersectionTypeNode" :
+ ts.isConditionalTypeNode(this) ? "ConditionalTypeNode" :
+ ts.isInferTypeNode(this) ? "InferTypeNode" :
+ ts.isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" :
+ ts.isThisTypeNode(this) ? "ThisTypeNode" :
+ ts.isTypeOperatorNode(this) ? "TypeOperatorNode" :
+ ts.isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" :
+ ts.isMappedTypeNode(this) ? "MappedTypeNode" :
+ ts.isLiteralTypeNode(this) ? "LiteralTypeNode" :
+ ts.isNamedTupleMember(this) ? "NamedTupleMember" :
+ ts.isImportTypeNode(this) ? "ImportTypeNode" :
+ formatSyntaxKind(this.kind);
+ return "".concat(nodeHeader).concat(this.flags ? " (".concat(formatNodeFlags(this.flags), ")") : "");
+ }
+ },
__debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
__debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
- __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
+ __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getEffectiveModifierFlagsNoCache(this)); } },
__debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
__debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
__debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
@@ -2526,9 +3034,16 @@ var ts;
value: function (includeTrivia) {
if (ts.nodeIsSynthesized(this))
return "";
- var parseNode = ts.getParseTreeNode(this);
- var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
- return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
+ // avoid recomputing
+ var map = getWeakNodeTextMap();
+ var text = map === null || map === void 0 ? void 0 : map.get(this);
+ if (text === undefined) {
+ var parseNode = ts.getParseTreeNode(this);
+ var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
+ text = sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
+ map === null || map === void 0 ? void 0 : map.set(this, text);
+ }
+ return text;
}
}
});
@@ -2551,167 +3066,54 @@ var ts;
isDebugInfoEnabled = true;
}
Debug.enableDebugInfo = enableDebugInfo;
- })(Debug = ts.Debug || (ts.Debug = {}));
-})(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. */
-var ts;
-(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;
- function createTimerIf(condition, measureName, startMarkName, endMarkName) {
- return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
+ function formatDeprecationMessage(name, error, errorAfter, since, message) {
+ var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
+ deprecationMessage += "'".concat(name, "' ");
+ deprecationMessage += since ? "has been deprecated since v".concat(since) : "is deprecated";
+ deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v".concat(errorAfter, ".") : ".";
+ deprecationMessage += message ? " ".concat(ts.formatStringFromArgs(message, [name], 0)) : "";
+ return deprecationMessage;
}
- performance.createTimerIf = createTimerIf;
- function createTimer(measureName, startMarkName, endMarkName) {
- var enterCount = 0;
- return {
- enter: enter,
- exit: exit
+ function createErrorDeprecation(name, errorAfter, since, message) {
+ var deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
+ return function () {
+ throw new TypeError(deprecationMessage);
};
- function enter() {
- if (++enterCount === 1) {
- mark(startMarkName);
- }
- }
- function exit() {
- if (--enterCount === 0) {
- mark(endMarkName);
- measure(measureName, startMarkName, endMarkName);
- }
- else if (enterCount < 0) {
- ts.Debug.fail("enter/exit count does not match.");
- }
- }
}
- performance.createTimer = createTimer;
- performance.nullTimer = { enter: ts.noop, exit: ts.noop };
- /**
- * Marks a performance event.
- *
- * @param markName The name of the mark.
- */
- function mark(markName) {
- if (enabled) {
- marks.set(markName, ts.timestamp());
- counts.set(markName, (counts.get(markName) || 0) + 1);
- profilerEvent(markName);
- }
- }
- 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();
- var start = startMarkName && marks.get(startMarkName) || profilerStart;
- measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
- }
- }
- 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();
- measures = ts.createMap();
- enabled = true;
- profilerStart = ts.timestamp();
- }
- performance.enable = enable;
- /** Disables performance measurements for the compiler. */
- function disable() {
- enabled = false;
+ function createWarningDeprecation(name, errorAfter, since, message) {
+ var hasWrittenDeprecation = false;
+ return function () {
+ if (!hasWrittenDeprecation) {
+ log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
+ hasWrittenDeprecation = true;
+ }
+ };
}
- performance.disable = disable;
- })(performance = ts.performance || (ts.performance = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var nullLogger = {
- logEvent: ts.noop,
- logErrEvent: ts.noop,
- logPerfEvent: ts.noop,
- logInfoEvent: ts.noop,
- logStartCommand: ts.noop,
- logStopCommand: ts.noop,
- logStartUpdateProgram: ts.noop,
- logStopUpdateProgram: ts.noop,
- logStartUpdateGraph: ts.noop,
- logStopUpdateGraph: ts.noop,
- logStartResolveModule: ts.noop,
- logStopResolveModule: ts.noop,
- logStartParseSourceFile: ts.noop,
- logStopParseSourceFile: ts.noop,
- logStartReadFile: ts.noop,
- logStopReadFile: ts.noop,
- logStartBindFile: ts.noop,
- logStopBindFile: ts.noop,
- logStartScheduledOperation: ts.noop,
- logStopScheduledOperation: ts.noop,
- };
- // Load optional module to enable Event Tracing for Windows
- // See https://github.com/microsoft/typescript-etw for more information
- var etwModule;
- try {
- // require() will throw an exception if the module is not installed
- // It may also return undefined if not installed properly
- etwModule = require("@microsoft/typescript-etw");
- }
- catch (e) {
- etwModule = undefined;
- }
- /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
- ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
+ function createDeprecation(name, options) {
+ var _a, _b;
+ if (options === void 0) { options = {}; }
+ var version = typeof options.typeScriptVersion === "string" ? new ts.Version(options.typeScriptVersion) : (_a = options.typeScriptVersion) !== null && _a !== void 0 ? _a : getTypeScriptVersion();
+ var errorAfter = typeof options.errorAfter === "string" ? new ts.Version(options.errorAfter) : options.errorAfter;
+ var warnAfter = typeof options.warnAfter === "string" ? new ts.Version(options.warnAfter) : options.warnAfter;
+ var since = typeof options.since === "string" ? new ts.Version(options.since) : (_b = options.since) !== null && _b !== void 0 ? _b : warnAfter;
+ var error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
+ var warn = !warnAfter || version.compareTo(warnAfter) >= 0;
+ return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
+ warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
+ ts.noop;
+ }
+ function wrapFunction(deprecation, func) {
+ return function () {
+ deprecation();
+ return func.apply(this, arguments);
+ };
+ }
+ function deprecate(func, options) {
+ var deprecation = createDeprecation(getFunctionName(func), options);
+ return wrapFunction(deprecation, func);
+ }
+ Debug.deprecate = deprecate;
+ })(Debug = ts.Debug || (ts.Debug = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -2789,7 +3191,7 @@ var ts;
return ts.compareValues(this.major, other.major)
|| ts.compareValues(this.minor, other.minor)
|| ts.compareValues(this.patch, other.patch)
- || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
+ || comparePrereleaseIdentifiers(this.prerelease, other.prerelease);
};
Version.prototype.increment = function (field) {
switch (field) {
@@ -2800,11 +3202,11 @@ var ts;
}
};
Version.prototype.toString = function () {
- var result = this.major + "." + this.minor + "." + this.patch;
+ var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch);
if (ts.some(this.prerelease))
- result += "-" + this.prerelease.join(".");
+ result += "-".concat(this.prerelease.join("."));
if (ts.some(this.build))
- result += "+" + this.build.join(".");
+ result += "+".concat(this.build.join("."));
return result;
};
Version.zero = new Version(0, 0, 0);
@@ -2828,7 +3230,7 @@ var ts;
build: build
};
}
- function comparePrerelaseIdentifiers(left, right) {
+ function comparePrereleaseIdentifiers(left, right) {
// https://semver.org/#spec-item-11
// > When major, minor, and patch are equal, a pre-release version has lower precedence
// > than a normal version.
@@ -2906,7 +3308,7 @@ var ts;
// range-set ::= range ( logical-or range ) *
// range ::= hyphen | simple ( ' ' simple ) * | ''
// logical-or ::= ( ' ' ) * '||' ( ' ' ) *
- var logicalOrRegExp = /\s*\|\|\s*/g;
+ var logicalOrRegExp = /\|\|/g;
var whitespaceRegExp = /\s+/g;
// https://github.com/npm/node-semver#range-grammar
//
@@ -2929,14 +3331,15 @@ var ts;
// primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
// tilde ::= '~' partial
// caret ::= '^' partial
- var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
+ var rangeRegExp = /^(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
function parseRange(text) {
var alternatives = [];
- for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
+ for (var _i = 0, _a = ts.trimString(text).split(logicalOrRegExp); _i < _a.length; _i++) {
var range = _a[_i];
if (!range)
continue;
var comparators = [];
+ range = ts.trimString(range);
var match = hyphenRegExp.exec(range);
if (match) {
if (!parseHyphen(match[1], match[2], comparators))
@@ -2945,7 +3348,7 @@ var ts;
else {
for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
var simple = _c[_b];
- var match_1 = rangeRegExp.exec(simple);
+ var match_1 = rangeRegExp.exec(ts.trimString(simple));
if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
return undefined;
}
@@ -3070,9 +3473,553 @@ var ts;
return ts.map(comparators, formatComparator).join(" ");
}
function formatComparator(comparator) {
- return "" + comparator.operator + comparator.operand;
+ return "".concat(comparator.operator).concat(comparator.operand);
}
})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ // The following definitions provide the minimum compatible support for the Web Performance User Timings API
+ // between browsers and NodeJS:
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ function hasRequiredAPI(performance, PerformanceObserver) {
+ return typeof performance === "object" &&
+ typeof performance.timeOrigin === "number" &&
+ typeof performance.mark === "function" &&
+ typeof performance.measure === "function" &&
+ typeof performance.now === "function" &&
+ typeof PerformanceObserver === "function";
+ }
+ function tryGetWebPerformanceHooks() {
+ if (typeof performance === "object" &&
+ typeof PerformanceObserver === "function" &&
+ hasRequiredAPI(performance, PerformanceObserver)) {
+ return {
+ // For now we always write native performance events when running in the browser. We may
+ // make this conditional in the future if we find that native web performance hooks
+ // in the browser also slow down compilation.
+ shouldWriteNativeEvents: true,
+ performance: performance,
+ PerformanceObserver: PerformanceObserver
+ };
+ }
+ }
+ function tryGetNodePerformanceHooks() {
+ if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") {
+ try {
+ var performance_1;
+ var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
+ if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) {
+ performance_1 = nodePerformance_1;
+ // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not
+ // match the Web Performance API specification. Node's implementation did not allow
+ // optional `start` and `end` arguments for `performance.measure`.
+ // See https://github.com/nodejs/node/pull/32651 for more information.
+ var version_1 = new ts.Version(process.versions.node);
+ var range = new ts.VersionRange("<12.16.3 || 13 <13.13");
+ if (range.test(version_1)) {
+ performance_1 = {
+ get timeOrigin() { return nodePerformance_1.timeOrigin; },
+ now: function () { return nodePerformance_1.now(); },
+ mark: function (name) { return nodePerformance_1.mark(name); },
+ measure: function (name, start, end) {
+ if (start === void 0) { start = "nodeStart"; }
+ if (end === undefined) {
+ end = "__performance.measure-fix__";
+ nodePerformance_1.mark(end);
+ }
+ nodePerformance_1.measure(name, start, end);
+ if (end === "__performance.measure-fix__") {
+ nodePerformance_1.clearMarks("__performance.measure-fix__");
+ }
+ }
+ };
+ }
+ return {
+ // By default, only write native events when generating a cpu profile or using the v8 profiler.
+ shouldWriteNativeEvents: false,
+ performance: performance_1,
+ PerformanceObserver: PerformanceObserver_1
+ };
+ }
+ }
+ catch (_b) {
+ // ignore errors
+ }
+ }
+ }
+ // Unlike with the native Map/Set 'tryGet' functions in corePublic.ts, we eagerly evaluate these
+ // since we will need them for `timestamp`, below.
+ var nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks();
+ var nativePerformance = nativePerformanceHooks === null || nativePerformanceHooks === void 0 ? void 0 : nativePerformanceHooks.performance;
+ function tryGetNativePerformanceHooks() {
+ return nativePerformanceHooks;
+ }
+ ts.tryGetNativePerformanceHooks = tryGetNativePerformanceHooks;
+ /** Gets a timestamp with (at least) ms resolution */
+ ts.timestamp = nativePerformance ? function () { return nativePerformance.now(); } :
+ Date.now ? Date.now :
+ function () { return +(new Date()); };
+})(ts || (ts = {}));
+/*@internal*/
+/** Performance measurements for the compiler. */
+var ts;
+(function (ts) {
+ var performance;
+ (function (performance) {
+ var perfHooks;
+ // when set, indicates the implementation of `Performance` to use for user timing.
+ // when unset, indicates user timing is unavailable or disabled.
+ var performanceImpl;
+ function createTimerIf(condition, measureName, startMarkName, endMarkName) {
+ return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
+ }
+ performance.createTimerIf = createTimerIf;
+ function createTimer(measureName, startMarkName, endMarkName) {
+ var enterCount = 0;
+ return {
+ enter: enter,
+ exit: exit
+ };
+ function enter() {
+ if (++enterCount === 1) {
+ mark(startMarkName);
+ }
+ }
+ function exit() {
+ if (--enterCount === 0) {
+ mark(endMarkName);
+ measure(measureName, startMarkName, endMarkName);
+ }
+ else if (enterCount < 0) {
+ ts.Debug.fail("enter/exit count does not match.");
+ }
+ }
+ }
+ performance.createTimer = createTimer;
+ performance.nullTimer = { enter: ts.noop, exit: ts.noop };
+ var enabled = false;
+ var timeorigin = ts.timestamp();
+ var marks = new ts.Map();
+ var counts = new ts.Map();
+ var durations = new ts.Map();
+ /**
+ * Marks a performance event.
+ *
+ * @param markName The name of the mark.
+ */
+ function mark(markName) {
+ var _a;
+ if (enabled) {
+ var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0;
+ counts.set(markName, count + 1);
+ marks.set(markName, ts.timestamp());
+ performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
+ }
+ }
+ 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) {
+ var _a, _b;
+ if (enabled) {
+ var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp();
+ var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin;
+ var previousDuration = durations.get(measureName) || 0;
+ durations.set(measureName, previousDuration + (end - start));
+ performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
+ }
+ }
+ performance.measure = measure;
+ /**
+ * Gets the number of times a marker was encountered.
+ *
+ * @param markName The name of the mark.
+ */
+ function getCount(markName) {
+ return 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 durations.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) {
+ durations.forEach(function (duration, measureName) { return cb(measureName, duration); });
+ }
+ performance.forEachMeasure = forEachMeasure;
+ /**
+ * Indicates whether the performance API is enabled.
+ */
+ function isEnabled() {
+ return enabled;
+ }
+ performance.isEnabled = isEnabled;
+ /** Enables (and resets) performance measurements for the compiler. */
+ function enable(system) {
+ var _a;
+ if (system === void 0) { system = ts.sys; }
+ if (!enabled) {
+ enabled = true;
+ perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks());
+ if (perfHooks) {
+ timeorigin = perfHooks.performance.timeOrigin;
+ // NodeJS's Web Performance API is currently slower than expected, but we'd still like
+ // to be able to leverage native trace events when node is run with either `--cpu-prof`
+ // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when
+ // running in debug mode (since its possible to generate a cpu profile while debugging).
+ if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) {
+ performanceImpl = perfHooks.performance;
+ }
+ }
+ }
+ return true;
+ }
+ performance.enable = enable;
+ /** Disables performance measurements for the compiler. */
+ function disable() {
+ if (enabled) {
+ marks.clear();
+ counts.clear();
+ durations.clear();
+ performanceImpl = undefined;
+ enabled = false;
+ }
+ }
+ performance.disable = disable;
+ })(performance = ts.performance || (ts.performance = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var _a;
+ var nullLogger = {
+ logEvent: ts.noop,
+ logErrEvent: ts.noop,
+ logPerfEvent: ts.noop,
+ logInfoEvent: ts.noop,
+ logStartCommand: ts.noop,
+ logStopCommand: ts.noop,
+ logStartUpdateProgram: ts.noop,
+ logStopUpdateProgram: ts.noop,
+ logStartUpdateGraph: ts.noop,
+ logStopUpdateGraph: ts.noop,
+ logStartResolveModule: ts.noop,
+ logStopResolveModule: ts.noop,
+ logStartParseSourceFile: ts.noop,
+ logStopParseSourceFile: ts.noop,
+ logStartReadFile: ts.noop,
+ logStopReadFile: ts.noop,
+ logStartBindFile: ts.noop,
+ logStopBindFile: ts.noop,
+ logStartScheduledOperation: ts.noop,
+ logStopScheduledOperation: ts.noop,
+ };
+ // Load optional module to enable Event Tracing for Windows
+ // See https://github.com/microsoft/typescript-etw for more information
+ var etwModule;
+ try {
+ var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
+ // require() will throw an exception if the module is not found
+ // It may also return undefined if not installed properly
+ etwModule = require(etwModulePath);
+ }
+ catch (e) {
+ etwModule = undefined;
+ }
+ /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
+ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
+})(ts || (ts = {}));
+/* Tracing events for the compiler. */
+/*@internal*/
+var ts;
+(function (ts) {
+ // enable the above using startTracing()
+ // `tracingEnabled` should never be used directly, only through the above
+ var tracingEnabled;
+ (function (tracingEnabled) {
+ var fs;
+ var traceCount = 0;
+ var traceFd = 0;
+ var mode;
+ var typeCatalog = []; // NB: id is index + 1
+ var legendPath;
+ var legend = [];
+ ;
+ /** Starts tracing for the given project. */
+ function startTracing(tracingMode, traceDir, configFilePath) {
+ ts.Debug.assert(!ts.tracing, "Tracing already started");
+ if (fs === undefined) {
+ try {
+ fs = require("fs");
+ }
+ catch (e) {
+ throw new Error("tracing requires having fs\n(original error: ".concat(e.message || e, ")"));
+ }
+ }
+ mode = tracingMode;
+ typeCatalog.length = 0;
+ if (legendPath === undefined) {
+ legendPath = ts.combinePaths(traceDir, "legend.json");
+ }
+ // Note that writing will fail later on if it exists and is not a directory
+ if (!fs.existsSync(traceDir)) {
+ fs.mkdirSync(traceDir, { recursive: true });
+ }
+ var countPart = mode === "build" ? ".".concat(process.pid, "-").concat(++traceCount)
+ : mode === "server" ? ".".concat(process.pid)
+ : "";
+ var tracePath = ts.combinePaths(traceDir, "trace".concat(countPart, ".json"));
+ var typesPath = ts.combinePaths(traceDir, "types".concat(countPart, ".json"));
+ legend.push({
+ configFilePath: configFilePath,
+ tracePath: tracePath,
+ typesPath: typesPath,
+ });
+ traceFd = fs.openSync(tracePath, "w");
+ ts.tracing = tracingEnabled; // only when traceFd is properly set
+ // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import)
+ var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 };
+ fs.writeSync(traceFd, "[\n"
+ + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })]
+ .map(function (v) { return JSON.stringify(v); }).join(",\n"));
+ }
+ tracingEnabled.startTracing = startTracing;
+ /** Stops tracing for the in-progress project and dumps the type catalog. */
+ function stopTracing() {
+ ts.Debug.assert(ts.tracing, "Tracing is not in progress");
+ ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode
+ fs.writeSync(traceFd, "\n]\n");
+ fs.closeSync(traceFd);
+ ts.tracing = undefined;
+ if (typeCatalog.length) {
+ dumpTypes(typeCatalog);
+ }
+ else {
+ // We pre-computed this path for convenience, but clear it
+ // now that the file won't be created.
+ legend[legend.length - 1].typesPath = undefined;
+ }
+ }
+ tracingEnabled.stopTracing = stopTracing;
+ function recordType(type) {
+ if (mode !== "server") {
+ typeCatalog.push(type);
+ }
+ }
+ tracingEnabled.recordType = recordType;
+ var Phase;
+ (function (Phase) {
+ Phase["Parse"] = "parse";
+ Phase["Program"] = "program";
+ Phase["Bind"] = "bind";
+ Phase["Check"] = "check";
+ Phase["CheckTypes"] = "checkTypes";
+ Phase["Emit"] = "emit";
+ Phase["Session"] = "session";
+ })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {}));
+ function instant(phase, name, args) {
+ writeEvent("I", phase, name, args, "\"s\":\"g\"");
+ }
+ tracingEnabled.instant = instant;
+ var eventStack = [];
+ /**
+ * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event
+ * never terminates (typically for reducing a scenario too big to trace to one that can be completed).
+ * In the future we might implement an exit handler to dump unfinished events which would deprecate
+ * these operations.
+ */
+ function push(phase, name, args, separateBeginAndEnd) {
+ if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; }
+ if (separateBeginAndEnd) {
+ writeEvent("B", phase, name, args);
+ }
+ eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd });
+ }
+ tracingEnabled.push = push;
+ function pop() {
+ ts.Debug.assert(eventStack.length > 0);
+ writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp());
+ eventStack.length--;
+ }
+ tracingEnabled.pop = pop;
+ function popAll() {
+ var endTime = 1000 * ts.timestamp();
+ for (var i = eventStack.length - 1; i >= 0; i--) {
+ writeStackEvent(i, endTime);
+ }
+ eventStack.length = 0;
+ }
+ tracingEnabled.popAll = popAll;
+ // sample every 10ms
+ var sampleInterval = 1000 * 10;
+ function writeStackEvent(index, endTime) {
+ var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd;
+ if (separateBeginAndEnd) {
+ writeEvent("E", phase, name, args, /*extras*/ undefined, endTime);
+ }
+ // test if [time,endTime) straddles a sampling point
+ else if (sampleInterval - (time % sampleInterval) <= endTime - time) {
+ writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time);
+ }
+ }
+ function writeEvent(eventType, phase, name, args, extras, time) {
+ if (time === void 0) { time = 1000 * ts.timestamp(); }
+ // In server mode, there's no easy way to dump type information, so we drop events that would require it.
+ if (mode === "server" && phase === "checkTypes" /* CheckTypes */)
+ return;
+ ts.performance.mark("beginTracing");
+ fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"".concat(eventType, "\",\"cat\":\"").concat(phase, "\",\"ts\":").concat(time, ",\"name\":\"").concat(name, "\""));
+ if (extras)
+ fs.writeSync(traceFd, ",".concat(extras));
+ if (args)
+ fs.writeSync(traceFd, ",\"args\":".concat(JSON.stringify(args)));
+ fs.writeSync(traceFd, "}");
+ ts.performance.mark("endTracing");
+ ts.performance.measure("Tracing", "beginTracing", "endTracing");
+ }
+ function getLocation(node) {
+ var file = ts.getSourceFileOfNode(node);
+ return !file
+ ? undefined
+ : {
+ path: file.path,
+ start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)),
+ end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)),
+ };
+ function indexFromOne(lc) {
+ return {
+ line: lc.line + 1,
+ character: lc.character + 1,
+ };
+ }
+ }
+ function dumpTypes(types) {
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
+ ts.performance.mark("beginDumpTypes");
+ var typesPath = legend[legend.length - 1].typesPath;
+ var typesFd = fs.openSync(typesPath, "w");
+ var recursionIdentityMap = new ts.Map();
+ // Cleverness: no line break here so that the type ID will match the line number
+ fs.writeSync(typesFd, "[");
+ var numTypes = types.length;
+ for (var i = 0; i < numTypes; i++) {
+ var type = types[i];
+ var objectFlags = type.objectFlags;
+ var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol;
+ // It's slow to compute the display text, so skip it unless it's really valuable (or cheap)
+ var display = void 0;
+ if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) {
+ try {
+ display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type);
+ }
+ catch (_y) {
+ display = undefined;
+ }
+ }
+ var indexedAccessProperties = {};
+ if (type.flags & 8388608 /* IndexedAccess */) {
+ var indexedAccessType = type;
+ indexedAccessProperties = {
+ indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id,
+ indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id,
+ };
+ }
+ var referenceProperties = {};
+ if (objectFlags & 4 /* Reference */) {
+ var referenceType = type;
+ referenceProperties = {
+ instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id,
+ typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }),
+ referenceLocation: getLocation(referenceType.node),
+ };
+ }
+ var conditionalProperties = {};
+ if (type.flags & 16777216 /* Conditional */) {
+ var conditionalType = type;
+ conditionalProperties = {
+ conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id,
+ conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id,
+ conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1,
+ conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1,
+ };
+ }
+ var substitutionProperties = {};
+ if (type.flags & 33554432 /* Substitution */) {
+ var substitutionType = type;
+ substitutionProperties = {
+ substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id,
+ substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id,
+ };
+ }
+ var reverseMappedProperties = {};
+ if (objectFlags & 1024 /* ReverseMapped */) {
+ var reverseMappedType = type;
+ reverseMappedProperties = {
+ reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id,
+ reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id,
+ reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id,
+ };
+ }
+ var evolvingArrayProperties = {};
+ if (objectFlags & 256 /* EvolvingArray */) {
+ var evolvingArrayType = type;
+ evolvingArrayProperties = {
+ evolvingArrayElementType: evolvingArrayType.elementType.id,
+ evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id,
+ };
+ }
+ // We can't print out an arbitrary object, so just assign each one a unique number.
+ // Don't call it an "id" so people don't treat it as a type id.
+ var recursionToken = void 0;
+ var recursionIdentity = type.checker.getRecursionIdentity(type);
+ if (recursionIdentity) {
+ recursionToken = recursionIdentityMap.get(recursionIdentity);
+ if (!recursionToken) {
+ recursionToken = recursionIdentityMap.size;
+ recursionIdentityMap.set(recursionIdentity, recursionToken);
+ }
+ }
+ var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display });
+ fs.writeSync(typesFd, JSON.stringify(descriptor));
+ if (i < numTypes - 1) {
+ fs.writeSync(typesFd, ",\n");
+ }
+ }
+ fs.writeSync(typesFd, "]\n");
+ fs.closeSync(typesFd);
+ ts.performance.mark("endDumpTypes");
+ ts.performance.measure("Dump types", "beginDumpTypes", "endDumpTypes");
+ }
+ function dumpLegend() {
+ if (!legendPath) {
+ return;
+ }
+ fs.writeFileSync(legendPath, JSON.stringify(legend));
+ }
+ tracingEnabled.dumpLegend = dumpLegend;
+ })(tracingEnabled || (tracingEnabled = {}));
+ // define after tracingEnabled is initialized
+ ts.startTracing = tracingEnabled.startTracing;
+ ts.dumpTracingLegend = tracingEnabled.dumpLegend;
+})(ts || (ts = {}));
var ts;
(function (ts) {
// token > SyntaxKind.Identifier => token is a keyword
@@ -3148,321 +4095,341 @@ var ts;
SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
/** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
+ /** Only the JSDoc scanner produces HashToken. The normal scanner produces PrivateIdentifier. */
+ SyntaxKind[SyntaxKind["HashToken"] = 62] = "HashToken";
// Assignments
- SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
- SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
- SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
- SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
- SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
- SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
- SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
- SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
- SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
- SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
+ SyntaxKind[SyntaxKind["EqualsToken"] = 63] = "EqualsToken";
+ SyntaxKind[SyntaxKind["PlusEqualsToken"] = 64] = "PlusEqualsToken";
+ SyntaxKind[SyntaxKind["MinusEqualsToken"] = 65] = "MinusEqualsToken";
+ SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 66] = "AsteriskEqualsToken";
+ SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 67] = "AsteriskAsteriskEqualsToken";
+ SyntaxKind[SyntaxKind["SlashEqualsToken"] = 68] = "SlashEqualsToken";
+ SyntaxKind[SyntaxKind["PercentEqualsToken"] = 69] = "PercentEqualsToken";
+ SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 70] = "LessThanLessThanEqualsToken";
+ SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanEqualsToken";
+ SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 72] = "GreaterThanGreaterThanGreaterThanEqualsToken";
+ SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 73] = "AmpersandEqualsToken";
+ SyntaxKind[SyntaxKind["BarEqualsToken"] = 74] = "BarEqualsToken";
+ SyntaxKind[SyntaxKind["BarBarEqualsToken"] = 75] = "BarBarEqualsToken";
+ SyntaxKind[SyntaxKind["AmpersandAmpersandEqualsToken"] = 76] = "AmpersandAmpersandEqualsToken";
+ SyntaxKind[SyntaxKind["QuestionQuestionEqualsToken"] = 77] = "QuestionQuestionEqualsToken";
+ SyntaxKind[SyntaxKind["CaretEqualsToken"] = 78] = "CaretEqualsToken";
// Identifiers and PrivateIdentifiers
- SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
- SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
+ SyntaxKind[SyntaxKind["Identifier"] = 79] = "Identifier";
+ SyntaxKind[SyntaxKind["PrivateIdentifier"] = 80] = "PrivateIdentifier";
// Reserved words
- SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
- SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
- SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
- SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
- SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
- SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
- SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
- SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
- SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
- SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
- SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
- SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
- SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
- SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
- SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
- SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
- SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
- SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
- SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
- SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
- SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
- SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
- SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
- SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
- SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
- SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
- SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
- SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
- SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
- SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
- SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
- SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
- SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
- SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
- SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
- SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
+ SyntaxKind[SyntaxKind["BreakKeyword"] = 81] = "BreakKeyword";
+ SyntaxKind[SyntaxKind["CaseKeyword"] = 82] = "CaseKeyword";
+ SyntaxKind[SyntaxKind["CatchKeyword"] = 83] = "CatchKeyword";
+ SyntaxKind[SyntaxKind["ClassKeyword"] = 84] = "ClassKeyword";
+ SyntaxKind[SyntaxKind["ConstKeyword"] = 85] = "ConstKeyword";
+ SyntaxKind[SyntaxKind["ContinueKeyword"] = 86] = "ContinueKeyword";
+ SyntaxKind[SyntaxKind["DebuggerKeyword"] = 87] = "DebuggerKeyword";
+ SyntaxKind[SyntaxKind["DefaultKeyword"] = 88] = "DefaultKeyword";
+ SyntaxKind[SyntaxKind["DeleteKeyword"] = 89] = "DeleteKeyword";
+ SyntaxKind[SyntaxKind["DoKeyword"] = 90] = "DoKeyword";
+ SyntaxKind[SyntaxKind["ElseKeyword"] = 91] = "ElseKeyword";
+ SyntaxKind[SyntaxKind["EnumKeyword"] = 92] = "EnumKeyword";
+ SyntaxKind[SyntaxKind["ExportKeyword"] = 93] = "ExportKeyword";
+ SyntaxKind[SyntaxKind["ExtendsKeyword"] = 94] = "ExtendsKeyword";
+ SyntaxKind[SyntaxKind["FalseKeyword"] = 95] = "FalseKeyword";
+ SyntaxKind[SyntaxKind["FinallyKeyword"] = 96] = "FinallyKeyword";
+ SyntaxKind[SyntaxKind["ForKeyword"] = 97] = "ForKeyword";
+ SyntaxKind[SyntaxKind["FunctionKeyword"] = 98] = "FunctionKeyword";
+ SyntaxKind[SyntaxKind["IfKeyword"] = 99] = "IfKeyword";
+ SyntaxKind[SyntaxKind["ImportKeyword"] = 100] = "ImportKeyword";
+ SyntaxKind[SyntaxKind["InKeyword"] = 101] = "InKeyword";
+ SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 102] = "InstanceOfKeyword";
+ SyntaxKind[SyntaxKind["NewKeyword"] = 103] = "NewKeyword";
+ SyntaxKind[SyntaxKind["NullKeyword"] = 104] = "NullKeyword";
+ SyntaxKind[SyntaxKind["ReturnKeyword"] = 105] = "ReturnKeyword";
+ SyntaxKind[SyntaxKind["SuperKeyword"] = 106] = "SuperKeyword";
+ SyntaxKind[SyntaxKind["SwitchKeyword"] = 107] = "SwitchKeyword";
+ SyntaxKind[SyntaxKind["ThisKeyword"] = 108] = "ThisKeyword";
+ SyntaxKind[SyntaxKind["ThrowKeyword"] = 109] = "ThrowKeyword";
+ SyntaxKind[SyntaxKind["TrueKeyword"] = 110] = "TrueKeyword";
+ SyntaxKind[SyntaxKind["TryKeyword"] = 111] = "TryKeyword";
+ SyntaxKind[SyntaxKind["TypeOfKeyword"] = 112] = "TypeOfKeyword";
+ SyntaxKind[SyntaxKind["VarKeyword"] = 113] = "VarKeyword";
+ SyntaxKind[SyntaxKind["VoidKeyword"] = 114] = "VoidKeyword";
+ SyntaxKind[SyntaxKind["WhileKeyword"] = 115] = "WhileKeyword";
+ SyntaxKind[SyntaxKind["WithKeyword"] = 116] = "WithKeyword";
// Strict mode reserved words
- SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
- SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
- SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
- SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
- SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
- SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
- SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
- SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
- SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
+ SyntaxKind[SyntaxKind["ImplementsKeyword"] = 117] = "ImplementsKeyword";
+ SyntaxKind[SyntaxKind["InterfaceKeyword"] = 118] = "InterfaceKeyword";
+ SyntaxKind[SyntaxKind["LetKeyword"] = 119] = "LetKeyword";
+ SyntaxKind[SyntaxKind["PackageKeyword"] = 120] = "PackageKeyword";
+ SyntaxKind[SyntaxKind["PrivateKeyword"] = 121] = "PrivateKeyword";
+ SyntaxKind[SyntaxKind["ProtectedKeyword"] = 122] = "ProtectedKeyword";
+ SyntaxKind[SyntaxKind["PublicKeyword"] = 123] = "PublicKeyword";
+ SyntaxKind[SyntaxKind["StaticKeyword"] = 124] = "StaticKeyword";
+ SyntaxKind[SyntaxKind["YieldKeyword"] = 125] = "YieldKeyword";
// Contextual keywords
- SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
- SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
- SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
- SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
- SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
- SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
- SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
- SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
- SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
- SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
- SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
- SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
- SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
- SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
- SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
- SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
- SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
- SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
- SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
- SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
- SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
- SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
- SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
- SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
- SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
- SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
- SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
- SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
- SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
- SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
- SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
+ SyntaxKind[SyntaxKind["AbstractKeyword"] = 126] = "AbstractKeyword";
+ SyntaxKind[SyntaxKind["AsKeyword"] = 127] = "AsKeyword";
+ SyntaxKind[SyntaxKind["AssertsKeyword"] = 128] = "AssertsKeyword";
+ SyntaxKind[SyntaxKind["AssertKeyword"] = 129] = "AssertKeyword";
+ SyntaxKind[SyntaxKind["AnyKeyword"] = 130] = "AnyKeyword";
+ SyntaxKind[SyntaxKind["AsyncKeyword"] = 131] = "AsyncKeyword";
+ SyntaxKind[SyntaxKind["AwaitKeyword"] = 132] = "AwaitKeyword";
+ SyntaxKind[SyntaxKind["BooleanKeyword"] = 133] = "BooleanKeyword";
+ SyntaxKind[SyntaxKind["ConstructorKeyword"] = 134] = "ConstructorKeyword";
+ SyntaxKind[SyntaxKind["DeclareKeyword"] = 135] = "DeclareKeyword";
+ SyntaxKind[SyntaxKind["GetKeyword"] = 136] = "GetKeyword";
+ SyntaxKind[SyntaxKind["InferKeyword"] = 137] = "InferKeyword";
+ SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 138] = "IntrinsicKeyword";
+ SyntaxKind[SyntaxKind["IsKeyword"] = 139] = "IsKeyword";
+ SyntaxKind[SyntaxKind["KeyOfKeyword"] = 140] = "KeyOfKeyword";
+ SyntaxKind[SyntaxKind["ModuleKeyword"] = 141] = "ModuleKeyword";
+ SyntaxKind[SyntaxKind["NamespaceKeyword"] = 142] = "NamespaceKeyword";
+ SyntaxKind[SyntaxKind["NeverKeyword"] = 143] = "NeverKeyword";
+ SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 144] = "ReadonlyKeyword";
+ SyntaxKind[SyntaxKind["RequireKeyword"] = 145] = "RequireKeyword";
+ SyntaxKind[SyntaxKind["NumberKeyword"] = 146] = "NumberKeyword";
+ SyntaxKind[SyntaxKind["ObjectKeyword"] = 147] = "ObjectKeyword";
+ SyntaxKind[SyntaxKind["SetKeyword"] = 148] = "SetKeyword";
+ SyntaxKind[SyntaxKind["StringKeyword"] = 149] = "StringKeyword";
+ SyntaxKind[SyntaxKind["SymbolKeyword"] = 150] = "SymbolKeyword";
+ SyntaxKind[SyntaxKind["TypeKeyword"] = 151] = "TypeKeyword";
+ SyntaxKind[SyntaxKind["UndefinedKeyword"] = 152] = "UndefinedKeyword";
+ SyntaxKind[SyntaxKind["UniqueKeyword"] = 153] = "UniqueKeyword";
+ SyntaxKind[SyntaxKind["UnknownKeyword"] = 154] = "UnknownKeyword";
+ SyntaxKind[SyntaxKind["FromKeyword"] = 155] = "FromKeyword";
+ SyntaxKind[SyntaxKind["GlobalKeyword"] = 156] = "GlobalKeyword";
+ SyntaxKind[SyntaxKind["BigIntKeyword"] = 157] = "BigIntKeyword";
+ SyntaxKind[SyntaxKind["OverrideKeyword"] = 158] = "OverrideKeyword";
+ SyntaxKind[SyntaxKind["OfKeyword"] = 159] = "OfKeyword";
// Parse tree nodes
// Names
- SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
- SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
+ SyntaxKind[SyntaxKind["QualifiedName"] = 160] = "QualifiedName";
+ SyntaxKind[SyntaxKind["ComputedPropertyName"] = 161] = "ComputedPropertyName";
// Signature elements
- SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
- SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
- SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
+ SyntaxKind[SyntaxKind["TypeParameter"] = 162] = "TypeParameter";
+ SyntaxKind[SyntaxKind["Parameter"] = 163] = "Parameter";
+ SyntaxKind[SyntaxKind["Decorator"] = 164] = "Decorator";
// TypeMember
- SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
- SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
- SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
- SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
- SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
- SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
- SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
- SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
- SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
- SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
+ SyntaxKind[SyntaxKind["PropertySignature"] = 165] = "PropertySignature";
+ SyntaxKind[SyntaxKind["PropertyDeclaration"] = 166] = "PropertyDeclaration";
+ SyntaxKind[SyntaxKind["MethodSignature"] = 167] = "MethodSignature";
+ SyntaxKind[SyntaxKind["MethodDeclaration"] = 168] = "MethodDeclaration";
+ SyntaxKind[SyntaxKind["ClassStaticBlockDeclaration"] = 169] = "ClassStaticBlockDeclaration";
+ SyntaxKind[SyntaxKind["Constructor"] = 170] = "Constructor";
+ SyntaxKind[SyntaxKind["GetAccessor"] = 171] = "GetAccessor";
+ SyntaxKind[SyntaxKind["SetAccessor"] = 172] = "SetAccessor";
+ SyntaxKind[SyntaxKind["CallSignature"] = 173] = "CallSignature";
+ SyntaxKind[SyntaxKind["ConstructSignature"] = 174] = "ConstructSignature";
+ SyntaxKind[SyntaxKind["IndexSignature"] = 175] = "IndexSignature";
// Type
- SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
- SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
- SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
- SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
- SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
- SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
- SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
- SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
- SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
- SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
- SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
- SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
- SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
- SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
- SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
- SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
- SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
- SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
- SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
- SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
- SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
+ SyntaxKind[SyntaxKind["TypePredicate"] = 176] = "TypePredicate";
+ SyntaxKind[SyntaxKind["TypeReference"] = 177] = "TypeReference";
+ SyntaxKind[SyntaxKind["FunctionType"] = 178] = "FunctionType";
+ SyntaxKind[SyntaxKind["ConstructorType"] = 179] = "ConstructorType";
+ SyntaxKind[SyntaxKind["TypeQuery"] = 180] = "TypeQuery";
+ SyntaxKind[SyntaxKind["TypeLiteral"] = 181] = "TypeLiteral";
+ SyntaxKind[SyntaxKind["ArrayType"] = 182] = "ArrayType";
+ SyntaxKind[SyntaxKind["TupleType"] = 183] = "TupleType";
+ SyntaxKind[SyntaxKind["OptionalType"] = 184] = "OptionalType";
+ SyntaxKind[SyntaxKind["RestType"] = 185] = "RestType";
+ SyntaxKind[SyntaxKind["UnionType"] = 186] = "UnionType";
+ SyntaxKind[SyntaxKind["IntersectionType"] = 187] = "IntersectionType";
+ SyntaxKind[SyntaxKind["ConditionalType"] = 188] = "ConditionalType";
+ SyntaxKind[SyntaxKind["InferType"] = 189] = "InferType";
+ SyntaxKind[SyntaxKind["ParenthesizedType"] = 190] = "ParenthesizedType";
+ SyntaxKind[SyntaxKind["ThisType"] = 191] = "ThisType";
+ SyntaxKind[SyntaxKind["TypeOperator"] = 192] = "TypeOperator";
+ SyntaxKind[SyntaxKind["IndexedAccessType"] = 193] = "IndexedAccessType";
+ SyntaxKind[SyntaxKind["MappedType"] = 194] = "MappedType";
+ SyntaxKind[SyntaxKind["LiteralType"] = 195] = "LiteralType";
+ SyntaxKind[SyntaxKind["NamedTupleMember"] = 196] = "NamedTupleMember";
+ SyntaxKind[SyntaxKind["TemplateLiteralType"] = 197] = "TemplateLiteralType";
+ SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 198] = "TemplateLiteralTypeSpan";
+ SyntaxKind[SyntaxKind["ImportType"] = 199] = "ImportType";
// Binding patterns
- SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
- SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
- SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
+ SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 200] = "ObjectBindingPattern";
+ SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 201] = "ArrayBindingPattern";
+ SyntaxKind[SyntaxKind["BindingElement"] = 202] = "BindingElement";
// Expression
- SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
- SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
- SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
- SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
- SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
- SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
- SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
- SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
- SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
- SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
- SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
- SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
- SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
- SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
- SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
- SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
- SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
- SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
- SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
- SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
- SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
- SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
- SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
- SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
- SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
- SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
- SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
- SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
- SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
+ SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 203] = "ArrayLiteralExpression";
+ SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 204] = "ObjectLiteralExpression";
+ SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 205] = "PropertyAccessExpression";
+ SyntaxKind[SyntaxKind["ElementAccessExpression"] = 206] = "ElementAccessExpression";
+ SyntaxKind[SyntaxKind["CallExpression"] = 207] = "CallExpression";
+ SyntaxKind[SyntaxKind["NewExpression"] = 208] = "NewExpression";
+ SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 209] = "TaggedTemplateExpression";
+ SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 210] = "TypeAssertionExpression";
+ SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 211] = "ParenthesizedExpression";
+ SyntaxKind[SyntaxKind["FunctionExpression"] = 212] = "FunctionExpression";
+ SyntaxKind[SyntaxKind["ArrowFunction"] = 213] = "ArrowFunction";
+ SyntaxKind[SyntaxKind["DeleteExpression"] = 214] = "DeleteExpression";
+ SyntaxKind[SyntaxKind["TypeOfExpression"] = 215] = "TypeOfExpression";
+ SyntaxKind[SyntaxKind["VoidExpression"] = 216] = "VoidExpression";
+ SyntaxKind[SyntaxKind["AwaitExpression"] = 217] = "AwaitExpression";
+ SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 218] = "PrefixUnaryExpression";
+ SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 219] = "PostfixUnaryExpression";
+ SyntaxKind[SyntaxKind["BinaryExpression"] = 220] = "BinaryExpression";
+ SyntaxKind[SyntaxKind["ConditionalExpression"] = 221] = "ConditionalExpression";
+ SyntaxKind[SyntaxKind["TemplateExpression"] = 222] = "TemplateExpression";
+ SyntaxKind[SyntaxKind["YieldExpression"] = 223] = "YieldExpression";
+ SyntaxKind[SyntaxKind["SpreadElement"] = 224] = "SpreadElement";
+ SyntaxKind[SyntaxKind["ClassExpression"] = 225] = "ClassExpression";
+ SyntaxKind[SyntaxKind["OmittedExpression"] = 226] = "OmittedExpression";
+ SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 227] = "ExpressionWithTypeArguments";
+ SyntaxKind[SyntaxKind["AsExpression"] = 228] = "AsExpression";
+ SyntaxKind[SyntaxKind["NonNullExpression"] = 229] = "NonNullExpression";
+ SyntaxKind[SyntaxKind["MetaProperty"] = 230] = "MetaProperty";
+ SyntaxKind[SyntaxKind["SyntheticExpression"] = 231] = "SyntheticExpression";
// Misc
- SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
- SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
+ SyntaxKind[SyntaxKind["TemplateSpan"] = 232] = "TemplateSpan";
+ SyntaxKind[SyntaxKind["SemicolonClassElement"] = 233] = "SemicolonClassElement";
// Element
- SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
- SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
- SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
- SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
- SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
- SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
- SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
- SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
- SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
- SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
- SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
- SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
- SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
- SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
- SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
- SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
- SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
- SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
- SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
- SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
- SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
- SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
- SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
- SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
- SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
- SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
- SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
- SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
- SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
- SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
- SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
- SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
- SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
- SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
- SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
- SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
- SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
- SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
- SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
- SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
- SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
- SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
+ SyntaxKind[SyntaxKind["Block"] = 234] = "Block";
+ SyntaxKind[SyntaxKind["EmptyStatement"] = 235] = "EmptyStatement";
+ SyntaxKind[SyntaxKind["VariableStatement"] = 236] = "VariableStatement";
+ SyntaxKind[SyntaxKind["ExpressionStatement"] = 237] = "ExpressionStatement";
+ SyntaxKind[SyntaxKind["IfStatement"] = 238] = "IfStatement";
+ SyntaxKind[SyntaxKind["DoStatement"] = 239] = "DoStatement";
+ SyntaxKind[SyntaxKind["WhileStatement"] = 240] = "WhileStatement";
+ SyntaxKind[SyntaxKind["ForStatement"] = 241] = "ForStatement";
+ SyntaxKind[SyntaxKind["ForInStatement"] = 242] = "ForInStatement";
+ SyntaxKind[SyntaxKind["ForOfStatement"] = 243] = "ForOfStatement";
+ SyntaxKind[SyntaxKind["ContinueStatement"] = 244] = "ContinueStatement";
+ SyntaxKind[SyntaxKind["BreakStatement"] = 245] = "BreakStatement";
+ SyntaxKind[SyntaxKind["ReturnStatement"] = 246] = "ReturnStatement";
+ SyntaxKind[SyntaxKind["WithStatement"] = 247] = "WithStatement";
+ SyntaxKind[SyntaxKind["SwitchStatement"] = 248] = "SwitchStatement";
+ SyntaxKind[SyntaxKind["LabeledStatement"] = 249] = "LabeledStatement";
+ SyntaxKind[SyntaxKind["ThrowStatement"] = 250] = "ThrowStatement";
+ SyntaxKind[SyntaxKind["TryStatement"] = 251] = "TryStatement";
+ SyntaxKind[SyntaxKind["DebuggerStatement"] = 252] = "DebuggerStatement";
+ SyntaxKind[SyntaxKind["VariableDeclaration"] = 253] = "VariableDeclaration";
+ SyntaxKind[SyntaxKind["VariableDeclarationList"] = 254] = "VariableDeclarationList";
+ SyntaxKind[SyntaxKind["FunctionDeclaration"] = 255] = "FunctionDeclaration";
+ SyntaxKind[SyntaxKind["ClassDeclaration"] = 256] = "ClassDeclaration";
+ SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 257] = "InterfaceDeclaration";
+ SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 258] = "TypeAliasDeclaration";
+ SyntaxKind[SyntaxKind["EnumDeclaration"] = 259] = "EnumDeclaration";
+ SyntaxKind[SyntaxKind["ModuleDeclaration"] = 260] = "ModuleDeclaration";
+ SyntaxKind[SyntaxKind["ModuleBlock"] = 261] = "ModuleBlock";
+ SyntaxKind[SyntaxKind["CaseBlock"] = 262] = "CaseBlock";
+ SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 263] = "NamespaceExportDeclaration";
+ SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 264] = "ImportEqualsDeclaration";
+ SyntaxKind[SyntaxKind["ImportDeclaration"] = 265] = "ImportDeclaration";
+ SyntaxKind[SyntaxKind["ImportClause"] = 266] = "ImportClause";
+ SyntaxKind[SyntaxKind["NamespaceImport"] = 267] = "NamespaceImport";
+ SyntaxKind[SyntaxKind["NamedImports"] = 268] = "NamedImports";
+ SyntaxKind[SyntaxKind["ImportSpecifier"] = 269] = "ImportSpecifier";
+ SyntaxKind[SyntaxKind["ExportAssignment"] = 270] = "ExportAssignment";
+ SyntaxKind[SyntaxKind["ExportDeclaration"] = 271] = "ExportDeclaration";
+ SyntaxKind[SyntaxKind["NamedExports"] = 272] = "NamedExports";
+ SyntaxKind[SyntaxKind["NamespaceExport"] = 273] = "NamespaceExport";
+ SyntaxKind[SyntaxKind["ExportSpecifier"] = 274] = "ExportSpecifier";
+ SyntaxKind[SyntaxKind["MissingDeclaration"] = 275] = "MissingDeclaration";
// Module references
- SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
+ SyntaxKind[SyntaxKind["ExternalModuleReference"] = 276] = "ExternalModuleReference";
// JSX
- SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
- SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
- SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
- SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
- SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
- SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
- SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
- SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
- SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
- SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
- SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
+ SyntaxKind[SyntaxKind["JsxElement"] = 277] = "JsxElement";
+ SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 278] = "JsxSelfClosingElement";
+ SyntaxKind[SyntaxKind["JsxOpeningElement"] = 279] = "JsxOpeningElement";
+ SyntaxKind[SyntaxKind["JsxClosingElement"] = 280] = "JsxClosingElement";
+ SyntaxKind[SyntaxKind["JsxFragment"] = 281] = "JsxFragment";
+ SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 282] = "JsxOpeningFragment";
+ SyntaxKind[SyntaxKind["JsxClosingFragment"] = 283] = "JsxClosingFragment";
+ SyntaxKind[SyntaxKind["JsxAttribute"] = 284] = "JsxAttribute";
+ SyntaxKind[SyntaxKind["JsxAttributes"] = 285] = "JsxAttributes";
+ SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 286] = "JsxSpreadAttribute";
+ SyntaxKind[SyntaxKind["JsxExpression"] = 287] = "JsxExpression";
// Clauses
- SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
- SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
- SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
- SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
+ SyntaxKind[SyntaxKind["CaseClause"] = 288] = "CaseClause";
+ SyntaxKind[SyntaxKind["DefaultClause"] = 289] = "DefaultClause";
+ SyntaxKind[SyntaxKind["HeritageClause"] = 290] = "HeritageClause";
+ SyntaxKind[SyntaxKind["CatchClause"] = 291] = "CatchClause";
+ SyntaxKind[SyntaxKind["AssertClause"] = 292] = "AssertClause";
+ SyntaxKind[SyntaxKind["AssertEntry"] = 293] = "AssertEntry";
// Property assignments
- SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
- SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
- SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
+ SyntaxKind[SyntaxKind["PropertyAssignment"] = 294] = "PropertyAssignment";
+ SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 295] = "ShorthandPropertyAssignment";
+ SyntaxKind[SyntaxKind["SpreadAssignment"] = 296] = "SpreadAssignment";
// Enum
- SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
+ SyntaxKind[SyntaxKind["EnumMember"] = 297] = "EnumMember";
// Unparsed
- SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
- SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
- SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
- SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
- SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 298] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 299] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 300] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 301] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 302] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 303] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 304] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 305] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 306] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
- // The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
- // The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
- // https://jsdoc.app/about-namepaths.html
- SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag";
- SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag";
- SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag";
- SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag";
- SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 307] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocNameReference"] = 308] = "JSDocNameReference";
+ SyntaxKind[SyntaxKind["JSDocMemberName"] = 309] = "JSDocMemberName";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 310] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 311] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 312] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 313] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 314] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 315] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 316] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocNamepathType"] = 317] = "JSDocNamepathType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 318] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocText"] = 319] = "JSDocText";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 320] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 321] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocLink"] = 322] = "JSDocLink";
+ SyntaxKind[SyntaxKind["JSDocLinkCode"] = 323] = "JSDocLinkCode";
+ SyntaxKind[SyntaxKind["JSDocLinkPlain"] = 324] = "JSDocLinkPlain";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 325] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 326] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 327] = "JSDocImplementsTag";
+ SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 328] = "JSDocAuthorTag";
+ SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 329] = "JSDocDeprecatedTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 330] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocPublicTag"] = 331] = "JSDocPublicTag";
+ SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 332] = "JSDocPrivateTag";
+ SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 333] = "JSDocProtectedTag";
+ SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 334] = "JSDocReadonlyTag";
+ SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 335] = "JSDocOverrideTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 336] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 337] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 338] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 339] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 340] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 341] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 342] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 343] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocSeeTag"] = 344] = "JSDocSeeTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 345] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 346] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker";
- SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 347] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 348] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 349] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 350] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 351] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 352] = "SyntheticReferenceExpression";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 331] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 353] = "Count";
// Markers
- SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
- SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
- SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
- SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
- SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
- SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
- SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
- SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
- SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
- SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
- SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
- SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
+ SyntaxKind[SyntaxKind["FirstAssignment"] = 63] = "FirstAssignment";
+ SyntaxKind[SyntaxKind["LastAssignment"] = 78] = "LastAssignment";
+ SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 64] = "FirstCompoundAssignment";
+ SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 78] = "LastCompoundAssignment";
+ SyntaxKind[SyntaxKind["FirstReservedWord"] = 81] = "FirstReservedWord";
+ SyntaxKind[SyntaxKind["LastReservedWord"] = 116] = "LastReservedWord";
+ SyntaxKind[SyntaxKind["FirstKeyword"] = 81] = "FirstKeyword";
+ SyntaxKind[SyntaxKind["LastKeyword"] = 159] = "LastKeyword";
+ SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 117] = "FirstFutureReservedWord";
+ SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 125] = "LastFutureReservedWord";
+ SyntaxKind[SyntaxKind["FirstTypeNode"] = 176] = "FirstTypeNode";
+ SyntaxKind[SyntaxKind["LastTypeNode"] = 199] = "LastTypeNode";
SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
- SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
+ SyntaxKind[SyntaxKind["LastPunctuation"] = 78] = "LastPunctuation";
SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
- SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
+ SyntaxKind[SyntaxKind["LastToken"] = 159] = "LastToken";
SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
@@ -3470,16 +4437,16 @@ var ts;
SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
- SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
- SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
- SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
- SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode";
- /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
- /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
+ SyntaxKind[SyntaxKind["LastBinaryOperator"] = 78] = "LastBinaryOperator";
+ SyntaxKind[SyntaxKind["FirstStatement"] = 236] = "FirstStatement";
+ SyntaxKind[SyntaxKind["LastStatement"] = 252] = "LastStatement";
+ SyntaxKind[SyntaxKind["FirstNode"] = 160] = "FirstNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 307] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 345] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 325] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 345] = "LastJSDocTagNode";
+ /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword";
+ /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 159] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
var NodeFlags;
(function (NodeFlags) {
@@ -3520,6 +4487,7 @@ var ts;
/* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
/* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
+ /* @internal */ NodeFlags[NodeFlags["Deprecated"] = 134217728] = "Deprecated";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
@@ -3546,14 +4514,17 @@ var ts;
ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
+ ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers";
+ ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated";
+ ModifierFlags[ModifierFlags["Override"] = 16384] = "Override";
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["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier";
ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
- ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
+ ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier";
ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
- ModifierFlags[ModifierFlags["All"] = 3071] = "All";
+ ModifierFlags[ModifierFlags["All"] = 27647] = "All";
})(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
var JsxFlags;
(function (JsxFlags) {
@@ -3574,20 +4545,20 @@ var ts;
RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
})(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";
+ /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
+ /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
+ /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
+ /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
+ /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
// Flags
GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["AllowNameSubstitution"] = 64] = "AllowNameSubstitution";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
var TokenFlags;
(function (TokenFlags) {
@@ -3615,6 +4586,8 @@ var ts;
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
/* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
+ /* @internal */
+ TokenFlags[TokenFlags["TemplateLiteralLikeFlags"] = 2048] = "TemplateLiteralLikeFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
// NOTE: Ensure this is up-to-date with src/debug/debug.ts
var FlowFlags;
@@ -3648,12 +4621,24 @@ var ts;
}());
ts.OperationCanceledException = OperationCanceledException;
/*@internal*/
- var RefFileKind;
- (function (RefFileKind) {
- RefFileKind[RefFileKind["Import"] = 0] = "Import";
- RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
- RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
- })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
+ var FileIncludeKind;
+ (function (FileIncludeKind) {
+ FileIncludeKind[FileIncludeKind["RootFile"] = 0] = "RootFile";
+ FileIncludeKind[FileIncludeKind["SourceFromProjectReference"] = 1] = "SourceFromProjectReference";
+ FileIncludeKind[FileIncludeKind["OutputFromProjectReference"] = 2] = "OutputFromProjectReference";
+ FileIncludeKind[FileIncludeKind["Import"] = 3] = "Import";
+ FileIncludeKind[FileIncludeKind["ReferenceFile"] = 4] = "ReferenceFile";
+ FileIncludeKind[FileIncludeKind["TypeReferenceDirective"] = 5] = "TypeReferenceDirective";
+ FileIncludeKind[FileIncludeKind["LibFile"] = 6] = "LibFile";
+ FileIncludeKind[FileIncludeKind["LibReferenceDirective"] = 7] = "LibReferenceDirective";
+ FileIncludeKind[FileIncludeKind["AutomaticTypeDirectiveFile"] = 8] = "AutomaticTypeDirectiveFile";
+ })(FileIncludeKind = ts.FileIncludeKind || (ts.FileIncludeKind = {}));
+ /*@internal*/
+ var FilePreprocessingDiagnosticsKind;
+ (function (FilePreprocessingDiagnosticsKind) {
+ FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingReferencedDiagnostic"] = 0] = "FilePreprocessingReferencedDiagnostic";
+ FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingFileExplainingDiagnostic"] = 1] = "FilePreprocessingFileExplainingDiagnostic";
+ })(FilePreprocessingDiagnosticsKind = ts.FilePreprocessingDiagnosticsKind || (ts.FilePreprocessingDiagnosticsKind = {}));
/* @internal */
var StructureIsReused;
(function (StructureIsReused) {
@@ -3680,6 +4665,13 @@ var ts;
ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
})(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
/* @internal */
+ var MemberOverrideStatus;
+ (function (MemberOverrideStatus) {
+ MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok";
+ MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride";
+ MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride";
+ })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {}));
+ /* @internal */
var UnionReduction;
(function (UnionReduction) {
UnionReduction[UnionReduction["None"] = 0] = "None";
@@ -3693,6 +4685,7 @@ var ts;
ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
+ ContextFlags[ContextFlags["SkipBindingPatterns"] = 8] = "SkipBindingPatterns";
})(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
// NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
var NodeBuilderFlags;
@@ -3716,8 +4709,11 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
+ NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType";
// Error handling
NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
+ NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier";
+ /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */
NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
@@ -3732,7 +4728,6 @@ var ts;
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;
@@ -3947,6 +4942,7 @@ var ts;
CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
+ CheckFlags[CheckFlags["Unresolved"] = 1048576] = "Unresolved";
CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
@@ -3997,6 +4993,7 @@ var ts;
NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
+ NodeCheckFlags[NodeCheckFlags["ContainsSuperPropertyInStaticInitializer"] = 134217728] = "ContainsSuperPropertyInStaticInitializer";
})(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
var TypeFlags;
(function (TypeFlags) {
@@ -4027,6 +5024,8 @@ var ts;
TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
+ TypeFlags[TypeFlags["TemplateLiteral"] = 134217728] = "TemplateLiteral";
+ TypeFlags[TypeFlags["StringMapping"] = 268435456] = "StringMapping";
/* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
@@ -4043,7 +5042,7 @@ var ts;
TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
/* @internal */
TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
- TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
+ TypeFlags[TypeFlags["StringLike"] = 402653316] = "StringLike";
TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
@@ -4051,39 +5050,43 @@ var ts;
TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
/* @internal */
- TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
+ TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains";
TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
- TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
- TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
- TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ TypeFlags[TypeFlags["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive";
+ TypeFlags[TypeFlags["Instantiable"] = 465829888] = "Instantiable";
+ TypeFlags[TypeFlags["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable";
/* @internal */
TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
/* @internal */
TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
/* @internal */
- TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
+ TypeFlags[TypeFlags["Singleton"] = 67358815] = "Singleton";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
- TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
- TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
- /* @internal */
- TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable";
// The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
+ TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
+ TypeFlags[TypeFlags["IncludesMissingType"] = 262144] = "IncludesMissingType";
/* @internal */
TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
/* @internal */
TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
/* @internal */
TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
+ /* @internal */
+ TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
+ // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags
+ // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check
+ // for a certain TypeFlags value to determine their meaning.
var ObjectFlags;
(function (ObjectFlags) {
ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
@@ -4096,45 +5099,59 @@ var ts;
ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
- ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
- ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
- ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
- ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
- ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
- ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
- ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
- ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
+ ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped";
+ ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes";
+ ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType";
+ ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral";
+ ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral";
+ ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral";
/* @internal */
- ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
/* @internal */
- ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
/* @internal */
- ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
+ ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral";
/* @internal */
- ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
+ ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
/* @internal */
- ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
+ ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed";
/* @internal */
- ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
+ ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables";
+ ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
/* @internal */
- ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
/* @internal */
- ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
+ // Object flags that uniquely identify the kind of ObjectType
/* @internal */
- ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
+ ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask";
+ // Flags that require TypeFlags.Object
+ ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread";
+ ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType";
/* @internal */
- ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
+ ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone";
+ // Flags that require TypeFlags.Object and ObjectFlags.Reference
/* @internal */
- ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
+ ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated";
/* @internal */
- ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
+ ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists";
+ // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution
/* @internal */
- ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
- ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ ObjectFlags[ObjectFlags["IsGenericTypeComputed"] = 4194304] = "IsGenericTypeComputed";
+ /* @internal */
+ ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["IsGenericIndexType"] = 16777216] = "IsGenericIndexType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["IsGenericType"] = 25165824] = "IsGenericType";
+ // Flags that require TypeFlags.Union
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsIntersections"] = 33554432] = "ContainsIntersections";
+ // Flags that require TypeFlags.Intersection
/* @internal */
- ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
+ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 33554432] = "IsNeverIntersectionComputed";
/* @internal */
- ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
+ ObjectFlags[ObjectFlags["IsNeverIntersection"] = 67108864] = "IsNeverIntersection";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var VarianceFlags;
@@ -4149,6 +5166,32 @@ var ts;
VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
})(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
+ var ElementFlags;
+ (function (ElementFlags) {
+ ElementFlags[ElementFlags["Required"] = 1] = "Required";
+ ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
+ ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
+ ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
+ ElementFlags[ElementFlags["Fixed"] = 3] = "Fixed";
+ ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
+ ElementFlags[ElementFlags["NonRequired"] = 14] = "NonRequired";
+ ElementFlags[ElementFlags["NonRest"] = 11] = "NonRest";
+ })(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
+ /* @internal */
+ var AccessFlags;
+ (function (AccessFlags) {
+ AccessFlags[AccessFlags["None"] = 0] = "None";
+ AccessFlags[AccessFlags["IncludeUndefined"] = 1] = "IncludeUndefined";
+ AccessFlags[AccessFlags["NoIndexSignatures"] = 2] = "NoIndexSignatures";
+ AccessFlags[AccessFlags["Writing"] = 4] = "Writing";
+ AccessFlags[AccessFlags["CacheSymbol"] = 8] = "CacheSymbol";
+ AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 16] = "NoTupleBoundsCheck";
+ AccessFlags[AccessFlags["ExpressionPosition"] = 32] = "ExpressionPosition";
+ AccessFlags[AccessFlags["ReportDeprecated"] = 64] = "ReportDeprecated";
+ AccessFlags[AccessFlags["SuppressNoImplicitAnyError"] = 128] = "SuppressNoImplicitAnyError";
+ AccessFlags[AccessFlags["Contextual"] = 256] = "Contextual";
+ AccessFlags[AccessFlags["Persistent"] = 1] = "Persistent";
+ })(AccessFlags = ts.AccessFlags || (ts.AccessFlags = {}));
/* @internal */
var JsxReferenceKind;
(function (JsxReferenceKind) {
@@ -4165,16 +5208,19 @@ var ts;
var SignatureFlags;
(function (SignatureFlags) {
SignatureFlags[SignatureFlags["None"] = 0] = "None";
+ // Propagating flags
SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
- SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
- SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
- SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
- // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
+ SignatureFlags[SignatureFlags["Abstract"] = 4] = "Abstract";
+ // Non-propagating flags
+ SignatureFlags[SignatureFlags["IsInnerCallChain"] = 8] = "IsInnerCallChain";
+ SignatureFlags[SignatureFlags["IsOuterCallChain"] = 16] = "IsOuterCallChain";
+ SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile";
+ // We do not propagate `IsInnerCallChain` or `IsOuterCallChain` to instantiated signatures, as that would result in us
// attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
// instantiating the return type.
- SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
- SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
+ SignatureFlags[SignatureFlags["PropagatingFlags"] = 39] = "PropagatingFlags";
+ SignatureFlags[SignatureFlags["CallChainFlags"] = 24] = "CallChainFlags";
})(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
var IndexKind;
(function (IndexKind) {
@@ -4193,16 +5239,18 @@ var ts;
var InferencePriority;
(function (InferencePriority) {
InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
- InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
- InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
- InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
- InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
- InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
- InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
- InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
- InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
+ InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple";
+ InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource";
+ InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType";
+ InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType";
+ InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint";
+ InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional";
+ InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType";
+ InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof";
+ InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints";
+ InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict";
+ InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue";
+ InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination";
InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
})(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
/* @internal */
@@ -4215,18 +5263,18 @@ var ts;
})(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.
+ * x & y picks the lesser in the order False < Unknown < Maybe < True, and
+ * x | y picks the greater in the order False < Unknown < Maybe < True.
+ * Generally, Ternary.Maybe is used as the result of a relation that depends on itself, and
+ * Ternary.Unknown is used as the result of a variance check that depends on itself. We make
+ * a distinction because we don't want to cache circular variance check results.
*/
/* @internal */
var Ternary;
(function (Ternary) {
Ternary[Ternary["False"] = 0] = "False";
- Ternary[Ternary["Maybe"] = 1] = "Maybe";
+ Ternary[Ternary["Unknown"] = 1] = "Unknown";
+ Ternary[Ternary["Maybe"] = 3] = "Maybe";
Ternary[Ternary["True"] = -1] = "True";
})(Ternary = ts.Ternary || (ts.Ternary = {}));
/* @internal */
@@ -4234,6 +5282,7 @@ var ts;
(function (AssignmentDeclarationKind) {
AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
/// exports.name = expr
+ /// module.exports.name = expr
AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
/// module.exports = expr
AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
@@ -4273,26 +5322,35 @@ var ts;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
+ // Starting with node12, node's module resolver has significant departures from traditional cjs resolution
+ // to better support ecmascript modules and their use within node - more features are still being added, so
+ // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12`
+ // version-anchored resolution target
+ ModuleResolutionKind[ModuleResolutionKind["Node12"] = 3] = "Node12";
+ ModuleResolutionKind[ModuleResolutionKind["NodeNext"] = 99] = "NodeNext";
})(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
var WatchFileKind;
(function (WatchFileKind) {
WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
- WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
- WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
+ WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling";
+ WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents";
+ WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory";
})(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
var WatchDirectoryKind;
(function (WatchDirectoryKind) {
WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
+ WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling";
})(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
var PollingWatchKind;
(function (PollingWatchKind) {
PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
+ PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize";
})(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
var ModuleKind;
(function (ModuleKind) {
@@ -4306,7 +5364,11 @@ var ts;
// module kind).
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
+ ModuleKind[ModuleKind["ES2022"] = 7] = "ES2022";
ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
+ // Node12+ is an amalgam of commonjs (albeit updated) and es2020+, and represents a distinct module system from es2020/esnext
+ ModuleKind[ModuleKind["Node12"] = 100] = "Node12";
+ ModuleKind[ModuleKind["NodeNext"] = 199] = "NodeNext";
})(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
var JsxEmit;
(function (JsxEmit) {
@@ -4314,6 +5376,8 @@ var ts;
JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
JsxEmit[JsxEmit["React"] = 2] = "React";
JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
+ JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
+ JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
})(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
var ImportsNotUsedAsValues;
(function (ImportsNotUsedAsValues) {
@@ -4351,6 +5415,7 @@ var ts;
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
+ ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021";
ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
@@ -4503,6 +5568,12 @@ var ts;
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
Extension["TsBuildInfo"] = ".tsbuildinfo";
+ Extension["Mjs"] = ".mjs";
+ Extension["Mts"] = ".mts";
+ Extension["Dmts"] = ".d.mts";
+ Extension["Cjs"] = ".cjs";
+ Extension["Cts"] = ".cts";
+ Extension["Dcts"] = ".d.cts";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -4513,28 +5584,32 @@ var ts;
TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
- TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
- TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
- TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
- TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021";
+ TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020";
+ TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016";
+ TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
- TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport";
+ TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields";
+ TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait";
+ TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper";
+ TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier";
// 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
@@ -4544,40 +5619,51 @@ var ts;
TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
- TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
- TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
- TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021";
+ TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020";
+ TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes";
TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes";
TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper";
// Propagating flags
// - Bitmasks for flags that should propagate from a child
- TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
+ // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax
+ /* @internal */
+ var SnippetKind;
+ (function (SnippetKind) {
+ SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop";
+ SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder";
+ SnippetKind[SnippetKind["Choice"] = 2] = "Choice";
+ SnippetKind[SnippetKind["Variable"] = 3] = "Variable";
+ })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {}));
var EmitFlags;
(function (EmitFlags) {
EmitFlags[EmitFlags["None"] = 0] = "None";
@@ -4612,6 +5698,8 @@ var ts;
/*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
/*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
/*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
+ /*@internal*/ EmitFlags[EmitFlags["Immutable"] = 268435456] = "Immutable";
+ /*@internal*/ EmitFlags[EmitFlags["IndirectCall"] = 536870912] = "IndirectCall";
})(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
/**
* Used by the checker, this enum keeps track of external emit helpers that should be type
@@ -4630,27 +5718,29 @@ var ts;
ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
- ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
- ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
- ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
- ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
- ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
- ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
- ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
- ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding";
+ ExternalEmitHelpers[ExternalEmitHelpers["SpreadArray"] = 1024] = "SpreadArray";
+ ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
+ ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
+ ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 65536] = "ImportStar";
+ ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 131072] = "ImportDefault";
+ ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 262144] = "MakeTemplateObject";
+ ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 524288] = "ClassPrivateFieldGet";
+ ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 1048576] = "ClassPrivateFieldSet";
+ ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldIn"] = 2097152] = "ClassPrivateFieldIn";
+ ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 4194304] = "CreateBinding";
ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
- ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper";
+ ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 4194304] = "LastEmitHelper";
// Helpers included by ES2015 for..of
ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
// Helpers included by ES2017 for..await..of
- ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
// Helpers included by ES2017 async generators
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
// Helpers included by yield* in ES2017 async generators
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
// Helpers included by ES2015 spread
ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
})(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
@@ -4664,6 +5754,16 @@ var ts;
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ var OuterExpressionKinds;
+ (function (OuterExpressionKinds) {
+ OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
+ OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
+ OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
+ OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
+ OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
+ OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
+ OuterExpressionKinds[OuterExpressionKinds["ExcludeJSDocTypeAssertion"] = 16] = "ExcludeJSDocTypeAssertion";
+ })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
/* @internal */
var LexicalEnvironmentFlags;
(function (LexicalEnvironmentFlags) {
@@ -4726,12 +5826,14 @@ var ts;
ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
- ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
+ ListFormat[ListFormat["SingleLineTupleTypeElements"] = 528] = "SingleLineTupleTypeElements";
+ ListFormat[ListFormat["MultiLineTupleTypeElements"] = 657] = "MultiLineTupleTypeElements";
ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
+ ListFormat[ListFormat["ImportClauseEntries"] = 526226] = "ImportClauseEntries";
ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
@@ -4815,69963 +5917,81060 @@ var ts;
args: [{ name: "factory" }],
kind: 4 /* MultiLine */
},
+ "jsxfrag": {
+ args: [{ name: "factory" }],
+ kind: 4 /* MultiLine */
+ },
+ "jsximportsource": {
+ args: [{ name: "factory" }],
+ kind: 4 /* MultiLine */
+ },
+ "jsxruntime": {
+ args: [{ name: "factory" }],
+ kind: 4 /* MultiLine */
+ },
};
})(ts || (ts = {}));
+/* @internal */
var ts;
(function (ts) {
/**
- * djb2 hashing algorithm
- * http://www.cse.yorku.ca/~oz/hash.html
+ * 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.
*/
- /* @internal */
- function generateDjb2Hash(data) {
- var acc = 5381;
- for (var i = 0; i < data.length; i++) {
- acc = ((acc << 5) + acc) + data.charCodeAt(i);
- }
- return acc.toString();
+ ts.directorySeparator = "/";
+ ts.altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ //// Path Tests
+ /**
+ * Determines whether a charCode corresponds to `/` or `\`.
+ */
+ function isAnyDirectorySeparator(charCode) {
+ return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
}
- ts.generateDjb2Hash = generateDjb2Hash;
+ ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
/**
- * 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.
+ * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
*/
- /* @internal */
- function setStackTraceLimit() {
- if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
- Error.stackTraceLimit = 100;
- }
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
}
- ts.setStackTraceLimit = setStackTraceLimit;
- var FileWatcherEventKind;
- (function (FileWatcherEventKind) {
- FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
- 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";
- PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
- PollingInterval[PollingInterval["Low"] = 250] = "Low";
- })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
- /* @internal */
- ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
- function createPollingIntervalBasedLevels(levels) {
- var _a;
- return _a = {},
- _a[PollingInterval.Low] = levels.Low,
- _a[PollingInterval.Medium] = levels.Medium,
- _a[PollingInterval.High] = levels.High,
- _a;
+ ts.isUrl = isUrl;
+ /**
+ * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
+ * like `c:`, `c:\` or `c:/`).
+ */
+ function isRootedDiskPath(path) {
+ return getEncodedRootLength(path) > 0;
}
- 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;
- }
- var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
- pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
- ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
- function getLevel(envVar, level) {
- return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
- }
- function getCustomLevels(baseVariable) {
- var customLevels;
- setCustomLevel("Low");
- setCustomLevel("Medium");
- setCustomLevel("High");
- return customLevels;
- function setCustomLevel(level) {
- var customLevel = getLevel(baseVariable, level);
- if (customLevel) {
- (customLevels || (customLevels = {}))[level] = Number(customLevel);
- }
- }
- }
- function setCustomLevels(baseVariable, levels) {
- var customLevels = getCustomLevels(baseVariable);
- if (customLevels) {
- setLevel("Low");
- setLevel("Medium");
- setLevel("High");
+ 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;
+ /**
+ * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
+ *
+ * ```ts
+ * // POSIX
+ * pathIsAbsolute("/path/to/file.ext") === true
+ * // DOS
+ * pathIsAbsolute("c:/path/to/file.ext") === true
+ * // URL
+ * pathIsAbsolute("file:///path/to/file.ext") === true
+ * // Non-absolute
+ * pathIsAbsolute("path/to/file.ext") === false
+ * pathIsAbsolute("./path/to/file.ext") === false
+ * ```
+ */
+ function pathIsAbsolute(path) {
+ return getEncodedRootLength(path) !== 0;
+ }
+ ts.pathIsAbsolute = pathIsAbsolute;
+ /**
+ * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
+ */
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
+ /**
+ * Determines whether a path is neither relative nor absolute, e.g. "path/to/file".
+ * Also known misleadingly as "non-relative".
+ */
+ function pathIsBareSpecifier(path) {
+ return !pathIsAbsolute(path) && !pathIsRelative(path);
+ }
+ ts.pathIsBareSpecifier = pathIsBareSpecifier;
+ function hasExtension(fileName) {
+ return ts.stringContains(getBaseFileName(fileName), ".");
+ }
+ ts.hasExtension = hasExtension;
+ function fileExtensionIs(path, extension) {
+ return path.length > extension.length && ts.endsWith(path, extension);
+ }
+ ts.fileExtensionIs = fileExtensionIs;
+ function fileExtensionIsOneOf(path, extensions) {
+ for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
+ var extension = extensions_1[_i];
+ if (fileExtensionIs(path, extension)) {
return true;
}
- return false;
- function setLevel(level) {
- levels[level] = customLevels[level] || levels[level];
- }
- }
- function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
- var customLevels = getCustomLevels(baseVariable);
- return (pollingIntervalChanged || customLevels) &&
- createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
}
+ return false;
}
- ts.setCustomPollingValues = setCustomPollingValues;
- /* @internal */
- function createDynamicPriorityPollingWatchFile(host) {
- var watchedFiles = [];
- var changedFilesInLastPoll = [];
- var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
- var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
- var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
- return watchFile;
- function watchFile(fileName, callback, defaultPollingInterval) {
- var file = {
- fileName: fileName,
- callback: callback,
- unchangedPolls: 0,
- mtime: getModifiedTime(fileName)
- };
- watchedFiles.push(file);
- addToPollingIntervalQueue(file, defaultPollingInterval);
- 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
- }
- };
- }
- function createPollingIntervalQueue(pollingInterval) {
- var queue = [];
- queue.pollingInterval = pollingInterval;
- queue.pollIndex = 0;
- queue.pollScheduled = false;
- return queue;
+ ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
+ /**
+ * Determines whether a path has a trailing separator (`/` or `\\`).
+ */
+ function hasTrailingDirectorySeparator(path) {
+ return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
+ //// Path Parsing
+ function isVolumeCharacter(charCode) {
+ 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 /* colon */)
+ return start + 1;
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
+ return start + 3;
}
- 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);
- }
- else {
- ts.Debug.assert(queue.pollIndex === 0);
- queue.pollScheduled = false;
- }
+ 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);
+ // POSIX or UNC
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1; // POSIX: "/" (or non-normalized "\")
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length; // UNC: "//server" or "\\server"
+ return p1 + 1; // UNC: "//server/" or "\\server\"
}
- function pollLowPollingIntervalQueue(queue) {
- // 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);
- }
+ // DOS
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
+ return 3; // DOS: "c:/" or "c:\"
+ if (path.length === 2)
+ return 2; // DOS: "c:" (but not "c:d")
}
- 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--) {
- var watchedFile = queue[pollIndex];
- if (!watchedFile) {
- continue;
- }
- else if (watchedFile.isClosed) {
- queue[pollIndex] = undefined;
- continue;
- }
- 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);
- }
- }
- else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
- 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);
- }
- else if (pollingInterval !== PollingInterval.High) {
- watchedFile.unchangedPolls++;
- queue[pollIndex] = undefined;
- 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;
- }
- 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;
+ // URL
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ 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 /* 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;
+ }
}
- pollIndex = 0;
- definedValueCopyToIndex = 0;
}
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
+ return ~path.length; // URL: "file://server", "http://server"
}
- function pollingIntervalQueue(pollingInterval) {
- switch (pollingInterval) {
- case PollingInterval.Low:
- return lowPollingIntervalQueue;
- case PollingInterval.Medium:
- return mediumPollingIntervalQueue;
- case PollingInterval.High:
- return highPollingIntervalQueue;
+ // 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;
+ 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 = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ // if the path provided is itself the root, then it has not file name.
+ var rootLength = 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(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;
+ function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
+ if (!ts.startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
}
}
- function addToPollingIntervalQueue(file, pollingInterval) {
- pollingIntervalQueue(pollingInterval).push(file);
- scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
- }
- function addChangedFileToLowPollingIntervalQueue(file) {
- changedFilesInLastPoll.push(file);
- scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
+ }
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string") {
+ return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
}
- function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
- if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
- scheduleNextPoll(pollingInterval);
- }
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
+ if (result)
+ return result;
}
- function scheduleNextPoll(pollingInterval) {
- pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
+ 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(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
}
- function getModifiedTime(fileName) {
- return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
+ var baseFileName = getBaseFileName(path);
+ var extensionIndex = baseFileName.lastIndexOf(".");
+ if (extensionIndex >= 0) {
+ return baseFileName.substring(extensionIndex);
}
+ return "";
}
- ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
- function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
- // One file can have multiple watchers
- var fileWatcherCallbacks = ts.createMultiMap();
- var dirWatchers = ts.createMap();
- var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
- return nonPollingWatchFile;
- function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
- var filePath = toCanonicalName(fileName);
- fileWatcherCallbacks.add(filePath, callback);
- var dirPath = ts.getDirectoryPath(filePath) || ".";
- var watcher = dirWatchers.get(dirPath) ||
- createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
- watcher.referenceCount++;
- return {
- close: function () {
- if (watcher.referenceCount === 1) {
- watcher.close();
- dirWatchers.delete(dirPath);
- }
- else {
- watcher.referenceCount--;
- }
- fileWatcherCallbacks.remove(filePath, callback);
- }
- };
+ ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !ts.lastOrUndefined(rest))
+ rest.pop();
+ return __spreadArray([root], rest, true);
+ }
+ /**
+ * 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 (`/`).
+ *
+ * ```ts
+ * // POSIX
+ * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
+ * getPathComponents("/path/to/") === ["/", "path", "to"]
+ * getPathComponents("/") === ["/"]
+ * // DOS
+ * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
+ * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
+ * getPathComponents("c:/") === ["c:/"]
+ * getPathComponents("c:") === ["c:"]
+ * // URL
+ * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
+ * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
+ * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
+ * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
+ * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
+ * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
+ * getPathComponents("file://server/") === ["file://server/"]
+ * getPathComponents("file://server") === ["file://server"]
+ * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
+ * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
+ * getPathComponents("file:///") === ["file:///"]
+ * getPathComponents("file://") === ["file://"]
+ */
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
+ return pathComponents(path, getRootLength(path));
+ }
+ ts.getPathComponents = getPathComponents;
+ //// Path Formatting
+ /**
+ * Formats a parsed path consisting of a root component (at index 0) and zero or more path
+ * segments (at indices > 0).
+ *
+ * ```ts
+ * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
+ * ```
+ */
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
+ }
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ //// Path Normalization
+ /**
+ * Normalize path separators, converting `\` into `/`.
+ */
+ function normalizeSlashes(path) {
+ var index = path.indexOf("\\");
+ if (index === -1) {
+ return path;
}
- function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
- var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
- // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
- if (!ts.isString(relativeFileName)) {
- return;
- }
- var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
- // Some applications save a working file via rename operations
- var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
- if (callbacks) {
- for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
- var fileCallback = callbacks_1[_i];
- fileCallback(fileName, FileWatcherEventKind.Changed);
+ backslashRegExp.lastIndex = index; // prime regex with known position
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ /**
+ * 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 [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
}
}
- },
- /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
- watcher.referenceCount = 0;
- dirWatchers.set(dirPath, watcher);
- return watcher;
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
+ return reduced;
}
- /* @internal */
- function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
- var cache = ts.createMap();
- var callbacksCache = ts.createMultiMap();
- var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
- return function (fileName, callback, pollingInterval, options) {
- var path = toCanonicalFileName(fileName);
- var existing = cache.get(path);
- if (existing) {
- existing.refCount++;
+ ts.reducePathComponents = reducePathComponents;
+ /**
+ * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
+ *
+ * ```ts
+ * // Non-rooted
+ * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
+ * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
+ * // POSIX
+ * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
+ * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
+ * // DOS
+ * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
+ * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
+ * // URL
+ * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
+ * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
+ * ```
+ */
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
}
else {
- cache.set(path, {
- watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
- refCount: 1
- });
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
}
- callbacksCache.add(path, callback);
- return {
- close: function () {
- var watcher = ts.Debug.checkDefined(cache.get(path));
- callbacksCache.remove(path, callback);
- watcher.refCount--;
- if (watcher.refCount)
- return;
- cache.delete(path);
- ts.closeFileWatcherOf(watcher);
- }
- };
- };
+ }
+ return path;
}
- ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
+ ts.combinePaths = combinePaths;
/**
- * Returns true if file status changed
+ * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
+ * `.` and `..` path components are resolved. Trailing directory separators are preserved.
+ *
+ * ```ts
+ * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
+ * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
+ * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
+ * ```
*/
- /*@internal*/
- function onWatchedFileStat(watchedFile, modifiedTime) {
- var oldTime = watchedFile.mtime.getTime();
- var newTime = modifiedTime.getTime();
- if (oldTime !== newTime) {
- watchedFile.mtime = modifiedTime;
- watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
- return true;
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
}
- return false;
- }
- ts.onWatchedFileStat = onWatchedFileStat;
- /*@internal*/
- function getFileWatcherEventKind(oldTime, newTime) {
- return oldTime === 0
- ? FileWatcherEventKind.Created
- : newTime === 0
- ? FileWatcherEventKind.Deleted
- : FileWatcherEventKind.Changed;
- }
- ts.getFileWatcherEventKind = getFileWatcherEventKind;
- /*@internal*/
- ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
- /*@internal*/
- ts.sysLog = ts.noop; // eslint-disable-line prefer-const
- /*@internal*/
- function setSysLog(logger) {
- ts.sysLog = logger;
+ return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths, false)) : normalizeSlashes(path));
}
- ts.setSysLog = setSysLog;
+ ts.resolvePath = resolvePath;
/**
- * 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)
+ * 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 (`/`).
+ *
+ * ```ts
+ * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
+ * ```
*/
- /*@internal*/
- function createDirectoryWatcherSupportingRecursive(host) {
- var cache = ts.createMap();
- var callbackCache = ts.createMultiMap();
- var cacheToUpdateChildWatches = ts.createMap();
- var timerToUpdateChildWatches;
- var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
- var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
- return function (dirName, callback, recursive, options) { return recursive ?
- createDirectoryWatcher(dirName, options, callback) :
- host.watchDirectory(dirName, callback, recursive, options); };
- /**
- * Create the directory watcher for the dirPath.
- */
- function createDirectoryWatcher(dirName, options, callback) {
- var dirPath = toCanonicalFilePath(dirName);
- var directoryWatcher = cache.get(dirPath);
- if (directoryWatcher) {
- directoryWatcher.refCount++;
- }
- else {
- directoryWatcher = {
- watcher: host.watchDirectory(dirName, function (fileName) {
- if (isIgnoredPath(fileName))
- return;
- if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
- // Call the actual callback
- invokeCallbacks(dirPath, fileName);
- // Iterate through existing children and update the watches if needed
- updateChildWatches(dirName, dirPath, options);
- }
- else {
- nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
- }
- }, /*recursive*/ false, options),
- refCount: 1,
- childWatches: ts.emptyArray
- };
- cache.set(dirPath, directoryWatcher);
- updateChildWatches(dirName, dirPath, options);
- }
- var callbackToAdd = callback && { dirName: dirName, callback: callback };
- if (callbackToAdd) {
- callbackCache.add(dirPath, callbackToAdd);
- }
- return {
- dirName: dirName,
- close: function () {
- var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
- if (callbackToAdd)
- callbackCache.remove(dirPath, callbackToAdd);
- directoryWatcher.refCount--;
- if (directoryWatcher.refCount)
- return;
- cache.delete(dirPath);
- ts.closeFileWatcherOf(directoryWatcher);
- directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
- }
- };
- }
- function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
- var fileName;
- var invokeMap;
- if (ts.isString(fileNameOrInvokeMap)) {
- fileName = fileNameOrInvokeMap;
- }
- else {
- invokeMap = fileNameOrInvokeMap;
- }
- // Call the actual callback
- callbackCache.forEach(function (callbacks, rootDirName) {
- if (invokeMap && invokeMap.has(rootDirName))
- return;
- if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
- if (invokeMap) {
- invokeMap.set(rootDirName, true);
- }
- else {
- callbacks.forEach(function (_a) {
- var callback = _a.callback;
- return callback(fileName);
- });
- }
- }
- });
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
+ }
+ ts.getNormalizedPathComponents = getNormalizedPathComponents;
+ function getNormalizedAbsolutePath(fileName, currentDirectory) {
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ }
+ ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
+ function normalizePath(path) {
+ path = normalizeSlashes(path);
+ // Most paths don't require normalization
+ if (!relativePathSegmentRegExp.test(path)) {
+ return path;
}
- function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
- // Iterate through existing children and update the watches if needed
- var parentWatcher = cache.get(dirPath);
- if (parentWatcher && host.directoryExists(dirName)) {
- // Schedule the update and postpone invoke for callbacks
- scheduleUpdateChildWatches(dirName, dirPath, options);
- return;
+ // Some paths only require cleanup of `/./` or leading `./`
+ var simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, "");
+ if (simplified !== path) {
+ path = simplified;
+ if (!relativePathSegmentRegExp.test(path)) {
+ return path;
}
- // Call the actual callbacks and remove child watches
- invokeCallbacks(dirPath, fileName);
- removeChildWatches(parentWatcher);
}
- function scheduleUpdateChildWatches(dirName, dirPath, options) {
- if (!cacheToUpdateChildWatches.has(dirPath)) {
- cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
- }
- if (timerToUpdateChildWatches) {
- host.clearTimeout(timerToUpdateChildWatches);
- timerToUpdateChildWatches = undefined;
- }
- timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
+ // Other paths require full normalization
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
+ return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.normalizePath = normalizePath;
+ function getPathWithoutRoot(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ return pathComponents.slice(1).join(ts.directorySeparator);
+ }
+ function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
+ return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
+ }
+ ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
+ function toPath(fileName, basePath, getCanonicalFileName) {
+ var nonCanonicalizedPath = isRootedDiskPath(fileName)
+ ? normalizePath(fileName)
+ : getNormalizedAbsolutePath(fileName, basePath);
+ return getCanonicalFileName(nonCanonicalizedPath);
+ }
+ ts.toPath = toPath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
}
- function onTimerToUpdateChildWatches() {
- timerToUpdateChildWatches = undefined;
- ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
- var start = ts.timestamp();
- var invokeMap = ts.createMap();
- while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
- var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
- ts.Debug.assert(!done);
- cacheToUpdateChildWatches.delete(dirPath);
- // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
- // to ensure that all the changes are reflected at this time
- invokeCallbacks(dirPath, invokeMap);
- updateChildWatches(dirName, dirPath, options);
- }
- ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
- callbackCache.forEach(function (callbacks, rootDirName) {
- if (invokeMap.has(rootDirName)) {
- callbacks.forEach(function (_a) {
- var callback = _a.callback, dirName = _a.dirName;
- return callback(dirName);
- });
- }
- });
- var elapsed = ts.timestamp() - start;
- ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
+ else {
+ return { path: root, parts: parts };
}
- function removeChildWatches(parentWatcher) {
- if (!parentWatcher)
- return;
- var existingChildWatches = parentWatcher.childWatches;
- parentWatcher.childWatches = ts.emptyArray;
- for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
- var childWatcher = existingChildWatches_1[_i];
- childWatcher.close();
- removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
- }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function removeTrailingDirectorySeparator(path) {
+ if (hasTrailingDirectorySeparator(path)) {
+ return path.substr(0, path.length - 1);
}
- function updateChildWatches(dirName, dirPath, options) {
- // Iterate through existing children and update the watches if needed
- var parentWatcher = cache.get(dirPath);
- if (parentWatcher) {
- parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
- }
+ return path;
+ }
+ ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
+ function ensureTrailingDirectorySeparator(path) {
+ if (!hasTrailingDirectorySeparator(path)) {
+ return path + ts.directorySeparator;
}
- /**
- * Watch the directories in the parentDir
- */
- function watchChildDirectories(parentDir, existingChildWatches, options) {
- var newChildWatches;
- ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
- var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
- // 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 !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
- }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return 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, options);
- addChildDirectoryWatcher(result);
- }
- /**
- * Add child directory watcher to the new ChildDirectoryWatcher list
- */
- function addChildDirectoryWatcher(childWatcher) {
- (newChildWatches || (newChildWatches = [])).push(childWatcher);
- }
+ return path;
+ }
+ ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
+ /**
+ * 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.
+ *
+ * ```ts
+ * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
+ * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
+ * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
+ * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
+ * ```
+ */
+ function ensurePathIsNonModuleName(path) {
+ return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
+ }
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
+ //// Path Comparisons
+ // check path for these segments: '', '.'. '..'
+ var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/;
+ function comparePathsWorker(a, b, componentComparer) {
+ if (a === b)
+ return 0 /* EqualTo */;
+ if (a === undefined)
+ return -1 /* LessThan */;
+ if (b === undefined)
+ return 1 /* GreaterThan */;
+ // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
+ // need to perform path reduction.
+ var aRoot = a.substring(0, getRootLength(a));
+ var bRoot = b.substring(0, getRootLength(b));
+ var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
+ if (result !== 0 /* EqualTo */) {
+ return result;
}
- function isIgnoredPath(path) {
- return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ // NOTE: Performance optimization - shortcut if there are no relative path segments in
+ // the non-root portion of the path
+ var aRest = a.substring(aRoot.length);
+ var bRest = b.substring(bRoot.length);
+ if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
+ return componentComparer(aRest, bRest);
}
- function isInPath(path, searchPath) {
- if (ts.stringContains(path, searchPath))
- return true;
- if (host.useCaseSensitiveFileNames)
- return false;
- return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ // The path contains a relative path segment. Normalize the paths and perform a slower component
+ // by component comparison.
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
+ var sharedLength = Math.min(aComponents.length, bComponents.length);
+ for (var i = 1; i < sharedLength; i++) {
+ var result_2 = componentComparer(aComponents[i], bComponents[i]);
+ if (result_2 !== 0 /* EqualTo */) {
+ return result_2;
+ }
}
+ return ts.compareValues(aComponents.length, bComponents.length);
}
- ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
- /*@internal*/
- var FileSystemEntryKind;
- (function (FileSystemEntryKind) {
- FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
- FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
- })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
- /*@internal*/
- function createFileWatcherCallback(callback) {
- return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
- }
- ts.createFileWatcherCallback = createFileWatcherCallback;
- function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
- return function (eventName) {
- if (eventName === "rename") {
- callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
- }
- else {
- // Change
- callback(fileName, FileWatcherEventKind.Changed);
- }
- };
+ /**
+ * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
+ */
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
}
- 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)));
- }
- };
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ /**
+ * Performs a case-insensitive comparison of two paths.
+ */
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
}
- /*@internal*/
- function createSystemWatchFunctions(_a) {
- var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory;
- var dynamicPollingWatchFile;
- var nonPollingWatchFile;
- var hostRecursiveDirectoryWatcher;
- return {
- watchFile: watchFile,
- watchDirectory: watchDirectory
- };
- function watchFile(fileName, callback, pollingInterval, options) {
- options = updateOptionsForWatchFile(options, useNonPollingWatchers);
- var watchFileKind = ts.Debug.checkDefined(options.watchFile);
- switch (watchFileKind) {
- case ts.WatchFileKind.FixedPollingInterval:
- return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
- case ts.WatchFileKind.PriorityPollingInterval:
- return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
- case ts.WatchFileKind.DynamicPriorityPolling:
- return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
- case ts.WatchFileKind.UseFsEvents:
- return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists),
- /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
- case ts.WatchFileKind.UseFsEventsOnParentDirectory:
- if (!nonPollingWatchFile) {
- nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
- }
- return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
- default:
- ts.Debug.assertNever(watchFileKind);
- }
- }
- function ensureDynamicPollingWatchFile() {
- return dynamicPollingWatchFile ||
- (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
}
- function updateOptionsForWatchFile(options, useNonPollingWatchers) {
- if (options && options.watchFile !== undefined)
- return options;
- switch (tscWatchFile) {
- case "PriorityPollingInterval":
- // Use polling interval based on priority when create watch using host.watchFile
- return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
- case "DynamicPriorityPolling":
- // Use polling interval but change the interval depending on file changes and their default polling interval
- return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
- case "UseFsEvents":
- // Use notifications from FS to watch with falling back to fs.watchFile
- return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
- case "UseFsEventsWithFallbackDynamicPolling":
- // Use notifications from FS to watch with falling back to dynamic watch file
- return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
- case "UseFsEventsOnParentDirectory":
- useNonPollingWatchers = true;
- // fall through
- default:
- return useNonPollingWatchers ?
- // Use notifications from FS to watch with falling back to fs.watchFile
- generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
- // Default to do not use fixed polling interval
- { watchFile: ts.WatchFileKind.FixedPollingInterval };
- }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
}
- function generateWatchFileOptions(watchFile, fallbackPolling, options) {
- var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
- return {
- watchFile: watchFile,
- fallbackPolling: defaultFallbackPolling === undefined ?
- fallbackPolling :
- defaultFallbackPolling
- };
+ return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
+ }
+ ts.comparePaths = comparePaths;
+ function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
}
- function watchDirectory(directoryName, callback, recursive, options) {
- if (fsSupportsRecursiveFsWatch) {
- return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
- }
- if (!hostRecursiveDirectoryWatcher) {
- hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
- useCaseSensitiveFileNames: useCaseSensitiveFileNames,
- directoryExists: directoryExists,
- getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
- watchDirectory: nonRecursiveWatchDirectory,
- realpath: realpath,
- setTimeout: setTimeout,
- clearTimeout: clearTimeout
- });
- }
- return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
}
- function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
- ts.Debug.assert(!recursive);
- options = updateOptionsForWatchDirectory(options);
- var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
- switch (watchDirectoryKind) {
- case ts.WatchDirectoryKind.FixedPollingInterval:
- return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
- /*options*/ undefined);
- case ts.WatchDirectoryKind.DynamicPriorityPolling:
- return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
- /*options*/ undefined);
- case ts.WatchDirectoryKind.UseFsEvents:
- return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
- default:
- ts.Debug.assertNever(watchDirectoryKind);
- }
+ if (parent === undefined || child === undefined)
+ return false;
+ if (parent === child)
+ return true;
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
+ if (childComponents.length < parentComponents.length) {
+ return false;
}
- function updateOptionsForWatchDirectory(options) {
- if (options && options.watchDirectory !== undefined)
- return options;
- switch (tscWatchDirectory) {
- case "RecursiveDirectoryUsingFsWatchFile":
- // Use polling interval based on priority when create watch using host.watchFile
- return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
- case "RecursiveDirectoryUsingDynamicPriorityPolling":
- // Use polling interval but change the interval depending on file changes and their default polling interval
- return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
- default:
- var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
- return {
- watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
- fallbackPolling: defaultFallbackPolling !== undefined ?
- defaultFallbackPolling :
- undefined
- };
+ var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
+ for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
+ if (!equalityComparer(parentComponents[i], childComponents[i])) {
+ return false;
}
}
+ return true;
}
- ts.createSystemWatchFunctions = createSystemWatchFunctions;
+ ts.containsPath = containsPath;
/**
- * patch writefile to create folder before writing the file
+ * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
+ * Comparison is case-sensitive between the canonical paths.
+ *
+ * Use `containsPath` if file names are not already reduced and absolute.
*/
- /*@internal*/
- function patchWriteFileEnsuringDirectory(sys) {
- // patch writefile to create folder before writing the file
- var originalWriteFile = sys.writeFile;
- sys.writeFile = function (path, data, writeBom) {
- return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); });
- };
+ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
+ var canonicalFileName = getCanonicalFileName(fileName);
+ var canonicalDirectoryName = getCanonicalFileName(directoryName);
+ return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
}
- ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
- function getNodeMajorVersion() {
- if (typeof process === "undefined") {
- return undefined;
+ ts.startsWithDirectory = startsWithDirectory;
+ //// Relative Paths
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
+ break;
}
- var version = process.version;
- if (!version) {
- return undefined;
+ if (start === 0) {
+ return toComponents;
}
- var dot = version.indexOf(".");
- if (dot === -1) {
- return undefined;
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
- return parseInt(version.substring(1, dot));
+ return __spreadArray(__spreadArray([""], relative, true), components, true);
}
- ts.getNodeMajorVersion = getNodeMajorVersion;
- // TODO: GH#18217 this is used as if it's certainly defined in many places.
- // eslint-disable-next-line prefer-const
- 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 nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
- 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");
+ ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
+ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
+ return !isRootedDiskPath(absoluteOrRelativePath)
+ ? absoluteOrRelativePath
+ : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
+ }
+ ts.convertToRelativePath = convertToRelativePath;
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
+ }
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
+ }
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
+ function forEachAncestorDirectory(directory, callback) {
+ while (true) {
+ var result = callback(directory);
+ if (result !== undefined) {
+ return result;
}
- catch (_a) {
- _crypto = undefined;
+ var parentPath = getDirectoryPath(directory);
+ if (parentPath === directory) {
+ return undefined;
}
- var activeSession;
- var profilePath = "./profile.cpuprofile";
- var Buffer = require("buffer").Buffer;
- var nodeVersion = getNodeMajorVersion();
- var isNode4OrLater = nodeVersion >= 4;
- var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
- var platform = _os.platform();
- var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
- var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
- var _b = createSystemWatchFunctions({
- pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
- getModifiedTime: getModifiedTime,
- setTimeout: setTimeout,
- clearTimeout: clearTimeout,
- fsWatch: fsWatch,
- useCaseSensitiveFileNames: useCaseSensitiveFileNames,
- fileExists: fileExists,
- // 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)
- fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
- directoryExists: directoryExists,
- getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
- realpath: realpath,
- tscWatchFile: process.env.TSC_WATCHFILE,
- useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
- tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
- }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
- var nodeSystem = {
- args: process.argv.slice(2),
- newLine: _os.EOL,
- useCaseSensitiveFileNames: useCaseSensitiveFileNames,
- write: function (s) {
- process.stdout.write(s);
- },
- writeOutputIsTTY: function () {
- return process.stdout.isTTY;
- },
- readFile: readFile,
- writeFile: writeFile,
- watchFile: watchFile,
- watchDirectory: watchDirectory,
- resolvePath: function (path) { return _path.resolve(path); },
- fileExists: fileExists,
- directoryExists: directoryExists,
- createDirectory: function (directoryName) {
- if (!nodeSystem.directoryExists(directoryName)) {
- // Wrapped in a try-catch to prevent crashing if we are in a race
- // with another copy of ourselves to create the same directory
- try {
- _fs.mkdirSync(directoryName);
- }
- catch (e) {
- if (e.code !== "EEXIST") {
- // Failed for some other reason (access denied?); still throw
- throw e;
- }
- }
- }
- },
- getExecutingFilePath: function () {
- return __filename;
- },
- getCurrentDirectory: function () {
- return process.cwd();
- },
- getDirectories: getDirectories,
- getEnvironmentVariable: function (name) {
- return process.env[name] || "";
- },
- readDirectory: readDirectory,
- getModifiedTime: getModifiedTime,
- setModifiedTime: setModifiedTime,
- deleteFile: deleteFile,
- createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
- createSHA256Hash: _crypto ? createSHA256Hash : undefined,
- getMemoryUsage: function () {
- if (global.gc) {
- global.gc();
- }
- return process.memoryUsage().heapUsed;
- },
- getFileSize: function (path) {
- try {
- var stat = _fs.statSync(path);
- if (stat.isFile()) {
- return stat.size;
- }
- }
- catch ( /*ignore*/_a) { /*ignore*/ }
- return 0;
- },
- exit: function (exitCode) {
- disableCPUProfiler(function () { return process.exit(exitCode); });
- },
- enableCPUProfiler: enableCPUProfiler,
- disableCPUProfiler: disableCPUProfiler,
- realpath: realpath,
- debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
- tryEnableSourceMapsForHost: function () {
- try {
- require("source-map-support").install();
- }
- catch (_a) {
- // Could not enable source maps.
- }
- },
- setTimeout: setTimeout,
- clearTimeout: clearTimeout,
- clearScreen: function () {
- process.stdout.write("\x1Bc");
- },
- setBlocking: function () {
- if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
- process.stdout._handle.setBlocking(true);
- }
- },
- bufferFrom: bufferFrom,
- base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
- base64encode: function (input) { return bufferFrom(input).toString("base64"); },
- require: function (baseDir, moduleName) {
- try {
- var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
- return { module: require(modulePath), modulePath: modulePath, error: undefined };
- }
- catch (error) {
- return { module: undefined, modulePath: undefined, error: error };
- }
- }
- };
- return nodeSystem;
- /**
- * Uses the builtin inspector APIs to capture a CPU profile
- * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
- */
- function enableCPUProfiler(path, cb) {
- if (activeSession) {
- cb();
- return false;
- }
- var inspector = require("inspector");
- if (!inspector || !inspector.Session) {
- cb();
- return false;
+ directory = parentPath;
+ }
+ }
+ ts.forEachAncestorDirectory = forEachAncestorDirectory;
+ function isNodeModulesDirectory(dirPath) {
+ return ts.endsWith(dirPath, "/node_modules");
+ }
+ ts.isNodeModulesDirectory = isNodeModulesDirectory;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ /**
+ * djb2 hashing algorithm
+ * http://www.cse.yorku.ca/~oz/hash.html
+ */
+ /* @internal */
+ function generateDjb2Hash(data) {
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
+ }
+ ts.generateDjb2Hash = generateDjb2Hash;
+ /**
+ * 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) { // Also tests that we won't set the property if it doesn't exist.
+ Error.stackTraceLimit = 100;
+ }
+ }
+ ts.setStackTraceLimit = setStackTraceLimit;
+ var FileWatcherEventKind;
+ (function (FileWatcherEventKind) {
+ FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
+ 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";
+ PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
+ PollingInterval[PollingInterval["Low"] = 250] = "Low";
+ })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
+ /* @internal */
+ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
+ /* @internal */
+ function getModifiedTime(host, fileName) {
+ return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
+ }
+ ts.getModifiedTime = getModifiedTime;
+ function createPollingIntervalBasedLevels(levels) {
+ var _a;
+ return _a = {},
+ _a[PollingInterval.Low] = levels.Low,
+ _a[PollingInterval.Medium] = levels.Medium,
+ _a[PollingInterval.High] = levels.High,
+ _a;
+ }
+ 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;
+ }
+ var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
+ pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
+ ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
+ function getLevel(envVar, level) {
+ return system.getEnvironmentVariable("".concat(envVar, "_").concat(level.toUpperCase()));
+ }
+ function getCustomLevels(baseVariable) {
+ var customLevels;
+ setCustomLevel("Low");
+ setCustomLevel("Medium");
+ setCustomLevel("High");
+ return customLevels;
+ function setCustomLevel(level) {
+ var customLevel = getLevel(baseVariable, level);
+ if (customLevel) {
+ (customLevels || (customLevels = {}))[level] = Number(customLevel);
}
- var session = new inspector.Session();
- session.connect();
- session.post("Profiler.enable", function () {
- session.post("Profiler.start", function () {
- activeSession = session;
- profilePath = path;
- cb();
- });
- });
+ }
+ }
+ function setCustomLevels(baseVariable, levels) {
+ var customLevels = getCustomLevels(baseVariable);
+ if (customLevels) {
+ setLevel("Low");
+ setLevel("Medium");
+ setLevel("High");
return true;
}
- /**
- * Strips non-TS paths from the profile, so users with private projects shouldn't
- * need to worry about leaking paths by submitting a cpu profile to us
- */
- function cleanupPaths(profile) {
- var externalFileCounter = 0;
- var remappedPaths = ts.createMap();
- var normalizedDir = ts.normalizeSlashes(__dirname);
- // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
- var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
- for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
- var node = _a[_i];
- if (node.callFrame.url) {
- var url = ts.normalizeSlashes(node.callFrame.url);
- if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
- node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
- }
- else if (!nativePattern.test(url)) {
- node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
- externalFileCounter++;
- }
- }
- }
- return profile;
+ return false;
+ function setLevel(level) {
+ levels[level] = customLevels[level] || levels[level];
}
- function disableCPUProfiler(cb) {
- if (activeSession && activeSession !== "stopping") {
- var s_1 = activeSession;
- activeSession.post("Profiler.stop", function (err, _a) {
- var profile = _a.profile;
- if (!err) {
- try {
- if (_fs.statSync(profilePath).isDirectory()) {
- profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
- }
- }
- catch (_b) {
- // do nothing and ignore fallible fs operation
- }
- try {
- _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
- }
- catch (_c) {
- // do nothing and ignore fallible fs operation
- }
- _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
- }
- activeSession = undefined;
- s_1.disconnect();
- cb();
- });
- activeSession = "stopping";
- return true;
- }
- else {
- cb();
- return false;
+ }
+ function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
+ var customLevels = getCustomLevels(baseVariable);
+ return (pollingIntervalChanged || customLevels) &&
+ createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
+ }
+ }
+ ts.setCustomPollingValues = setCustomPollingValues;
+ function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) {
+ var definedValueCopyToIndex = pollIndex;
+ // Max visit would be all elements of the queue
+ for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) {
+ var watchedFile = queue[pollIndex];
+ if (!watchedFile) {
+ continue;
+ }
+ else if (watchedFile.isClosed) {
+ queue[pollIndex] = undefined;
+ continue;
+ }
+ // Only files polled count towards chunkSize
+ chunkSize--;
+ var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName));
+ if (watchedFile.isClosed) {
+ // Closed watcher as part of callback
+ queue[pollIndex] = undefined;
+ continue;
+ }
+ callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged);
+ // Defragment the queue while we are at it
+ if (queue[pollIndex]) {
+ // Copy this file to the non hole location
+ if (definedValueCopyToIndex < pollIndex) {
+ queue[definedValueCopyToIndex] = watchedFile;
+ queue[pollIndex] = undefined;
}
+ definedValueCopyToIndex++;
}
- function bufferFrom(input, encoding) {
- // See https://github.com/Microsoft/TypeScript/issues/25652
- return Buffer.from && Buffer.from !== Int8Array.from
- ? Buffer.from(input, encoding)
- : new Buffer(input, encoding);
+ }
+ // Return next poll index
+ return pollIndex;
+ function nextPollIndex() {
+ pollIndex++;
+ if (pollIndex === queue.length) {
+ if (definedValueCopyToIndex < pollIndex) {
+ // There are holes from definedValueCopyToIndex to end of queue, change queue size
+ queue.length = definedValueCopyToIndex;
+ }
+ pollIndex = 0;
+ definedValueCopyToIndex = 0;
}
- function isFileSystemCaseSensitive() {
- // win32\win64 are case insensitive platforms
- if (platform === "win32" || platform === "win64") {
- return false;
+ }
+ }
+ /* @internal */
+ function createDynamicPriorityPollingWatchFile(host) {
+ var watchedFiles = [];
+ var changedFilesInLastPoll = [];
+ var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
+ var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
+ var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
+ return watchFile;
+ function watchFile(fileName, callback, defaultPollingInterval) {
+ var file = {
+ fileName: fileName,
+ callback: callback,
+ unchangedPolls: 0,
+ mtime: getModifiedTime(host, fileName)
+ };
+ watchedFiles.push(file);
+ addToPollingIntervalQueue(file, defaultPollingInterval);
+ 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
}
- // If this file exists under a different case, we must be case-insensitve.
- return !fileExists(swapCase(__filename));
+ };
+ }
+ function createPollingIntervalQueue(pollingInterval) {
+ var queue = [];
+ queue.pollingInterval = pollingInterval;
+ queue.pollIndex = 0;
+ queue.pollScheduled = false;
+ return queue;
+ }
+ 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);
}
- /** Convert all lowercase chars to uppercase, and vice-versa */
- function swapCase(s) {
- return s.replace(/\w/g, function (ch) {
- var up = ch.toUpperCase();
- return ch === up ? ch.toLowerCase() : up;
- });
+ else {
+ ts.Debug.assert(queue.pollIndex === 0);
+ queue.pollScheduled = false;
}
- function fsWatchFileWorker(fileName, callback, pollingInterval) {
- _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
- var eventKind;
- return {
- 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;
- }
- 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;
+ }
+ function pollLowPollingIntervalQueue(queue) {
+ // 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) {
+ return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat);
+ function onWatchFileStat(watchedFile, pollIndex, fileChanged) {
+ if (fileChanged) {
+ watchedFile.unchangedPolls = 0;
+ // Changed files go to changedFilesInLastPoll queue
+ if (queue !== changedFilesInLastPoll) {
+ queue[pollIndex] = undefined;
+ addChangedFileToLowPollingIntervalQueue(watchedFile);
}
- callback(fileName, eventKind);
}
- }
- function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
- var options;
- var lastDirectoryPartWithDirectorySeparator;
- var lastDirectoryPart;
- if (isLinuxOrMacOs) {
- lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
- lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
+ else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
+ watchedFile.unchangedPolls++;
}
- /** 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)
+ 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);
+ }
+ else if (pollingInterval !== PollingInterval.High) {
+ watchedFile.unchangedPolls++;
+ queue[pollIndex] = undefined;
+ addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
+ }
+ }
+ }
+ function pollingIntervalQueue(pollingInterval) {
+ switch (pollingInterval) {
+ case PollingInterval.Low:
+ return lowPollingIntervalQueue;
+ case PollingInterval.Medium:
+ return mediumPollingIntervalQueue;
+ case PollingInterval.High:
+ return highPollingIntervalQueue;
+ }
+ }
+ function addToPollingIntervalQueue(file, pollingInterval) {
+ pollingIntervalQueue(pollingInterval).push(file);
+ scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
+ }
+ function addChangedFileToLowPollingIntervalQueue(file) {
+ changedFilesInLastPoll.push(file);
+ scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
+ }
+ function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
+ if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
+ scheduleNextPoll(pollingInterval);
+ }
+ }
+ function scheduleNextPoll(pollingInterval) {
+ pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
+ }
+ }
+ ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
+ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
+ // One file can have multiple watchers
+ var fileWatcherCallbacks = ts.createMultiMap();
+ var dirWatchers = new ts.Map();
+ var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
+ return nonPollingWatchFile;
+ function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
+ var filePath = toCanonicalName(fileName);
+ fileWatcherCallbacks.add(filePath, callback);
+ var dirPath = ts.getDirectoryPath(filePath) || ".";
+ var watcher = dirWatchers.get(dirPath) ||
+ createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
+ watcher.referenceCount++;
+ return {
+ close: function () {
+ if (watcher.referenceCount === 1) {
watcher.close();
- watcher = undefined;
+ dirWatchers.delete(dirPath);
}
- };
- /**
- * Invoke the callback with rename and update the watcher if not closed
- * @param createWatcher
- */
- function invokeCallbackAndUpdateWatcher(createWatcher) {
- ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
- // Call the callback for current directory
- callback("rename", "");
- // If watcher is not closed, update it
- if (watcher) {
- watcher.close();
- watcher = createWatcher();
+ else {
+ watcher.referenceCount--;
}
+ fileWatcherCallbacks.remove(filePath, callback);
}
- /**
- * 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 (fsSupportsRecursiveFsWatch) {
- options = { persistent: true, recursive: !!recursive };
- }
- else {
- options = { persistent: true };
- }
- }
- try {
- var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
- callbackChangingToMissingFileSystemEntry :
- 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();
+ };
+ }
+ function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
+ var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
+ // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
+ if (!ts.isString(relativeFileName))
+ return;
+ var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
+ // Some applications save a working file via rename operations
+ var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
+ if (callbacks) {
+ for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
+ var fileCallback = callbacks_1[_i];
+ fileCallback(fileName, FileWatcherEventKind.Changed);
}
}
- function callbackChangingToMissingFileSystemEntry(event, relativeName) {
- // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
- // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
- return event === "rename" &&
- (!relativeName ||
- relativeName === lastDirectoryPart ||
- relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
- !fileSystemEntryExists(fileOrDirectory, entryKind) ?
- invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
- callback(event, relativeName);
- }
- /**
- * 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() {
- ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
- return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
- }
- /**
- * 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 watchFile(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);
- }
- }, fallbackPollingInterval, fallbackOptions);
+ },
+ /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
+ watcher.referenceCount = 0;
+ dirWatchers.set(dirPath, watcher);
+ return watcher;
+ }
+ }
+ function createFixedChunkSizePollingWatchFile(host) {
+ var watchedFiles = [];
+ var pollIndex = 0;
+ var pollScheduled;
+ return watchFile;
+ function watchFile(fileName, callback) {
+ var file = {
+ fileName: fileName,
+ callback: callback,
+ mtime: getModifiedTime(host, fileName)
+ };
+ watchedFiles.push(file);
+ scheduleNextPoll();
+ return {
+ close: function () {
+ file.isClosed = true;
+ ts.unorderedRemoveItem(watchedFiles, file);
}
+ };
+ }
+ function pollQueue() {
+ pollScheduled = undefined;
+ pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]);
+ scheduleNextPoll();
+ }
+ function scheduleNextPoll() {
+ if (!watchedFiles.length || pollScheduled)
+ return;
+ pollScheduled = host.setTimeout(pollQueue, PollingInterval.High);
+ }
+ }
+ /* @internal */
+ function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
+ var cache = new ts.Map();
+ var callbacksCache = ts.createMultiMap();
+ var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
+ return function (fileName, callback, pollingInterval, options) {
+ var path = toCanonicalFileName(fileName);
+ var existing = cache.get(path);
+ if (existing) {
+ existing.refCount++;
}
- function readFileWorker(fileName, _encoding) {
- var buffer;
- try {
- buffer = _fs.readFileSync(fileName);
- }
- catch (e) {
- return undefined;
- }
- var len = buffer.length;
- if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
- // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
- // flip all byte pairs and treat as little endian.
- len &= ~1; // Round down to a multiple of 2
- for (var i = 0; i < len; i += 2) {
- var temp = buffer[i];
- buffer[i] = buffer[i + 1];
- buffer[i + 1] = temp;
- }
- 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);
+ else {
+ cache.set(path, {
+ watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
+ refCount: 1
+ });
+ }
+ callbacksCache.add(path, callback);
+ return {
+ close: function () {
+ var watcher = ts.Debug.checkDefined(cache.get(path));
+ callbacksCache.remove(path, callback);
+ watcher.refCount--;
+ if (watcher.refCount)
+ return;
+ cache.delete(path);
+ ts.closeFileWatcherOf(watcher);
}
- // Default is UTF-8 with no byte order mark
- return buffer.toString("utf8");
+ };
+ };
+ }
+ ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
+ /**
+ * Returns true if file status changed
+ */
+ /*@internal*/
+ function onWatchedFileStat(watchedFile, modifiedTime) {
+ var oldTime = watchedFile.mtime.getTime();
+ var newTime = modifiedTime.getTime();
+ if (oldTime !== newTime) {
+ watchedFile.mtime = modifiedTime;
+ watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
+ return true;
+ }
+ return false;
+ }
+ ts.onWatchedFileStat = onWatchedFileStat;
+ /*@internal*/
+ function getFileWatcherEventKind(oldTime, newTime) {
+ return oldTime === 0
+ ? FileWatcherEventKind.Created
+ : newTime === 0
+ ? FileWatcherEventKind.Deleted
+ : FileWatcherEventKind.Changed;
+ }
+ ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
+ /*@internal*/
+ ts.sysLog = ts.noop; // eslint-disable-line prefer-const
+ /*@internal*/
+ function setSysLog(logger) {
+ ts.sysLog = logger;
+ }
+ ts.setSysLog = setSysLog;
+ /**
+ * 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 createDirectoryWatcherSupportingRecursive(_a) {
+ var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout;
+ var cache = new ts.Map();
+ var callbackCache = ts.createMultiMap();
+ var cacheToUpdateChildWatches = new ts.Map();
+ var timerToUpdateChildWatches;
+ var filePathComparer = ts.getStringComparer(!useCaseSensitiveFileNames);
+ var toCanonicalFilePath = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
+ return function (dirName, callback, recursive, options) { return recursive ?
+ createDirectoryWatcher(dirName, options, callback) :
+ watchDirectory(dirName, callback, recursive, options); };
+ /**
+ * Create the directory watcher for the dirPath.
+ */
+ function createDirectoryWatcher(dirName, options, callback) {
+ var dirPath = toCanonicalFilePath(dirName);
+ var directoryWatcher = cache.get(dirPath);
+ if (directoryWatcher) {
+ directoryWatcher.refCount++;
}
- function readFile(fileName, _encoding) {
- ts.perfLogger.logStartReadFile(fileName);
- var file = readFileWorker(fileName, _encoding);
- ts.perfLogger.logStopReadFile();
- return file;
+ else {
+ directoryWatcher = {
+ watcher: watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName, options))
+ return;
+ if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
+ // Call the actual callback
+ invokeCallbacks(dirPath, fileName);
+ // Iterate through existing children and update the watches if needed
+ updateChildWatches(dirName, dirPath, options);
+ }
+ else {
+ nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
+ }
+ }, /*recursive*/ false, options),
+ refCount: 1,
+ childWatches: ts.emptyArray
+ };
+ cache.set(dirPath, directoryWatcher);
+ updateChildWatches(dirName, dirPath, options);
}
- function writeFile(fileName, data, writeByteOrderMark) {
- ts.perfLogger.logEvent("WriteFile: " + fileName);
- // If a BOM is required, emit one
- if (writeByteOrderMark) {
- data = byteOrderMarkIndicator + data;
- }
- var fd;
- try {
- fd = _fs.openSync(fileName, "w");
- _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
- }
- finally {
- if (fd !== undefined) {
- _fs.closeSync(fd);
- }
+ var callbackToAdd = callback && { dirName: dirName, callback: callback };
+ if (callbackToAdd) {
+ callbackCache.add(dirPath, callbackToAdd);
+ }
+ return {
+ dirName: dirName,
+ close: function () {
+ var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
+ if (callbackToAdd)
+ callbackCache.remove(dirPath, callbackToAdd);
+ directoryWatcher.refCount--;
+ if (directoryWatcher.refCount)
+ return;
+ cache.delete(dirPath);
+ ts.closeFileWatcherOf(directoryWatcher);
+ directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
}
+ };
+ }
+ function invokeCallbacks(dirPath, fileNameOrInvokeMap, fileNames) {
+ var fileName;
+ var invokeMap;
+ if (ts.isString(fileNameOrInvokeMap)) {
+ fileName = fileNameOrInvokeMap;
}
- function getAccessibleFileSystemEntries(path) {
- ts.perfLogger.logEvent("ReadDir: " + (path || "."));
- try {
- var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
- var files = [];
- var directories = [];
- for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
- var dirent = entries_2[_i];
- // withFileTypes is not supported before Node 10.10.
- var entry = typeof dirent === "string" ? dirent : dirent.name;
- // 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;
- }
- var stat = void 0;
- if (typeof dirent === "string" || dirent.isSymbolicLink()) {
- var name = ts.combinePaths(path, entry);
- try {
- stat = _fs.statSync(name);
+ else {
+ invokeMap = fileNameOrInvokeMap;
+ }
+ // Call the actual callback
+ callbackCache.forEach(function (callbacks, rootDirName) {
+ var _a;
+ if (invokeMap && invokeMap.get(rootDirName) === true)
+ return;
+ if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
+ if (invokeMap) {
+ if (fileNames) {
+ var existing = invokeMap.get(rootDirName);
+ if (existing) {
+ (_a = existing).push.apply(_a, fileNames);
}
- catch (e) {
- continue;
+ else {
+ invokeMap.set(rootDirName, fileNames.slice());
}
}
else {
- stat = dirent;
- }
- if (stat.isFile()) {
- files.push(entry);
- }
- else if (stat.isDirectory()) {
- directories.push(entry);
+ invokeMap.set(rootDirName, true);
}
}
- files.sort();
- directories.sort();
- return { files: files, directories: directories };
- }
- catch (e) {
- return ts.emptyFileSystemEntries;
- }
- }
- function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
- }
- function fileSystemEntryExists(path, entryKind) {
- try {
- var stat = _fs.statSync(path);
- switch (entryKind) {
- case 0 /* File */: return stat.isFile();
- case 1 /* Directory */: return stat.isDirectory();
- default: return false;
+ else {
+ callbacks.forEach(function (_a) {
+ var callback = _a.callback;
+ return callback(fileName);
+ });
}
}
- catch (e) {
- return false;
- }
- }
- function fileExists(path) {
- return fileSystemEntryExists(path, 0 /* File */);
+ });
+ }
+ function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
+ // Iterate through existing children and update the watches if needed
+ var parentWatcher = cache.get(dirPath);
+ if (parentWatcher && directoryExists(dirName)) {
+ // Schedule the update and postpone invoke for callbacks
+ scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
+ return;
}
- function directoryExists(path) {
- return fileSystemEntryExists(path, 1 /* Directory */);
+ // Call the actual callbacks and remove child watches
+ invokeCallbacks(dirPath, fileName);
+ removeChildWatches(parentWatcher);
+ }
+ function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) {
+ var existing = cacheToUpdateChildWatches.get(dirPath);
+ if (existing) {
+ existing.fileNames.push(fileName);
}
- function getDirectories(path) {
- return getAccessibleFileSystemEntries(path).directories.slice();
+ else {
+ cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
}
- function realpath(path) {
- try {
- return _fs.realpathSync(path);
- }
- catch (_a) {
- return path;
- }
+ if (timerToUpdateChildWatches) {
+ clearTimeout(timerToUpdateChildWatches);
+ timerToUpdateChildWatches = undefined;
}
- function getModifiedTime(path) {
- try {
- return _fs.statSync(path).mtime;
- }
- catch (e) {
- return undefined;
- }
+ timerToUpdateChildWatches = setTimeout(onTimerToUpdateChildWatches, 1000);
+ }
+ function onTimerToUpdateChildWatches() {
+ timerToUpdateChildWatches = undefined;
+ ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: ".concat(cacheToUpdateChildWatches.size));
+ var start = ts.timestamp();
+ var invokeMap = new ts.Map();
+ while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
+ var result = cacheToUpdateChildWatches.entries().next();
+ ts.Debug.assert(!result.done);
+ var _a = result.value, dirPath = _a[0], _b = _a[1], dirName = _b.dirName, options = _b.options, fileNames = _b.fileNames;
+ cacheToUpdateChildWatches.delete(dirPath);
+ // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
+ // to ensure that all the changes are reflected at this time
+ var hasChanges = updateChildWatches(dirName, dirPath, options);
+ invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
}
- function setModifiedTime(path, time) {
- try {
- _fs.utimesSync(path, time, time);
- }
- catch (e) {
- return;
+ ts.sysLog("sysLog:: invokingWatchers:: Elapsed:: ".concat(ts.timestamp() - start, "ms:: ").concat(cacheToUpdateChildWatches.size));
+ callbackCache.forEach(function (callbacks, rootDirName) {
+ var existing = invokeMap.get(rootDirName);
+ if (existing) {
+ callbacks.forEach(function (_a) {
+ var callback = _a.callback, dirName = _a.dirName;
+ if (ts.isArray(existing)) {
+ existing.forEach(callback);
+ }
+ else {
+ callback(dirName);
+ }
+ });
}
+ });
+ var elapsed = ts.timestamp() - start;
+ ts.sysLog("sysLog:: Elapsed:: ".concat(elapsed, "ms:: onTimerToUpdateChildWatches:: ").concat(cacheToUpdateChildWatches.size, " ").concat(timerToUpdateChildWatches));
+ }
+ function removeChildWatches(parentWatcher) {
+ if (!parentWatcher)
+ return;
+ var existingChildWatches = parentWatcher.childWatches;
+ parentWatcher.childWatches = ts.emptyArray;
+ for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
+ var childWatcher = existingChildWatches_1[_i];
+ childWatcher.close();
+ removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
}
- function deleteFile(path) {
- try {
- return _fs.unlinkSync(path);
- }
- catch (e) {
- return;
- }
+ }
+ function updateChildWatches(parentDir, parentDirPath, options) {
+ // Iterate through existing children and update the watches if needed
+ var parentWatcher = cache.get(parentDirPath);
+ if (!parentWatcher)
+ return false;
+ var newChildWatches;
+ var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) {
+ var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
+ // 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 !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, ts.normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
+ parentWatcher.childWatches = newChildWatches || ts.emptyArray;
+ return hasChanges;
+ /**
+ * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
+ */
+ function createAndAddChildDirectoryWatcher(childName) {
+ var result = createDirectoryWatcher(childName, options);
+ addChildDirectoryWatcher(result);
}
- function createSHA256Hash(data) {
- var hash = _crypto.createHash("sha256");
- hash.update(data);
- return hash.digest("hex");
+ /**
+ * Add child directory watcher to the new ChildDirectoryWatcher list
+ */
+ function addChildDirectoryWatcher(childWatcher) {
+ (newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
- var sys;
- 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();
+ function isIgnoredPath(path, options) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); }) ||
+ isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory);
}
- if (sys) {
- // patch writefile to create folder before writing the file
- patchWriteFileEnsuringDirectory(sys);
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
}
- return sys;
- })();
- if (ts.sys && ts.sys.getEnvironmentVariable) {
- setCustomPollingValues(ts.sys);
- ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
- ? 1 /* Normal */
- : 0 /* None */);
- }
- if (ts.sys && ts.sys.debugMode) {
- ts.Debug.isDebugging = true;
- }
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- /**
- * 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;
- //// Path Tests
- /**
- * Determines whether a charCode corresponds to `/` or `\`.
- */
- function isAnyDirectorySeparator(charCode) {
- return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
- }
- ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
- /**
- * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
- */
- function isUrl(path) {
- return getEncodedRootLength(path) < 0;
}
- ts.isUrl = isUrl;
- /**
- * Determines whether a path is an absolute disk 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;
- /**
- * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
- *
- * ```ts
- * // POSIX
- * pathIsAbsolute("/path/to/file.ext") === true
- * // DOS
- * pathIsAbsolute("c:/path/to/file.ext") === true
- * // URL
- * pathIsAbsolute("file:///path/to/file.ext") === true
- * // Non-absolute
- * pathIsAbsolute("path/to/file.ext") === false
- * pathIsAbsolute("./path/to/file.ext") === false
- * ```
- */
- function pathIsAbsolute(path) {
- return getEncodedRootLength(path) !== 0;
+ ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
+ /*@internal*/
+ var FileSystemEntryKind;
+ (function (FileSystemEntryKind) {
+ FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
+ FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
+ })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
+ /*@internal*/
+ function createFileWatcherCallback(callback) {
+ return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
}
- ts.pathIsAbsolute = pathIsAbsolute;
- /**
- * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
- */
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
+ ts.createFileWatcherCallback = createFileWatcherCallback;
+ function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
+ return function (eventName) {
+ if (eventName === "rename") {
+ callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
+ }
+ else {
+ // Change
+ callback(fileName, FileWatcherEventKind.Changed);
+ }
+ };
}
- ts.pathIsRelative = pathIsRelative;
- function hasExtension(fileName) {
- return ts.stringContains(getBaseFileName(fileName), ".");
+ function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) {
+ return ((options === null || options === void 0 ? void 0 : options.excludeDirectories) || (options === null || options === void 0 ? void 0 : options.excludeFiles)) && (ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) ||
+ ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory()));
}
- ts.hasExtension = hasExtension;
- function fileExtensionIs(path, extension) {
- return path.length > extension.length && ts.endsWith(path, extension);
+ function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) {
+ 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
+ var fileName = !relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName));
+ if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) {
+ callback(fileName);
+ }
+ }
+ };
}
- ts.fileExtensionIs = fileExtensionIs;
- function fileExtensionIsOneOf(path, extensions) {
- for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
- var extension = extensions_1[_i];
- if (fileExtensionIs(path, extension)) {
- return true;
+ /*@internal*/
+ function createSystemWatchFunctions(_a) {
+ var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind;
+ var dynamicPollingWatchFile;
+ var fixedChunkSizePollingWatchFile;
+ var nonPollingWatchFile;
+ var hostRecursiveDirectoryWatcher;
+ return {
+ watchFile: watchFile,
+ watchDirectory: watchDirectory
+ };
+ function watchFile(fileName, callback, pollingInterval, options) {
+ options = updateOptionsForWatchFile(options, useNonPollingWatchers);
+ var watchFileKind = ts.Debug.checkDefined(options.watchFile);
+ switch (watchFileKind) {
+ case ts.WatchFileKind.FixedPollingInterval:
+ return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
+ case ts.WatchFileKind.PriorityPollingInterval:
+ return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
+ case ts.WatchFileKind.DynamicPriorityPolling:
+ return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
+ case ts.WatchFileKind.FixedChunkSizePolling:
+ return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined);
+ case ts.WatchFileKind.UseFsEvents:
+ return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists),
+ /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
+ case ts.WatchFileKind.UseFsEventsOnParentDirectory:
+ if (!nonPollingWatchFile) {
+ nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
+ }
+ return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
+ default:
+ ts.Debug.assertNever(watchFileKind);
}
}
- return false;
- }
- ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
- /**
- * Determines whether a path has a trailing separator (`/` or `\\`).
- */
- function hasTrailingDirectorySeparator(path) {
- return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
- }
- ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
- //// Path Parsing
- function isVolumeCharacter(charCode) {
- 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 /* colon */)
- return start + 1;
- if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
- var ch2 = url.charCodeAt(start + 2);
- 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);
- // POSIX or UNC
- if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
- if (path.charCodeAt(1) !== ch0)
- return 1; // POSIX: "/" (or non-normalized "\")
- var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
- if (p1 < 0)
- return path.length; // UNC: "//server" or "\\server"
- return p1 + 1; // UNC: "//server/" or "\\server\"
- }
- // DOS
- if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
- var ch2 = path.charCodeAt(2);
- if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
- return 3; // DOS: "c:/" or "c:\"
- if (path.length === 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) { // 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 /* 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); // URL: "file://server/", "http://server/"
- }
- 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;
- 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 = removeTrailingDirectorySeparator(path);
- return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function getBaseFileName(path, extensions, ignoreCase) {
- path = normalizeSlashes(path);
- // if the path provided is itself the root, then it has not file name.
- var rootLength = 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(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;
- function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
- if (!ts.startsWith(extension, "."))
- extension = "." + extension;
- if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
- var pathExtension = path.slice(path.length - extension.length);
- if (stringEqualityComparer(pathExtension, extension)) {
- return pathExtension;
- }
- }
- }
- function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
- if (typeof extensions === "string") {
- return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
- }
- for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
- var extension = extensions_2[_i];
- var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
- if (result)
- return result;
- }
- 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(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
+ function ensureDynamicPollingWatchFile() {
+ return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
}
- var baseFileName = getBaseFileName(path);
- var extensionIndex = baseFileName.lastIndexOf(".");
- if (extensionIndex >= 0) {
- return baseFileName.substring(extensionIndex);
+ function ensureFixedChunkSizePollingWatchFile() {
+ return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
}
- return "";
- }
- ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
- function pathComponents(path, rootLength) {
- var root = path.substring(0, rootLength);
- var rest = path.substring(rootLength).split(ts.directorySeparator);
- if (rest.length && !ts.lastOrUndefined(rest))
- rest.pop();
- return __spreadArrays([root], 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 (`/`).
- *
- * ```ts
- * // POSIX
- * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
- * getPathComponents("/path/to/") === ["/", "path", "to"]
- * getPathComponents("/") === ["/"]
- * // DOS
- * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
- * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
- * getPathComponents("c:/") === ["c:/"]
- * getPathComponents("c:") === ["c:"]
- * // URL
- * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
- * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
- * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
- * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
- * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
- * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
- * getPathComponents("file://server/") === ["file://server/"]
- * getPathComponents("file://server") === ["file://server"]
- * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
- * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
- * getPathComponents("file:///") === ["file:///"]
- * getPathComponents("file://") === ["file://"]
- */
- function getPathComponents(path, currentDirectory) {
- if (currentDirectory === void 0) { currentDirectory = ""; }
- path = combinePaths(currentDirectory, path);
- return pathComponents(path, getRootLength(path));
- }
- ts.getPathComponents = getPathComponents;
- //// Path Formatting
- /**
- * Formats a parsed path consisting of a root component (at index 0) and zero or more path
- * segments (at indices > 0).
- *
- * ```ts
- * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
- * ```
- */
- function getPathFromPathComponents(pathComponents) {
- if (pathComponents.length === 0)
- return "";
- var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
- return root + pathComponents.slice(1).join(ts.directorySeparator);
- }
- ts.getPathFromPathComponents = getPathFromPathComponents;
- //// Path Normalization
- /**
- * Normalize path separators, converting `\` into `/`.
- */
- function normalizeSlashes(path) {
- return path.replace(backslashRegExp, ts.directorySeparator);
- }
- ts.normalizeSlashes = normalizeSlashes;
- /**
- * 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 [];
- var reduced = [components[0]];
- for (var i = 1; i < components.length; i++) {
- var component = components[i];
- if (!component)
- continue;
- if (component === ".")
- continue;
- if (component === "..") {
- if (reduced.length > 1) {
- if (reduced[reduced.length - 1] !== "..") {
- reduced.pop();
- continue;
- }
- }
- else if (reduced[0])
- continue;
+ function updateOptionsForWatchFile(options, useNonPollingWatchers) {
+ if (options && options.watchFile !== undefined)
+ return options;
+ switch (tscWatchFile) {
+ case "PriorityPollingInterval":
+ // Use polling interval based on priority when create watch using host.watchFile
+ return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
+ case "DynamicPriorityPolling":
+ // Use polling interval but change the interval depending on file changes and their default polling interval
+ return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
+ case "UseFsEvents":
+ // Use notifications from FS to watch with falling back to fs.watchFile
+ return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
+ case "UseFsEventsWithFallbackDynamicPolling":
+ // Use notifications from FS to watch with falling back to dynamic watch file
+ return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
+ case "UseFsEventsOnParentDirectory":
+ useNonPollingWatchers = true;
+ // fall through
+ default:
+ return useNonPollingWatchers ?
+ // Use notifications from FS to watch with falling back to fs.watchFile
+ generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
+ // Default to do not use fixed polling interval
+ { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval };
}
- reduced.push(component);
}
- return reduced;
- }
- ts.reducePathComponents = reducePathComponents;
- /**
- * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
- *
- * ```ts
- * // Non-rooted
- * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
- * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
- * // POSIX
- * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
- * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
- * // DOS
- * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
- * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
- * // URL
- * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
- * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
- * ```
- */
- function combinePaths(path) {
- var paths = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- paths[_i - 1] = arguments[_i];
+ function generateWatchFileOptions(watchFile, fallbackPolling, options) {
+ var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
+ return {
+ watchFile: watchFile,
+ fallbackPolling: defaultFallbackPolling === undefined ?
+ fallbackPolling :
+ defaultFallbackPolling
+ };
}
- if (path)
- path = normalizeSlashes(path);
- for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
- var relativePath = paths_1[_a];
- if (!relativePath)
- continue;
- relativePath = normalizeSlashes(relativePath);
- if (!path || getRootLength(relativePath) !== 0) {
- path = relativePath;
+ function watchDirectory(directoryName, callback, recursive, options) {
+ if (fsSupportsRecursiveFsWatch) {
+ return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
}
- else {
- path = ensureTrailingDirectorySeparator(path) + relativePath;
+ if (!hostRecursiveDirectoryWatcher) {
+ hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
+ useCaseSensitiveFileNames: useCaseSensitiveFileNames,
+ getCurrentDirectory: getCurrentDirectory,
+ directoryExists: directoryExists,
+ getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
+ watchDirectory: nonRecursiveWatchDirectory,
+ realpath: realpath,
+ setTimeout: setTimeout,
+ clearTimeout: clearTimeout
+ });
}
+ return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
}
- 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. Trailing directory separators are preserved.
- *
- * ```ts
- * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
- * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
- * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
- * ```
- */
- function resolvePath(path) {
- var paths = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- paths[_i - 1] = arguments[_i];
- }
- return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
- }
- ts.resolvePath = resolvePath;
- /**
- * 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 (`/`).
- *
- * ```ts
- * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
- * ```
- */
- function getNormalizedPathComponents(path, currentDirectory) {
- return reducePathComponents(getPathComponents(path, currentDirectory));
- }
- ts.getNormalizedPathComponents = getNormalizedPathComponents;
- function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
- }
- ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function normalizePath(path) {
- path = normalizeSlashes(path);
- var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
- return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
- }
- ts.normalizePath = normalizePath;
- function getPathWithoutRoot(pathComponents) {
- if (pathComponents.length === 0)
- return "";
- return pathComponents.slice(1).join(ts.directorySeparator);
- }
- function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
- return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
- }
- ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
- function toPath(fileName, basePath, getCanonicalFileName) {
- var nonCanonicalizedPath = isRootedDiskPath(fileName)
- ? normalizePath(fileName)
- : getNormalizedAbsolutePath(fileName, basePath);
- return getCanonicalFileName(nonCanonicalizedPath);
- }
- ts.toPath = toPath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- function removeTrailingDirectorySeparator(path) {
- if (hasTrailingDirectorySeparator(path)) {
- return path.substr(0, path.length - 1);
+ function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
+ ts.Debug.assert(!recursive);
+ var watchDirectoryOptions = updateOptionsForWatchDirectory(options);
+ var watchDirectoryKind = ts.Debug.checkDefined(watchDirectoryOptions.watchDirectory);
+ switch (watchDirectoryKind) {
+ case ts.WatchDirectoryKind.FixedPollingInterval:
+ return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
+ /*options*/ undefined);
+ case ts.WatchDirectoryKind.DynamicPriorityPolling:
+ return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
+ /*options*/ undefined);
+ case ts.WatchDirectoryKind.FixedChunkSizePolling:
+ return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); },
+ /* pollingInterval */ undefined,
+ /*options*/ undefined);
+ case ts.WatchDirectoryKind.UseFsEvents:
+ return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions));
+ default:
+ ts.Debug.assertNever(watchDirectoryKind);
+ }
}
- return path;
- }
- ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
- function ensureTrailingDirectorySeparator(path) {
- if (!hasTrailingDirectorySeparator(path)) {
- return path + ts.directorySeparator;
+ function updateOptionsForWatchDirectory(options) {
+ if (options && options.watchDirectory !== undefined)
+ return options;
+ switch (tscWatchDirectory) {
+ case "RecursiveDirectoryUsingFsWatchFile":
+ // Use polling interval based on priority when create watch using host.watchFile
+ return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
+ case "RecursiveDirectoryUsingDynamicPriorityPolling":
+ // Use polling interval but change the interval depending on file changes and their default polling interval
+ return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
+ default:
+ var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
+ return {
+ watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
+ fallbackPolling: defaultFallbackPolling !== undefined ?
+ defaultFallbackPolling :
+ undefined
+ };
+ }
}
- return path;
}
- ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
+ ts.createSystemWatchFunctions = createSystemWatchFunctions;
/**
- * 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.
- *
- * ```ts
- * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
- * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
- * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
- * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
- * ```
+ * patch writefile to create folder before writing the file
*/
- function ensurePathIsNonModuleName(path) {
- return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
- function changeAnyExtension(path, ext, extensions, ignoreCase) {
- var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
- return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
+ /*@internal*/
+ function patchWriteFileEnsuringDirectory(sys) {
+ // patch writefile to create folder before writing the file
+ var originalWriteFile = sys.writeFile;
+ sys.writeFile = function (path, data, writeBom) {
+ return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); });
+ };
}
- ts.changeAnyExtension = changeAnyExtension;
- //// Path Comparisons
- // check path for these segments: '', '.'. '..'
- var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
- function comparePathsWorker(a, b, componentComparer) {
- if (a === b)
- return 0 /* EqualTo */;
- if (a === undefined)
- return -1 /* LessThan */;
- if (b === undefined)
- return 1 /* GreaterThan */;
- // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
- // need to perform path reduction.
- var aRoot = a.substring(0, getRootLength(a));
- var bRoot = b.substring(0, getRootLength(b));
- var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
- if (result !== 0 /* EqualTo */) {
- return result;
+ ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
+ function getNodeMajorVersion() {
+ if (typeof process === "undefined") {
+ return undefined;
}
- // NOTE: Performance optimization - shortcut if there are no relative path segments in
- // the non-root portion of the path
- var aRest = a.substring(aRoot.length);
- var bRest = b.substring(bRoot.length);
- if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
- return componentComparer(aRest, bRest);
+ var version = process.version;
+ if (!version) {
+ return undefined;
}
- // The path contains a relative path segment. Normalize the paths and perform a slower component
- // by component comparison.
- var aComponents = reducePathComponents(getPathComponents(a));
- var bComponents = reducePathComponents(getPathComponents(b));
- var sharedLength = Math.min(aComponents.length, bComponents.length);
- for (var i = 1; i < sharedLength; i++) {
- var result_1 = componentComparer(aComponents[i], bComponents[i]);
- if (result_1 !== 0 /* EqualTo */) {
- return result_1;
- }
+ var dot = version.indexOf(".");
+ if (dot === -1) {
+ return undefined;
}
- return ts.compareValues(aComponents.length, bComponents.length);
+ return parseInt(version.substring(1, dot));
}
- /**
- * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
- */
- 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);
- }
- ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
- if (typeof currentDirectory === "string") {
- a = combinePaths(currentDirectory, a);
- b = combinePaths(currentDirectory, b);
- }
- else if (typeof currentDirectory === "boolean") {
- ignoreCase = currentDirectory;
- }
- return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
- }
- ts.comparePaths = comparePaths;
- function containsPath(parent, child, currentDirectory, ignoreCase) {
- if (typeof currentDirectory === "string") {
- parent = combinePaths(currentDirectory, parent);
- child = combinePaths(currentDirectory, child);
- }
- else if (typeof currentDirectory === "boolean") {
- ignoreCase = currentDirectory;
- }
- if (parent === undefined || child === undefined)
- return false;
- if (parent === child)
- return true;
- var parentComponents = reducePathComponents(getPathComponents(parent));
- var childComponents = reducePathComponents(getPathComponents(child));
- if (childComponents.length < parentComponents.length) {
- return false;
- }
- var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
- for (var i = 0; i < parentComponents.length; i++) {
- var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
- if (!equalityComparer(parentComponents[i], childComponents[i])) {
- return false;
+ ts.getNodeMajorVersion = getNodeMajorVersion;
+ // TODO: GH#18217 this is used as if it's certainly defined in many places.
+ // eslint-disable-next-line prefer-const
+ 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 _a;
+ var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
+ 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");
}
- }
- return true;
- }
- ts.containsPath = containsPath;
- /**
- * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
- * Comparison is case-sensitive between the canonical paths.
- *
- * @deprecated Use `containsPath` if possible.
- */
- function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
- var canonicalFileName = getCanonicalFileName(fileName);
- var canonicalDirectoryName = getCanonicalFileName(directoryName);
- return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
- }
- ts.startsWithDirectory = startsWithDirectory;
- //// Relative Paths
- function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
- var fromComponents = reducePathComponents(getPathComponents(from));
- var toComponents = reducePathComponents(getPathComponents(to));
- var start;
- for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
- var fromComponent = getCanonicalFileName(fromComponents[start]);
- var toComponent = getCanonicalFileName(toComponents[start]);
- var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
- if (!comparer(fromComponent, toComponent))
- break;
- }
- if (start === 0) {
- return toComponents;
- }
- var components = toComponents.slice(start);
- var relative = [];
- for (; start < fromComponents.length; start++) {
- relative.push("..");
- }
- return __spreadArrays([""], relative, components);
- }
- ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
- function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
- ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
- var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
- var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
- var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
- return getPathFromPathComponents(pathComponents);
- }
- ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
- function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
- return !isRootedDiskPath(absoluteOrRelativePath)
- ? absoluteOrRelativePath
- : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- }
- ts.convertToRelativePath = convertToRelativePath;
- function getRelativePathFromFile(from, to, getCanonicalFileName) {
- return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
- }
- ts.getRelativePathFromFile = getRelativePathFromFile;
- function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
- var firstComponent = pathComponents[0];
- if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
- var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
- pathComponents[0] = prefix + firstComponent;
- }
- return getPathFromPathComponents(pathComponents);
- }
- ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function forEachAncestorDirectory(directory, callback) {
- while (true) {
- var result = callback(directory);
- if (result !== undefined) {
- return result;
+ catch (_b) {
+ _crypto = undefined;
}
- var parentPath = getDirectoryPath(directory);
- if (parentPath === directory) {
- return undefined;
- }
- directory = parentPath;
- }
- }
- ts.forEachAncestorDirectory = forEachAncestorDirectory;
- function isNodeModulesDirectory(dirPath) {
- return ts.endsWith(dirPath, "/node_modules");
- }
- ts.isNodeModulesDirectory = isNodeModulesDirectory;
-})(ts || (ts = {}));
-//
-// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
-/* @internal */
-var ts;
-(function (ts) {
- function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
- return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
- }
- 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."),
- _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
- A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."),
- The_parser_expected_to_find_a_to_match_the_token_here: diag(1007, ts.DiagnosticCategory.Error, "The_parser_expected_to_find_a_to_match_the_token_here_1007", "The parser expected to find a '}' to match the '{' token here."),
- Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
- Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
- An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."),
- Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
- A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."),
- A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."),
- Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."),
- A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."),
- An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."),
- An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."),
- An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."),
- An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."),
- An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."),
- An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."),
- An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."),
- readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."),
- An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."),
- Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
- _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
- _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
- _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."),
- super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."),
- Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."),
- Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."),
- A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."),
- Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."),
- _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."),
- _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."),
- _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
- _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."),
- _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."),
- A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."),
- Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier: diag(1046, ts.DiagnosticCategory.Error, "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046", "Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier."),
- A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
- A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."),
- A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."),
- A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."),
- A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."),
- A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."),
- A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
- Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."),
- Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."),
- An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."),
- The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."),
- A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."),
- The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."),
- Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
- Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."),
- An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."),
- The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."),
- In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."),
- Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."),
- Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."),
- _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."),
- _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."),
- A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."),
- Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
- Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."),
- _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."),
- _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."),
- Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."),
- Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."),
- Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."),
- An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
- A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."),
- An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."),
- _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
- Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
- Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
- Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."),
- with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."),
- delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."),
- A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."),
- A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."),
- A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."),
- Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
- A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."),
- Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
- Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
- A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."),
- Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
- A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."),
- A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."),
- An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."),
- An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."),
- An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."),
- An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
- Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."),
- Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
- Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
- Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
- Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
- Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
- Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
- Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
- case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
- Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
- Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
- Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
- Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
- Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
- Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
- Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
- Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
- Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
- String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
- Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
- or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
- Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
- Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."),
- Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."),
- File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."),
- const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
- const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."),
- let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."),
- Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
- Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
- An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."),
- A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."),
- Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."),
- A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."),
- A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."),
- A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."),
- A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."),
- A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."),
- A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."),
- extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
- extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
- Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."),
- implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
- Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
- Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
- Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
- Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
- Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
- Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
- A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."),
- An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."),
- Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
- Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
- A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."),
- A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."),
- Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."),
- The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."),
- The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."),
- An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
- Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
- An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
- Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."),
- export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."),
- Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."),
- Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."),
- An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."),
- Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
- Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
- Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."),
- Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."),
- Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type: diag(1205, ts.DiagnosticCategory.Error, "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205", "Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'."),
- Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
- Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
- All_files_must_be_modules_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "All_files_must_be_modules_when_the_isolatedModules_flag_is_provided_1208", "All files must be modules when the '--isolatedModules' flag is provided."),
- Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
- A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
- Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
- Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."),
- Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."),
- Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."),
- Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."),
- Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."),
- Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning."),
- Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."),
- Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."),
- An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."),
- _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
- Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."),
- Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
- Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."),
- Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."),
- A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."),
- A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."),
- A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."),
- An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."),
- An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."),
- An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."),
- An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."),
- A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."),
- The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."),
- The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."),
- Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."),
- Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."),
- Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."),
- Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."),
- abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."),
- _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."),
- Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."),
- Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."),
- An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."),
- A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."),
- A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."),
- A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."),
- Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."),
- Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),
- Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),
- _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."),
- A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),
- A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."),
- A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."),
- A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."),
- Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation: diag(1258, ts.DiagnosticCategory.Error, "Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation_1258", "Definite assignment assertions can only be used along with a type annotation."),
- Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"),
- Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
- Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."),
- with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."),
- await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."),
- can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."),
- The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."),
- Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."),
- Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."),
- Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."),
- A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."),
- An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."),
- A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."),
- Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
- Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
- Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'."),
- Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
- Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
- Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
- String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
- Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."),
- _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"),
- A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."),
- A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."),
- A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."),
- unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."),
- unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."),
- unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."),
- An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."),
- An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."),
- infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."),
- Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."),
- Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"),
- Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
- The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'esnext' or 'system'."),
- A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
- An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"),
- This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."),
- use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."),
- Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
- use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
- Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."),
- An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
- A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
- A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
- readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
- A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355", "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."),
- Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"),
- An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."),
- Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."),
- Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."),
- Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"),
- _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."),
- _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."),
- A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."),
- Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
- Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"),
- Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
- Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
- Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"),
- Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
- Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."),
- This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371", "This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'."),
- Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
- Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"),
- await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."),
- _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
- _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
- Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
- An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."),
- An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."),
- Unexpected_token_Did_you_mean_or_rbrace: diag(1381, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_rbrace_1381", "Unexpected token. Did you mean `{'}'}` or `}`?"),
- Unexpected_token_Did_you_mean_or_gt: diag(1382, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_gt_1382", "Unexpected token. Did you mean `{'>'}` or `>`?"),
- Only_named_exports_may_use_export_type: diag(1383, ts.DiagnosticCategory.Error, "Only_named_exports_may_use_export_type_1383", "Only named exports may use 'export type'."),
- A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list: diag(1384, ts.DiagnosticCategory.Error, "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384", "A 'new' expression with type arguments must always be followed by a parenthesized argument list."),
- The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."),
- The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."),
- Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
- Construct_signature_return_types_0_and_1_are_incompatible: diag(2203, ts.DiagnosticCategory.Error, "Construct_signature_return_types_0_and_1_are_incompatible_2203", "Construct signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
- Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2204, ts.DiagnosticCategory.Error, "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
- Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
- Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
- Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),
- Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."),
- Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
- Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
- Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."),
- File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
- Cannot_find_module_0_or_its_corresponding_type_declarations: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", "Cannot find module '{0}' or its corresponding type declarations."),
- Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."),
- An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
- Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
- A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
- Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
- Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
- Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
- Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."),
- Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."),
- Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
- Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."),
- Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."),
- Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."),
- Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."),
- Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
- Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."),
- Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."),
- Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
- Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."),
- Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."),
- Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."),
- Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
- this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."),
- this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."),
- this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."),
- this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."),
- super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."),
- super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."),
- Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."),
- super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."),
- Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."),
- Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."),
- Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."),
- An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."),
- This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."),
- Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."),
- Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."),
- Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."),
- Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."),
- Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"),
- This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
- Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."),
- This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
- Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."),
- Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."),
- This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."),
- A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."),
- An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."),
- The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."),
- The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."),
- The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."),
- The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."),
- The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."),
- The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
- The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
- The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."),
- Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."),
- Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."),
- This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."),
- Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
- A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."),
- A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."),
- A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."),
- Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
- Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."),
- Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
- Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
- A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."),
- Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."),
- A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."),
- Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."),
- get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."),
- A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."),
- Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."),
- Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."),
- Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."),
- Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."),
- Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."),
- Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
- Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
- Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
- Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
- Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
- Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
- Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
- Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
- Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
- Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
- constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."),
- Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."),
- Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."),
- Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."),
- Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."),
- Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."),
- The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."),
- The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."),
- The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."),
- The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."),
- Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
- Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."),
- The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."),
- Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."),
- Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."),
- Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."),
- Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
- Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."),
- Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."),
- Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
- Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
- Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
- Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
- Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
- Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."),
- Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
- All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."),
- Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
- Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
- In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."),
- A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."),
- A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."),
- Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."),
- Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."),
- Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."),
- Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
- Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."),
- Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."),
- Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."),
- Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."),
- Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."),
- Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."),
- Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."),
- Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."),
- The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."),
- Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."),
- Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
- Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
- Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
- An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."),
- The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."),
- Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."),
- Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."),
- Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
- Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
- An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."),
- Module_0_declares_1_locally_but_it_is_not_exported: diag(2459, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_not_exported_2459", "Module '{0}' declares '{1}' locally, but it is not exported."),
- Module_0_declares_1_locally_but_it_is_exported_as_2: diag(2460, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_exported_as_2_2460", "Module '{0}' declares '{1}' locally, but it is exported as '{2}'."),
- Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."),
- A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."),
- A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."),
- A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."),
- this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."),
- super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."),
- A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."),
- Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
- The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."),
- Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."),
- A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."),
- Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."),
- Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."),
- const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."),
- const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."),
- A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."),
- const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."),
- const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."),
- Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."),
- let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."),
- Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."),
- The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."),
- Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."),
- The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."),
- Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."),
- An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."),
- The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the '{0}()' method of an iterator must have a 'value' property."),
- The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."),
- Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."),
- Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."),
- Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."),
- Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."),
- The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."),
- This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."),
- Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."),
- An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."),
- A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."),
- A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."),
- _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."),
- Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
- Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."),
- A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."),
- _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
- Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
- No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
- Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
- Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
- Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
- Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."),
- Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."),
- Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."),
- All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."),
- Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."),
- A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."),
- An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."),
- Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."),
- Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."),
- The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."),
- yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."),
- await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."),
- Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."),
- A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."),
- The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."),
- A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."),
- Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."),
- Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."),
- Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
- Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
- Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
- A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."),
- Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."),
- Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."),
- Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
- Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
- Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
- The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
- Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
- Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
- Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."),
- A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."),
- The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."),
- Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
- Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
- Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),
- Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"),
- Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."),
- Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
- Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."),
- Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."),
- Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."),
- Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."),
- Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."),
- Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"),
- Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"),
- Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."),
- The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."),
- Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."),
- Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."),
- A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."),
- Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."),
- Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),
- Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
- Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
- Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."),
- A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."),
- No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),
- Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"),
- Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
- Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
- Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
- Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
- _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
- Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
- JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
- Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
- Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
- Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
- This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."),
- _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."),
- _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."),
- _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."),
- _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."),
- JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
- The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
- JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
- Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."),
- JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."),
- JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."),
- Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."),
- JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."),
- The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."),
- JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."),
- _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."),
- _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."),
- Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."),
- Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"),
- Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"),
- Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."),
- _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."),
- _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."),
- Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."),
- A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."),
- Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."),
- Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."),
- Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."),
- Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."),
- JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."),
- Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."),
- super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."),
- super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."),
- Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."),
- Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"),
- Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"),
- Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."),
- Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."),
- Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."),
- Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."),
- export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."),
- Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."),
- Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."),
- Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."),
- Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."),
- Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."),
- Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."),
- Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."),
- Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."),
- A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."),
- Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."),
- A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."),
- A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."),
- A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."),
- get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."),
- this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."),
- The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."),
- The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."),
- _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."),
- All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."),
- Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."),
- Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"),
- An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."),
- _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.", /*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."),
- Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."),
- Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."),
- The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."),
- _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."),
- The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."),
- The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."),
- An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
- Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."),
- Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."),
- Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."),
- Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."),
- _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."),
- A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
- A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
- Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"),
- The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."),
- Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."),
- Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."),
- Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."),
- Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
- Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."),
- Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"),
- Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
- Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
- Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
- Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
- Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."),
- Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
- Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"),
- _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
- Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."),
- An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."),
- Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),
- Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"),
- Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
- Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
- Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"),
- Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."),
- BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."),
- An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."),
- Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
- Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
- Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
- The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
- No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."),
- Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."),
- This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
- This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
- _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
- Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
- _0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749", "'{0}' refers to a value, but is being used as a type here. Did you mean 'typeof {0}'?"),
- The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
- Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
- The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
- Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
- super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
- No_constituent_of_type_0_is_callable: diag(2755, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_callable_2755", "No constituent of type '{0}' is callable."),
- Not_all_constituents_of_type_0_are_callable: diag(2756, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_callable_2756", "Not all constituents of type '{0}' are callable."),
- Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
- Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2758, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758", "Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other."),
- No_constituent_of_type_0_is_constructable: diag(2759, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_constructable_2759", "No constituent of type '{0}' is constructable."),
- Not_all_constituents_of_type_0_are_constructable: diag(2760, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_constructable_2760", "Not all constituents of type '{0}' are constructable."),
- Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
- Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2762, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762", "Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other."),
- Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0: diag(2763, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but for-of will always send '{0}'."),
- Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0: diag(2764, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array spread will always send '{0}'."),
- Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0: diag(2765, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array destructuring will always send '{0}'."),
- Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0: diag(2766, ts.DiagnosticCategory.Error, "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766", "Cannot delegate iteration to value because the 'next' method of its iterator expects type '{1}', but the containing generator will always send '{0}'."),
- The_0_property_of_an_iterator_must_be_a_method: diag(2767, ts.DiagnosticCategory.Error, "The_0_property_of_an_iterator_must_be_a_method_2767", "The '{0}' property of an iterator must be a method."),
- The_0_property_of_an_async_iterator_must_be_a_method: diag(2768, ts.DiagnosticCategory.Error, "The_0_property_of_an_async_iterator_must_be_a_method_2768", "The '{0}' property of an async iterator must be a method."),
- No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
- The_last_overload_gave_the_following_error: diag(2770, ts.DiagnosticCategory.Error, "The_last_overload_gave_the_following_error_2770", "The last overload gave the following error."),
- The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
- Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."),
- Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
- This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"),
- Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."),
- Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."),
- The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."),
- The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access: diag(2778, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778", "The target of an object rest assignment may not be an optional property access."),
- The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access: diag(2779, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779", "The left-hand side of an assignment expression may not be an optional property access."),
- The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."),
- The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."),
- _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
- _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."),
- get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."),
- This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
- _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."),
- Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."),
- Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."),
- Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."),
- Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
- Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
- Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
- Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
- Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
- Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
- Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."),
- Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."),
- Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."),
- Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."),
- extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."),
- extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."),
- Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."),
- Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."),
- Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."),
- Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
- Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."),
- Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
- Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."),
- Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
- Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."),
- Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
- Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."),
- Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
- Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."),
- Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
- Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."),
- Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
- Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."),
- Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."),
- Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."),
- Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."),
- Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."),
- Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."),
- Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."),
- Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
- Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."),
- Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."),
- Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
- Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."),
- Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."),
- Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."),
- Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."),
- Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."),
- Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."),
- Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."),
- Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."),
- Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
- Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
- Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
- Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."),
- Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."),
- Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."),
- Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."),
- Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."),
- Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."),
- Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."),
- Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."),
- Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."),
- Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
- Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
- Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."),
- Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
- Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
- Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
- Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
- Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
- Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
- The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1: diag(4104, ts.DiagnosticCategory.Error, "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104", "The type '{0}' is 'readonly' and cannot be assigned to the mutable type '{1}'."),
- Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter: diag(4105, ts.DiagnosticCategory.Error, "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105", "Private or protected member '{0}' cannot be accessed on a type parameter."),
- Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."),
- Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."),
- Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."),
- Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."),
- Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
- The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
- Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
- File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
- Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
- Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."),
- Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
- Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."),
- Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"),
- Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."),
- Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."),
- Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."),
- Option_0_cannot_be_specified_when_option_target_is_ES3: diag(5048, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_target_is_ES3_5048", "Option '{0}' cannot be specified when option 'target' is 'ES3'."),
- Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."),
- Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."),
- Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."),
- A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."),
- Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."),
- Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."),
- Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."),
- The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."),
- Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."),
- Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."),
- Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."),
- Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' can have at most one '*' character."),
- Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."),
- Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."),
- File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."),
- Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."),
- Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
- Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
- Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
- Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
- Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),
- Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
- Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."),
- Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."),
- _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."),
- _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."),
- Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"),
- Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
- Unknown_watch_option_0_Did_you_mean_1: diag(5079, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"),
- Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."),
- Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."),
- _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."),
- Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
- Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
- Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
- Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
- Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."),
- Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."),
- Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
- Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
- Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."),
- Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."),
- Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
- Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
- Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."),
- Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
- Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
- Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."),
- Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."),
- Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
- Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
- Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."),
- Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
- options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
- file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
- Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
- Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
- Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
- Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."),
- Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
- File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
- KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
- FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
- VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
- LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
- DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
- STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
- FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
- Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
- Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
- Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."),
- Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."),
- Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."),
- Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
- Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
- Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
- Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."),
- File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
- File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."),
- Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."),
- Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."),
- Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."),
- File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."),
- Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."),
- NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
- Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."),
- Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
- Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."),
- Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."),
- Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."),
- Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."),
- Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
- Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."),
- Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."),
- Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."),
- Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."),
- Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."),
- Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."),
- Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."),
- Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."),
- Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."),
- File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."),
- Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."),
- Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."),
- Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"),
- Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."),
- Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
- Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."),
- Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."),
- Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"),
- Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
- paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."),
- Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
- Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."),
- Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."),
- Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."),
- File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
- File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."),
- Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."),
- Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
- package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."),
- package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."),
- Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
- Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."),
- Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),
- Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),
- baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),
- rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."),
- Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."),
- Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."),
- Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
- Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
- Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."),
- Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
- Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"),
- Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."),
- Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"),
- Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
- Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
- Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"),
- Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"),
- Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
- Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."),
- Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"),
- Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."),
- Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."),
- Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."),
- Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"),
- Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"),
- 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.", /*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.", /*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."),
- Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."),
- Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
- Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
- Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
- Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
- Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
- Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
- Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."),
- Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."),
- Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."),
- Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."),
- Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."),
- The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"),
- Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."),
- Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."),
- Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."),
- Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."),
- List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."),
- Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
- The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."),
- Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
- Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
- Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
- A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."),
- List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."),
- Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
- Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"),
- Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
- Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
- Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
- Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
- Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
- Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
- Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
- Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
- Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."),
- Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
- List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
- Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
- Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."),
- Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."),
- Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."),
- Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
- Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."),
- Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
- 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."),
- 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.", /*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.", /*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.", /*reportsUnnecessary*/ true),
- All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
- Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"),
- Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
- 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}"),
- _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
- and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
- All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
- package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."),
- package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),
- package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),
- package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),
- An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."),
- An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."),
- Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"),
- Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"),
- Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."),
- Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."),
- Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
- Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
- Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2: diag(6218, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218", "======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========"),
- Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3: diag(6219, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219", "======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========"),
- package_json_had_a_falsy_0_field: diag(6220, ts.DiagnosticCategory.Message, "package_json_had_a_falsy_0_field_6220", "'package.json' had a falsy '{0}' field."),
- Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects: diag(6221, ts.DiagnosticCategory.Message, "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221", "Disable use of source files instead of declaration files from referenced projects."),
- Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."),
- Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
- Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
- Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
- Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."),
- Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."),
- Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."),
- Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."),
- Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."),
- Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."),
- Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."),
- This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."),
- 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"),
- Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
- Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
- Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
- File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307", "File '{0}' is not listed within the file list of project '{1}'. Projects must list all files or use an 'include' pattern."),
- Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
- Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
- Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"),
- Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"),
- Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"),
- Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"),
- Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"),
- Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
- A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"),
- A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"),
- Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
- Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
- delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"),
- Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
- Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"),
- Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"),
- Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"),
- Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
- Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
- Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"),
- Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"),
- Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
- Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
- Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
- Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
- Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
- A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
- A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
- Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
- Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
- Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
- Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
- Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
- Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
- Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"),
- Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"),
- Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."),
- The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
- The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
- The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
- Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."),
- File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"),
- Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
- Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
- Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
- new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."),
- _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."),
- Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."),
- Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."),
- Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."),
- Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."),
- Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."),
- Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."),
- Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."),
- Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."),
- Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."),
- _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."),
- _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
- Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: 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_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_retu_7025", "Generator implicitly has yield type '{0}' because it does not yield any values. Consider supplying a return type annotation."),
- 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.", /*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."),
- Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."),
- Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."),
- Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."),
- Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
- Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."),
- Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."),
- Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."),
- Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."),
- If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"),
- The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
- Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),
- Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
- Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
- Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
- Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."),
- Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."),
- Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
- Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
- _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
- Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
- Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1: diag(7052, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052", "Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?"),
- Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1: diag(7053, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053", "Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'."),
- No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1: diag(7054, ts.DiagnosticCategory.Error, "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054", "No index signature with a parameter of type '{0}' was found on type '{1}'."),
- _0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type: diag(7055, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055", "'{0}', which lacks return-type annotation, implicitly has an '{1}' yield type."),
- You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
- You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."),
- import_can_only_be_used_in_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."),
- export_can_only_be_used_in_TypeScript_files: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_TypeScript_files_8003", "'export =' can only be used in TypeScript files."),
- Type_parameter_declarations_can_only_be_used_in_TypeScript_files: diag(8004, ts.DiagnosticCategory.Error, "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004", "Type parameter declarations can only be used in TypeScript files."),
- implements_clauses_can_only_be_used_in_TypeScript_files: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_TypeScript_files_8005", "'implements' clauses can only be used in TypeScript files."),
- _0_declarations_can_only_be_used_in_TypeScript_files: diag(8006, ts.DiagnosticCategory.Error, "_0_declarations_can_only_be_used_in_TypeScript_files_8006", "'{0}' declarations can only be used in TypeScript files."),
- Type_aliases_can_only_be_used_in_TypeScript_files: diag(8008, ts.DiagnosticCategory.Error, "Type_aliases_can_only_be_used_in_TypeScript_files_8008", "Type aliases can only be used in TypeScript files."),
- The_0_modifier_can_only_be_used_in_TypeScript_files: diag(8009, ts.DiagnosticCategory.Error, "The_0_modifier_can_only_be_used_in_TypeScript_files_8009", "The '{0}' modifier can only be used in TypeScript files."),
- Type_annotations_can_only_be_used_in_TypeScript_files: diag(8010, ts.DiagnosticCategory.Error, "Type_annotations_can_only_be_used_in_TypeScript_files_8010", "Type annotations can only be used in TypeScript files."),
- Type_arguments_can_only_be_used_in_TypeScript_files: diag(8011, ts.DiagnosticCategory.Error, "Type_arguments_can_only_be_used_in_TypeScript_files_8011", "Type arguments can only be used in TypeScript files."),
- Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, ts.DiagnosticCategory.Error, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."),
- Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, ts.DiagnosticCategory.Error, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."),
- Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, ts.DiagnosticCategory.Error, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."),
- Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."),
- Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."),
- Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
- JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."),
- JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."),
- JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."),
- JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."),
- JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."),
- Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."),
- Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."),
- Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."),
- JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."),
- JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."),
- The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."),
- You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."),
- Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."),
- Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."),
- class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
- Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
- Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."),
- Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."),
- JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."),
- JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."),
- Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."),
- JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
- Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."),
- A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."),
- An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
- A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
- JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."),
- super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."),
- Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
- super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."),
- _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"),
- Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."),
- JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
- Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
- JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
- JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
- Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"),
- Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
- A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
- The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
- No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
- File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
- This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
- Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
- JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
- require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."),
- This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."),
- await_has_no_effect_on_the_type_of_this_expression: diag(80007, ts.DiagnosticCategory.Suggestion, "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."),
- Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, ts.DiagnosticCategory.Suggestion, "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."),
- Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
- Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
- Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
- Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
- Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
- Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
- Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
- Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
- Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
- Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
- Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
- Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
- Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
- Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
- Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
- Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
- Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
- Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
- Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
- Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
- Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
- Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
- Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
- Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
- Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
- Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"),
- Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
- Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
- Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
- Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
- Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
- Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
- Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
- Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
- Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
- Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
- Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
- Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
- Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
- Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
- Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
- Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
- Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
- Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
- Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
- Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
- Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
- Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
- Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
- Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
- Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
- Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
- Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
- Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
- Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
- Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
- Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
- Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
- Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"),
- Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
- Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
- Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"),
- Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"),
- Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"),
- Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"),
- Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
- Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
- Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
- Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
- Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"),
- Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"),
- Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
- Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
- Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
- Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
- Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"),
- Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
- Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
- Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
- Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
- Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
- Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
- Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
- Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
- Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
- Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
- Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
- Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
- Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
- Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
- Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
- Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"),
- Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
- Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
- Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
- Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
- Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
- Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
- Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
- Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
- Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
- Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
- Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
- Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
- Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
- Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
- Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
- Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
- Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
- Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
- Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
- Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
- Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
- Infer_this_type_of_0_from_usage: diag(95080, ts.DiagnosticCategory.Message, "Infer_this_type_of_0_from_usage_95080", "Infer 'this' type of '{0}' from usage"),
- Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
- Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
- Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
- Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
- Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
- Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
- Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
- Enable_the_jsx_flag_in_your_configuration_file: diag(95088, ts.DiagnosticCategory.Message, "Enable_the_jsx_flag_in_your_configuration_file_95088", "Enable the '--jsx' flag in your configuration file"),
- Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
- Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
- Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
- Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
- Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
- Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
- Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"),
- Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
- Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"),
- Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"),
- Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"),
- Convert_invalid_character_to_its_html_entity_code: diag(95100, ts.DiagnosticCategory.Message, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"),
- Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, ts.DiagnosticCategory.Message, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"),
- Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
- Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
- Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
- Convert_function_expression_0_to_arrow_function: diag(95105, ts.DiagnosticCategory.Message, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"),
- Convert_function_declaration_0_to_arrow_function: diag(95106, ts.DiagnosticCategory.Message, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"),
- Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
- Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"),
- Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"),
- Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"),
- Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
- Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
- Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"),
- Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
- Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
- Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
- No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."),
- Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."),
- JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"),
- Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"),
- An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."),
- The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."),
- constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
- Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier: diag(18013, ts.DiagnosticCategory.Error, "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013", "Property '{0}' is not accessible outside class '{1}' because it has a private identifier."),
- The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling: diag(18014, ts.DiagnosticCategory.Error, "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014", "The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling."),
- Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2: diag(18015, ts.DiagnosticCategory.Error, "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015", "Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'."),
- Private_identifiers_are_not_allowed_outside_class_bodies: diag(18016, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_outside_class_bodies_18016", "Private identifiers are not allowed outside class bodies."),
- The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"),
- The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"),
- _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier"),
- A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."),
- An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."),
- An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."),
- can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."),
- Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."),
- Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."),
- Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."),
- An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."),
- The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."),
- The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."),
- Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."),
- };
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var _a;
- /* @internal */
- function tokenIsIdentifierOrKeyword(token) {
- return token >= 75 /* Identifier */;
- }
- ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
- /* @internal */
- function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
- return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
- }
- ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
- var textToKeywordObj = (_a = {
- abstract: 122 /* AbstractKeyword */,
- any: 125 /* AnyKeyword */,
- as: 123 /* AsKeyword */,
- asserts: 124 /* AssertsKeyword */,
- bigint: 151 /* BigIntKeyword */,
- boolean: 128 /* BooleanKeyword */,
- break: 77 /* BreakKeyword */,
- case: 78 /* CaseKeyword */,
- catch: 79 /* CatchKeyword */,
- class: 80 /* ClassKeyword */,
- continue: 82 /* ContinueKeyword */,
- const: 81 /* ConstKeyword */
- },
- _a["" + "constructor"] = 129 /* ConstructorKeyword */,
- _a.debugger = 83 /* DebuggerKeyword */,
- _a.declare = 130 /* DeclareKeyword */,
- _a.default = 84 /* DefaultKeyword */,
- _a.delete = 85 /* DeleteKeyword */,
- _a.do = 86 /* DoKeyword */,
- _a.else = 87 /* ElseKeyword */,
- _a.enum = 88 /* EnumKeyword */,
- _a.export = 89 /* ExportKeyword */,
- _a.extends = 90 /* ExtendsKeyword */,
- _a.false = 91 /* FalseKeyword */,
- _a.finally = 92 /* FinallyKeyword */,
- _a.for = 93 /* ForKeyword */,
- _a.from = 149 /* FromKeyword */,
- _a.function = 94 /* FunctionKeyword */,
- _a.get = 131 /* GetKeyword */,
- _a.if = 95 /* IfKeyword */,
- _a.implements = 113 /* ImplementsKeyword */,
- _a.import = 96 /* ImportKeyword */,
- _a.in = 97 /* InKeyword */,
- _a.infer = 132 /* InferKeyword */,
- _a.instanceof = 98 /* InstanceOfKeyword */,
- _a.interface = 114 /* InterfaceKeyword */,
- _a.is = 133 /* IsKeyword */,
- _a.keyof = 134 /* KeyOfKeyword */,
- _a.let = 115 /* LetKeyword */,
- _a.module = 135 /* ModuleKeyword */,
- _a.namespace = 136 /* NamespaceKeyword */,
- _a.never = 137 /* NeverKeyword */,
- _a.new = 99 /* NewKeyword */,
- _a.null = 100 /* NullKeyword */,
- _a.number = 140 /* NumberKeyword */,
- _a.object = 141 /* ObjectKeyword */,
- _a.package = 116 /* PackageKeyword */,
- _a.private = 117 /* PrivateKeyword */,
- _a.protected = 118 /* ProtectedKeyword */,
- _a.public = 119 /* PublicKeyword */,
- _a.readonly = 138 /* ReadonlyKeyword */,
- _a.require = 139 /* RequireKeyword */,
- _a.global = 150 /* GlobalKeyword */,
- _a.return = 101 /* ReturnKeyword */,
- _a.set = 142 /* SetKeyword */,
- _a.static = 120 /* StaticKeyword */,
- _a.string = 143 /* StringKeyword */,
- _a.super = 102 /* SuperKeyword */,
- _a.switch = 103 /* SwitchKeyword */,
- _a.symbol = 144 /* SymbolKeyword */,
- _a.this = 104 /* ThisKeyword */,
- _a.throw = 105 /* ThrowKeyword */,
- _a.true = 106 /* TrueKeyword */,
- _a.try = 107 /* TryKeyword */,
- _a.type = 145 /* TypeKeyword */,
- _a.typeof = 108 /* TypeOfKeyword */,
- _a.undefined = 146 /* UndefinedKeyword */,
- _a.unique = 147 /* UniqueKeyword */,
- _a.unknown = 148 /* UnknownKeyword */,
- _a.var = 109 /* VarKeyword */,
- _a.void = 110 /* VoidKeyword */,
- _a.while = 111 /* WhileKeyword */,
- _a.with = 112 /* WithKeyword */,
- _a.yield = 121 /* YieldKeyword */,
- _a.async = 126 /* AsyncKeyword */,
- _a.await = 127 /* AwaitKeyword */,
- _a.of = 152 /* OfKeyword */,
- _a);
- var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
- var textToToken = ts.createMapFromTemplate(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, "": 30 /* LessThanSlashToken */, ">>": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 74 /* CaretEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }));
- /*
- 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,];
- /**
- * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
- * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
- * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
- * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
- */
- var unicodeESNextIdentifierStart = [65, 90, 97, 122, 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, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 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, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 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, 2809, 2809, 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, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 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, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 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, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 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, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 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, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 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, 43824, 43866, 43868, 43879, 43888, 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, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101];
- var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 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, 2556, 2556, 2558, 2558, 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, 2809, 2815, 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, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 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, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 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, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 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, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 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, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 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, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 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, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 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, 65071, 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, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999];
- /**
- * Test for whether a single line comment's text contains a directive.
- */
- var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
- /**
- * Test for whether a multi-line comment's last line contains a directive.
- */
- var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
- 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;
- }
- if (code < map[mid]) {
- hi = mid;
- }
- else {
- lo = mid + 2;
- }
- }
- return false;
- }
- /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
- return languageVersion >= 2 /* ES2015 */ ?
- lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
- languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
- lookupInUnicodeMap(code, unicodeES3IdentifierStart);
- }
- ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
- function isUnicodeIdentifierPart(code, languageVersion) {
- return languageVersion >= 2 /* ES2015 */ ?
- lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
- languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
- lookupInUnicodeMap(code, unicodeES3IdentifierPart);
- }
- function makeReverseMap(source) {
- var result = [];
- source.forEach(function (value, name) {
- result[value] = name;
- });
- return result;
- }
- var tokenStrings = makeReverseMap(textToToken);
- function tokenToString(t) {
- 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;
- var lineStart = 0;
- while (pos < text.length) {
- var ch = text.charCodeAt(pos);
- pos++;
- switch (ch) {
- case 13 /* carriageReturn */:
- if (text.charCodeAt(pos) === 10 /* lineFeed */) {
- pos++;
- }
- // falls through
- case 10 /* lineFeed */:
- result.push(lineStart);
- lineStart = pos;
- break;
- default:
- if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
- result.push(lineStart);
- lineStart = pos;
- }
- break;
- }
- }
- result.push(lineStart);
- return result;
- }
- ts.computeLineStarts = computeLineStarts;
- function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
- return sourceFile.getPositionOfLineAndCharacter ?
- sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
- computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
- }
- ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
- /* @internal */
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
- if (line < 0 || line >= lineStarts.length) {
- if (allowEdits) {
- // Clamp line to nearest allowable value
- line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
- }
- else {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
- }
- }
- var res = lineStarts[line] + character;
- if (allowEdits) {
- // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
- // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
- // apply them to the computed position to improve accuracy
- return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
- }
- if (line < lineStarts.length - 1) {
- ts.Debug.assert(res < lineStarts[line + 1]);
- }
- else if (debugText !== undefined) {
- 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 */
- function computeLineAndCharacterOfPosition(lineStarts, position) {
- var lineNumber = computeLineOfPosition(lineStarts, position);
- return {
- line: lineNumber,
- character: position - lineStarts[lineNumber]
- };
- }
- ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
- /**
- * @internal
- * We assume the first line starts at position 0 and 'position' is non-negative.
- */
- function computeLineOfPosition(lineStarts, position, lowerBound) {
- var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
- 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");
- }
- return lineNumber;
- }
- ts.computeLineOfPosition = computeLineOfPosition;
- /** @internal */
- function getLinesBetweenPositions(sourceFile, pos1, pos2) {
- if (pos1 === pos2)
- return 0;
- var lineStarts = getLineStarts(sourceFile);
- var lower = Math.min(pos1, pos2);
- var isNegative = lower === pos2;
- var upper = isNegative ? pos1 : pos2;
- var lowerLine = computeLineOfPosition(lineStarts, lower);
- var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
- return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
- }
- ts.getLinesBetweenPositions = getLinesBetweenPositions;
- function getLineAndCharacterOfPosition(sourceFile, position) {
- return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
- }
- ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
- function isWhiteSpaceLike(ch) {
- return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
- }
- ts.isWhiteSpaceLike = isWhiteSpaceLike;
- /** Does not include line breaks. For that, see isWhiteSpaceLike. */
- function isWhiteSpaceSingleLine(ch) {
- // 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) {
- // 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 /* _0 */ && ch <= 57 /* _9 */;
- }
- function isHexDigit(ch) {
- return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
- }
- function isCodePoint(code) {
- return code <= 0x10FFFF;
- }
- /* @internal */
- function isOctalDigit(ch) {
- 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 /* carriageReturn */:
- case 10 /* lineFeed */:
- case 9 /* tab */:
- case 11 /* verticalTab */:
- case 12 /* formFeed */:
- case 32 /* space */:
- case 47 /* slash */:
- // starts of normal trivia
- // falls through
- case 60 /* lessThan */:
- case 124 /* bar */:
- case 61 /* equals */:
- case 62 /* greaterThan */:
- // Starts of conflict marker trivia
- return true;
- case 35 /* hash */:
- // Only if its the beginning can we have #! trivia
- return pos === 0;
- default:
- 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 /* carriageReturn */:
- if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
- pos++;
- }
- // falls through
- case 10 /* lineFeed */:
- pos++;
- if (stopAfterLineBreak) {
- return pos;
- }
- continue;
- case 9 /* tab */:
- case 11 /* verticalTab */:
- case 12 /* formFeed */:
- case 32 /* space */:
- pos++;
- continue;
- case 47 /* slash */:
- if (stopAtComments) {
- break;
- }
- if (text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- while (pos < text.length) {
- if (isLineBreak(text.charCodeAt(pos))) {
- break;
- }
- pos++;
- }
- continue;
- }
- if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
- pos += 2;
- while (pos < text.length) {
- if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- break;
- }
- pos++;
- }
- continue;
- }
- break;
- case 60 /* lessThan */:
- case 124 /* bar */:
- case 61 /* equals */:
- case 62 /* greaterThan */:
- if (isConflictMarkerTrivia(text, pos)) {
- pos = scanConflictMarkerTrivia(text, pos);
- continue;
- }
- break;
- case 35 /* hash */:
- if (pos === 0 && isShebangTrivia(text, pos)) {
- pos = scanShebangTrivia(text, pos);
- continue;
- }
- break;
- default:
- if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
- pos++;
- continue;
- }
- break;
- }
- return pos;
- }
- }
- 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) {
- for (var i = 0; i < mergeConflictMarkerLength; i++) {
- if (text.charCodeAt(pos + i) !== ch) {
- return false;
- }
- }
- return ch === 61 /* equals */ ||
- text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
- }
- }
- return false;
- }
- function scanConflictMarkerTrivia(text, pos, error) {
- if (error) {
- error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
- }
- var ch = text.charCodeAt(pos);
- var len = text.length;
- if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
- while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
- pos++;
- }
- }
- else {
- 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 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
- break;
- }
- pos++;
- }
- }
- return pos;
- }
- var shebangTriviaRegex = /^#!.*/;
- /*@internal*/
- 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);
- }
- ts.isShebangTrivia = isShebangTrivia;
- /*@internal*/
- function scanShebangTrivia(text, pos) {
- var shebang = shebangTriviaRegex.exec(text)[0];
- pos = pos + shebang.length;
- return pos;
- }
- ts.scanShebangTrivia = scanShebangTrivia;
- /**
- * 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;
- var pendingKind;
- var pendingHasTrailingNewLine;
- var hasPendingCommentRange = false;
- var collecting = trailing;
- var accumulator = initial;
- if (pos === 0) {
- collecting = true;
- var shebang = getShebang(text);
- if (shebang) {
- pos = shebang.length;
- }
- }
- scan: while (pos >= 0 && pos < text.length) {
- var ch = text.charCodeAt(pos);
- switch (ch) {
- case 13 /* carriageReturn */:
- if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
- pos++;
- }
- // falls through
- case 10 /* lineFeed */:
- pos++;
- if (trailing) {
- break scan;
- }
- collecting = true;
- if (hasPendingCommentRange) {
- pendingHasTrailingNewLine = true;
- }
- continue;
- case 9 /* tab */:
- case 11 /* verticalTab */:
- case 12 /* formFeed */:
- case 32 /* space */:
- pos++;
- continue;
- case 47 /* slash */:
- var nextChar = text.charCodeAt(pos + 1);
- var hasTrailingNewLine = false;
- if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
- var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
- var startPos = pos;
- pos += 2;
- if (nextChar === 47 /* slash */) {
- while (pos < text.length) {
- if (isLineBreak(text.charCodeAt(pos))) {
- hasTrailingNewLine = true;
- break;
- }
- pos++;
- }
- }
- else {
- while (pos < text.length) {
- if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- break;
- }
- pos++;
- }
- }
- if (collecting) {
- 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;
- }
- }
- pendingPos = startPos;
- pendingEnd = pos;
- pendingKind = kind;
- pendingHasTrailingNewLine = hasTrailingNewLine;
- hasPendingCommentRange = true;
- }
- continue;
- }
- break scan;
- default:
- if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
- if (hasPendingCommentRange && isLineBreak(ch)) {
- pendingHasTrailingNewLine = true;
- }
- pos++;
- continue;
- }
- break scan;
- }
- }
- if (hasPendingCommentRange) {
- accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
- }
- return accumulator;
- }
- function forEachLeadingCommentRange(text, pos, cb, state) {
- return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
- }
- ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
- function forEachTrailingCommentRange(text, pos, cb, state) {
- return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
- }
- ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
- function reduceEachLeadingCommentRange(text, pos, 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(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
- }
- ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
- function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
- if (!comments) {
- comments = [];
- }
- comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
- return comments;
- }
- function getLeadingCommentRanges(text, pos) {
- return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
- }
- ts.getLeadingCommentRanges = getLeadingCommentRanges;
- function getTrailingCommentRanges(text, pos) {
- 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) {
- return match[0];
- }
- }
- ts.getShebang = getShebang;
- function isIdentifierStart(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, identifierVariant) {
- return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
- ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
- // "-" and ":" are valid in JSX Identifiers
- (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
- ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
- }
- ts.isIdentifierPart = isIdentifierPart;
- /* @internal */
- function isIdentifierText(name, languageVersion, identifierVariant) {
- var ch = codePointAt(name, 0);
- if (!isIdentifierStart(ch, languageVersion)) {
- return false;
- }
- for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
- if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
- return false;
- }
- }
- 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 /* 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;
- var tokenFlags;
- var commentDirectives;
- var inJSDocType = 0;
- setText(text, start, length);
- var scanner = {
- getStartPos: function () { return startPos; },
- getTextPos: function () { return pos; },
- getToken: function () { return token; },
- getTokenPos: function () { return tokenPos; },
- getTokenText: function () { return text.substring(tokenPos, pos); },
- getTokenValue: function () { return tokenValue; },
- hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
- hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
- hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
- isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
- isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
- isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
- getCommentDirectives: function () { return commentDirectives; },
- getTokenFlags: function () { return tokenFlags; },
- reScanGreaterToken: reScanGreaterToken,
- reScanSlashToken: reScanSlashToken,
- reScanTemplateToken: reScanTemplateToken,
- reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
- scanJsxIdentifier: scanJsxIdentifier,
- scanJsxAttributeValue: scanJsxAttributeValue,
- reScanJsxAttributeValue: reScanJsxAttributeValue,
- reScanJsxToken: reScanJsxToken,
- reScanLessThanToken: reScanLessThanToken,
- reScanQuestionToken: reScanQuestionToken,
- scanJsxToken: scanJsxToken,
- scanJsDocToken: scanJsDocToken,
- scan: scan,
- getText: getText,
- clearCommentDirectives: clearCommentDirectives,
- setText: setText,
- setScriptTarget: setScriptTarget,
- setLanguageVariant: setLanguageVariant,
- setOnError: setOnError,
- setTextPos: setTextPos,
- setInJSDocType: setInJSDocType,
- tryScan: tryScan,
- lookAhead: lookAhead,
- scanRange: scanRange,
- };
- if (ts.Debug.isDebugging) {
- Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
- get: function () {
- var text = scanner.getText();
- return text.slice(0, scanner.getStartPos()) + "â" + text.slice(scanner.getStartPos());
- },
- });
- }
- return scanner;
- function error(message, errPos, length) {
- if (errPos === void 0) { errPos = pos; }
- if (onError) {
- var oldPos = pos;
- pos = errPos;
- onError(message, length || 0);
- pos = oldPos;
- }
- }
- function scanNumberFragment() {
- var start = pos;
- var allowSeparator = false;
- var isPreviousTokenSeparator = false;
- var result = "";
- while (true) {
- var ch = text.charCodeAt(pos);
- if (ch === 95 /* _ */) {
- tokenFlags |= 512 /* ContainsSeparator */;
- if (allowSeparator) {
- allowSeparator = false;
- isPreviousTokenSeparator = true;
- result += text.substring(start, pos);
- }
- else if (isPreviousTokenSeparator) {
- error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
- }
- else {
- error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
- }
- pos++;
- start = pos;
- continue;
- }
- if (isDigit(ch)) {
- allowSeparator = true;
- isPreviousTokenSeparator = false;
- pos++;
- continue;
- }
- break;
- }
- if (text.charCodeAt(pos - 1) === 95 /* _ */) {
- error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
- }
- return result + text.substring(start, pos);
- }
- function scanNumber() {
- var start = pos;
- var mainFragment = scanNumberFragment();
- var decimalFragment;
- var scientificFragment;
- if (text.charCodeAt(pos) === 46 /* dot */) {
- pos++;
- decimalFragment = scanNumberFragment();
- }
- var end = pos;
- if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
- pos++;
- tokenFlags |= 16 /* Scientific */;
- if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
- pos++;
- var preNumericPart = pos;
- var finalFragment = scanNumberFragment();
- if (!finalFragment) {
- error(ts.Diagnostics.Digit_expected);
- }
- else {
- scientificFragment = text.substring(end, preNumericPart) + finalFragment;
- end = pos;
- }
- }
- var result;
- if (tokenFlags & 512 /* ContainsSeparator */) {
- result = mainFragment;
- if (decimalFragment) {
- result += "." + decimalFragment;
- }
- if (scientificFragment) {
- result += scientificFragment;
- }
- }
- else {
- result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
- }
- if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
- checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
- return {
- type: 8 /* NumericLiteral */,
- value: "" + +result // if value is not an integer, it can be safely coerced to a number
- };
- }
- else {
- tokenValue = result;
- var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
- checkForIdentifierStartAfterNumericLiteral(start);
- return { type: type, value: tokenValue };
- }
- }
- function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
- if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
- return;
- }
- var identifierStart = pos;
- var length = scanIdentifierParts().length;
- if (length === 1 && text[identifierStart] === "n") {
- if (isScientific) {
- error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
- }
- else {
- error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
- }
- }
- else {
- error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
- pos = identifierStart;
- }
- }
- function scanOctalDigits() {
- var start = pos;
- while (isOctalDigit(text.charCodeAt(pos))) {
- pos++;
- }
- 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) {
- var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
- return valueString ? parseInt(valueString, 16) : -1;
- }
- /**
- * Scans as many hexadecimal digits as are available in the text,
- * returning "" if the given number of digits was unavailable.
- */
- function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
- return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
- }
- function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
- var valueChars = [];
- var allowSeparator = false;
- var isPreviousTokenSeparator = false;
- while (valueChars.length < minCount || scanAsManyAsPossible) {
- var ch = text.charCodeAt(pos);
- if (canHaveSeparators && ch === 95 /* _ */) {
- tokenFlags |= 512 /* ContainsSeparator */;
- if (allowSeparator) {
- allowSeparator = false;
- isPreviousTokenSeparator = true;
- }
- else if (isPreviousTokenSeparator) {
- error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
- }
- else {
- error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
- }
- pos++;
- continue;
- }
- allowSeparator = canHaveSeparators;
- if (ch >= 65 /* A */ && ch <= 70 /* F */) {
- ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
- }
- else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
- (ch >= 97 /* a */ && ch <= 102 /* f */))) {
- break;
- }
- valueChars.push(ch);
- pos++;
- isPreviousTokenSeparator = false;
- }
- if (valueChars.length < minCount) {
- valueChars = [];
- }
- if (text.charCodeAt(pos - 1) === 95 /* _ */) {
- error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
- }
- return String.fromCharCode.apply(String, valueChars);
- }
- function scanString(jsxAttributeString) {
- if (jsxAttributeString === void 0) { jsxAttributeString = false; }
- var quote = text.charCodeAt(pos);
- pos++;
- var result = "";
- var start = pos;
- while (true) {
- if (pos >= end) {
- result += text.substring(start, pos);
- tokenFlags |= 4 /* Unterminated */;
- error(ts.Diagnostics.Unterminated_string_literal);
- break;
- }
- var ch = text.charCodeAt(pos);
- if (ch === quote) {
- result += text.substring(start, pos);
- pos++;
- break;
- }
- if (ch === 92 /* backslash */ && !jsxAttributeString) {
- result += text.substring(start, pos);
- result += scanEscapeSequence();
- start = pos;
- continue;
- }
- if (isLineBreak(ch) && !jsxAttributeString) {
- result += text.substring(start, pos);
- tokenFlags |= 4 /* Unterminated */;
- error(ts.Diagnostics.Unterminated_string_literal);
- break;
- }
- pos++;
- }
- return result;
- }
- /**
- * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
- * a literal component of a TemplateExpression.
- */
- function scanTemplateAndSetTokenValue(isTaggedTemplate) {
- var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
- pos++;
- var start = pos;
- var contents = "";
- var resultingToken;
- while (true) {
- if (pos >= end) {
- contents += text.substring(start, pos);
- tokenFlags |= 4 /* Unterminated */;
- error(ts.Diagnostics.Unterminated_template_literal);
- resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
- break;
- }
- var currChar = text.charCodeAt(pos);
- // '`'
- if (currChar === 96 /* backtick */) {
- contents += text.substring(start, pos);
- pos++;
- resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
- break;
- }
- // '${'
- if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
- contents += text.substring(start, pos);
- pos += 2;
- resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
- break;
- }
- // Escape character
- if (currChar === 92 /* backslash */) {
- contents += text.substring(start, pos);
- contents += scanEscapeSequence(isTaggedTemplate);
- start = pos;
- continue;
- }
- // 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 /* lineFeed */) {
- pos++;
- }
- contents += "\n";
- start = pos;
- continue;
- }
- pos++;
- }
- ts.Debug.assert(resultingToken !== undefined);
- tokenValue = contents;
- return resultingToken;
- }
- function scanEscapeSequence(isTaggedTemplate) {
- var start = pos;
- pos++;
- if (pos >= end) {
- error(ts.Diagnostics.Unexpected_end_of_text);
- return "";
- }
- var ch = text.charCodeAt(pos);
- pos++;
- switch (ch) {
- case 48 /* _0 */:
- // '\01'
- if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
- pos++;
- tokenFlags |= 2048 /* ContainsInvalidEscape */;
- return text.substring(start, pos);
- }
- return "\0";
- case 98 /* b */:
- return "\b";
- case 116 /* t */:
- return "\t";
- case 110 /* n */:
- return "\n";
- case 118 /* v */:
- return "\v";
- case 102 /* f */:
- return "\f";
- case 114 /* r */:
- return "\r";
- case 39 /* singleQuote */:
- return "\'";
- case 34 /* doubleQuote */:
- return "\"";
- case 117 /* u */:
- if (isTaggedTemplate) {
- // '\u' or '\u0' or '\u00' or '\u000'
- for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
- if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
- pos = escapePos;
- tokenFlags |= 2048 /* ContainsInvalidEscape */;
- return text.substring(start, pos);
- }
- }
- }
- // '\u{DDDDDDDD}'
- if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
- pos++;
- // '\u{'
- if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
- tokenFlags |= 2048 /* ContainsInvalidEscape */;
- return text.substring(start, pos);
- }
- if (isTaggedTemplate) {
- var savePos = pos;
- var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
- var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
- // '\u{Not Code Point' or '\u{CodePoint'
- if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
- tokenFlags |= 2048 /* ContainsInvalidEscape */;
- return text.substring(start, pos);
- }
- else {
- pos = savePos;
- }
- }
- tokenFlags |= 8 /* ExtendedUnicodeEscape */;
- return scanExtendedUnicodeEscape();
- }
- tokenFlags |= 1024 /* UnicodeEscape */;
- // '\uDDDD'
- return scanHexadecimalEscape(/*numDigits*/ 4);
- case 120 /* x */:
- if (isTaggedTemplate) {
- if (!isHexDigit(text.charCodeAt(pos))) {
- tokenFlags |= 2048 /* ContainsInvalidEscape */;
- return text.substring(start, pos);
- }
- else if (!isHexDigit(text.charCodeAt(pos + 1))) {
- pos++;
- tokenFlags |= 2048 /* ContainsInvalidEscape */;
- return text.substring(start, pos);
- }
- }
- // '\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++;
- }
- // falls through
- case 10 /* lineFeed */:
- case 8232 /* lineSeparator */:
- case 8233 /* paragraphSeparator */:
- return "";
- default:
- return String.fromCharCode(ch);
- }
- }
- function scanHexadecimalEscape(numDigits) {
- var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
- if (escapedValue >= 0) {
- return String.fromCharCode(escapedValue);
- }
- else {
- error(ts.Diagnostics.Hexadecimal_digit_expected);
- return "";
- }
- }
- function scanExtendedUnicodeEscape() {
- var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
- var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
- var isInvalidExtendedEscape = false;
- // Validate the value of the digit
- if (escapedValue < 0) {
- error(ts.Diagnostics.Hexadecimal_digit_expected);
- isInvalidExtendedEscape = true;
- }
- else if (escapedValue > 0x10FFFF) {
- error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
- isInvalidExtendedEscape = true;
- }
- if (pos >= end) {
- error(ts.Diagnostics.Unexpected_end_of_text);
- isInvalidExtendedEscape = true;
- }
- else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
- // Only swallow the following character up if it's a '}'.
- pos++;
- }
- else {
- error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
- isInvalidExtendedEscape = true;
- }
- if (isInvalidExtendedEscape) {
- return "";
- }
- return utf16EncodeAsString(escapedValue);
- }
- // 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 /* u */) {
- var start_1 = pos;
- pos += 2;
- var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
- pos = start_1;
- return value;
- }
- return -1;
- }
- function peekExtendedUnicodeEscape() {
- if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
- var start_2 = pos;
- pos += 3;
- var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
- var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
- pos = start_2;
- return escapedValue;
- }
- return -1;
- }
- function scanIdentifierParts() {
- var result = "";
- var start = pos;
- while (pos < end) {
- var ch = codePointAt(text, pos);
- if (isIdentifierPart(ch, languageVersion)) {
- pos += charSize(ch);
- }
- else if (ch === 92 /* backslash */) {
- ch = peekExtendedUnicodeEscape();
- if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
- pos += 3;
- tokenFlags |= 8 /* ExtendedUnicodeEscape */;
- result += scanExtendedUnicodeEscape();
- start = pos;
- continue;
- }
- ch = peekUnicodeEscape();
- if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
- break;
- }
- tokenFlags |= 1024 /* UnicodeEscape */;
- result += text.substring(start, pos);
- result += utf16EncodeAsString(ch);
- // Valid Unicode escape is always six characters
- pos += 6;
- start = pos;
- }
- else {
- break;
- }
- }
- result += text.substring(start, pos);
- 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 /* a */ && ch <= 122 /* z */) {
- var keyword = textToKeyword.get(tokenValue);
- if (keyword !== undefined) {
- return token = keyword;
- }
- }
- }
- return token = 75 /* Identifier */;
- }
- function scanBinaryOrOctalDigits(base) {
- var value = "";
- // 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 separatorAllowed = false;
- var isPreviousTokenSeparator = false;
- while (true) {
- var ch = text.charCodeAt(pos);
- // 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;
- }
- else if (isPreviousTokenSeparator) {
- error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
- }
- else {
- error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
- }
- pos++;
- continue;
- }
- separatorAllowed = true;
- if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
- break;
- }
- value += text[pos];
- pos++;
- isPreviousTokenSeparator = false;
- }
- 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;
- }
- function checkBigIntSuffix() {
- if (text.charCodeAt(pos) === 110 /* n */) {
- tokenValue += "n";
- // Use base 10 instead of base 2 or base 8 for shorter literals
- if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
- tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
- }
- pos++;
- return 9 /* BigIntLiteral */;
- }
- else { // not a bigint, so can convert to number in simplified form
- // Number() may not support 0b or 0o, so use parseInt() instead
- var numericValue = tokenFlags & 128 /* BinarySpecifier */
- ? parseInt(tokenValue.slice(2), 2) // skip "0b"
- : tokenFlags & 256 /* OctalSpecifier */
- ? parseInt(tokenValue.slice(2), 8) // skip "0o"
- : +tokenValue;
- tokenValue = "" + numericValue;
- return 8 /* NumericLiteral */;
- }
- }
- function scan() {
- var _a;
- startPos = pos;
- tokenFlags = 0 /* None */;
- var asteriskSeen = false;
- while (true) {
- tokenPos = pos;
- if (pos >= end) {
- return token = 1 /* EndOfFileToken */;
- }
- var ch = codePointAt(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 /* ShebangTrivia */;
- }
- }
- switch (ch) {
- case 10 /* lineFeed */:
- case 13 /* carriageReturn */:
- tokenFlags |= 1 /* PrecedingLineBreak */;
- if (skipTrivia) {
- pos++;
- continue;
- }
- else {
- 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 /* NewLineTrivia */;
- }
- case 9 /* tab */:
- case 11 /* verticalTab */:
- case 12 /* formFeed */:
- case 32 /* space */:
- case 160 /* nonBreakingSpace */:
- case 5760 /* ogham */:
- case 8192 /* enQuad */:
- case 8193 /* emQuad */:
- case 8194 /* enSpace */:
- case 8195 /* emSpace */:
- case 8196 /* threePerEmSpace */:
- case 8197 /* fourPerEmSpace */:
- case 8198 /* sixPerEmSpace */:
- case 8199 /* figureSpace */:
- case 8200 /* punctuationSpace */:
- case 8201 /* thinSpace */:
- case 8202 /* hairSpace */:
- case 8203 /* zeroWidthSpace */:
- case 8239 /* narrowNoBreakSpace */:
- case 8287 /* mathematicalSpace */:
- case 12288 /* ideographicSpace */:
- case 65279 /* byteOrderMark */:
- if (skipTrivia) {
- pos++;
- continue;
- }
- else {
- while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
- pos++;
- }
- return token = 5 /* WhitespaceTrivia */;
- }
- case 33 /* exclamation */:
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- if (text.charCodeAt(pos + 2) === 61 /* equals */) {
- return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
- }
- return pos += 2, token = 35 /* ExclamationEqualsToken */;
- }
- pos++;
- return token = 53 /* ExclamationToken */;
- case 34 /* doubleQuote */:
- case 39 /* singleQuote */:
- tokenValue = scanString();
- return token = 10 /* StringLiteral */;
- case 96 /* backtick */:
- return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
- case 37 /* percent */:
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 68 /* PercentEqualsToken */;
- }
- pos++;
- return token = 44 /* PercentToken */;
- case 38 /* ampersand */:
- if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
- return pos += 2, token = 55 /* AmpersandAmpersandToken */;
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 72 /* AmpersandEqualsToken */;
- }
- pos++;
- return token = 50 /* AmpersandToken */;
- case 40 /* openParen */:
- pos++;
- return token = 20 /* OpenParenToken */;
- case 41 /* closeParen */:
- pos++;
- return token = 21 /* CloseParenToken */;
- case 42 /* asterisk */:
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 65 /* AsteriskEqualsToken */;
- }
- if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
- if (text.charCodeAt(pos + 2) === 61 /* equals */) {
- return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
- }
- return pos += 2, token = 42 /* AsteriskAsteriskToken */;
- }
- pos++;
- if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
- // decoration at the start of a JSDoc comment line
- asteriskSeen = true;
- continue;
- }
- return token = 41 /* AsteriskToken */;
- case 43 /* plus */:
- if (text.charCodeAt(pos + 1) === 43 /* plus */) {
- return pos += 2, token = 45 /* PlusPlusToken */;
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 63 /* PlusEqualsToken */;
- }
- pos++;
- return token = 39 /* PlusToken */;
- case 44 /* comma */:
- pos++;
- return token = 27 /* CommaToken */;
- case 45 /* minus */:
- if (text.charCodeAt(pos + 1) === 45 /* minus */) {
- return pos += 2, token = 46 /* MinusMinusToken */;
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 64 /* MinusEqualsToken */;
- }
- pos++;
- return token = 40 /* MinusToken */;
- case 46 /* dot */:
- if (isDigit(text.charCodeAt(pos + 1))) {
- tokenValue = scanNumber().value;
- return token = 8 /* NumericLiteral */;
- }
- if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
- return pos += 3, token = 25 /* DotDotDotToken */;
- }
- pos++;
- return token = 24 /* DotToken */;
- case 47 /* slash */:
- // Single-line comment
- if (text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- while (pos < end) {
- if (isLineBreak(text.charCodeAt(pos))) {
- break;
- }
- pos++;
- }
- commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
- if (skipTrivia) {
- continue;
- }
- else {
- return token = 2 /* SingleLineCommentTrivia */;
- }
- }
- // Multi-line comment
- if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
- pos += 2;
- if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
- tokenFlags |= 2 /* PrecedingJSDocComment */;
- }
- var commentClosed = false;
- var lastLineStart = tokenPos;
- while (pos < end) {
- var ch_1 = text.charCodeAt(pos);
- if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- commentClosed = true;
- break;
- }
- pos++;
- if (isLineBreak(ch_1)) {
- lastLineStart = pos;
- tokenFlags |= 1 /* PrecedingLineBreak */;
- }
- }
- commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
- if (!commentClosed) {
- error(ts.Diagnostics.Asterisk_Slash_expected);
- }
- if (skipTrivia) {
- continue;
- }
- else {
- if (!commentClosed) {
- tokenFlags |= 4 /* Unterminated */;
- }
- return token = 3 /* MultiLineCommentTrivia */;
- }
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 67 /* SlashEqualsToken */;
- }
- pos++;
- return token = 43 /* SlashToken */;
- case 48 /* _0 */:
- if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
- pos += 2;
- tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
- if (!tokenValue) {
- error(ts.Diagnostics.Hexadecimal_digit_expected);
- tokenValue = "0";
- }
- tokenValue = "0x" + tokenValue;
- tokenFlags |= 64 /* HexSpecifier */;
- return token = checkBigIntSuffix();
- }
- else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
- pos += 2;
- tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
- if (!tokenValue) {
- error(ts.Diagnostics.Binary_digit_expected);
- tokenValue = "0";
- }
- tokenValue = "0b" + tokenValue;
- tokenFlags |= 128 /* BinarySpecifier */;
- return token = checkBigIntSuffix();
- }
- else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
- pos += 2;
- tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
- if (!tokenValue) {
- error(ts.Diagnostics.Octal_digit_expected);
- tokenValue = "0";
- }
- tokenValue = "0o" + tokenValue;
- tokenFlags |= 256 /* OctalSpecifier */;
- return token = checkBigIntSuffix();
- }
- // Try to parse as an octal
- if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
- tokenValue = "" + scanOctalDigits();
- tokenFlags |= 32 /* Octal */;
- return token = 8 /* NumericLiteral */;
- }
- // 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 */:
- (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
- return token;
- case 58 /* colon */:
- pos++;
- return token = 58 /* ColonToken */;
- case 59 /* semicolon */:
- pos++;
- return token = 26 /* SemicolonToken */;
- case 60 /* lessThan */:
- if (isConflictMarkerTrivia(text, pos)) {
- pos = scanConflictMarkerTrivia(text, pos, error);
- if (skipTrivia) {
- continue;
- }
- else {
- return token = 7 /* ConflictMarkerTrivia */;
- }
- }
- if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
- if (text.charCodeAt(pos + 2) === 61 /* equals */) {
- return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
- }
- return pos += 2, token = 47 /* LessThanLessThanToken */;
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 32 /* LessThanEqualsToken */;
- }
- if (languageVariant === 1 /* JSX */ &&
- text.charCodeAt(pos + 1) === 47 /* slash */ &&
- text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
- return pos += 2, token = 30 /* LessThanSlashToken */;
- }
- pos++;
- return token = 29 /* LessThanToken */;
- case 61 /* equals */:
- if (isConflictMarkerTrivia(text, pos)) {
- pos = scanConflictMarkerTrivia(text, pos, error);
- if (skipTrivia) {
- continue;
- }
- else {
- return token = 7 /* ConflictMarkerTrivia */;
- }
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- if (text.charCodeAt(pos + 2) === 61 /* equals */) {
- return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
- }
- return pos += 2, token = 34 /* EqualsEqualsToken */;
- }
- if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
- return pos += 2, token = 38 /* EqualsGreaterThanToken */;
- }
- pos++;
- return token = 62 /* EqualsToken */;
- case 62 /* greaterThan */:
- if (isConflictMarkerTrivia(text, pos)) {
- pos = scanConflictMarkerTrivia(text, pos, error);
- if (skipTrivia) {
- continue;
- }
- else {
- return token = 7 /* ConflictMarkerTrivia */;
- }
- }
- pos++;
- return token = 31 /* GreaterThanToken */;
- case 63 /* question */:
- pos++;
- if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
- pos++;
- return token = 28 /* QuestionDotToken */;
- }
- if (text.charCodeAt(pos) === 63 /* question */) {
- pos++;
- return token = 60 /* QuestionQuestionToken */;
- }
- return token = 57 /* QuestionToken */;
- case 91 /* openBracket */:
- pos++;
- return token = 22 /* OpenBracketToken */;
- case 93 /* closeBracket */:
- pos++;
- return token = 23 /* CloseBracketToken */;
- case 94 /* caret */:
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 74 /* CaretEqualsToken */;
- }
- pos++;
- return token = 52 /* CaretToken */;
- case 123 /* openBrace */:
- pos++;
- return token = 18 /* OpenBraceToken */;
- case 124 /* bar */:
- if (isConflictMarkerTrivia(text, pos)) {
- pos = scanConflictMarkerTrivia(text, pos, error);
- if (skipTrivia) {
- continue;
- }
- else {
- return token = 7 /* ConflictMarkerTrivia */;
- }
- }
- if (text.charCodeAt(pos + 1) === 124 /* bar */) {
- return pos += 2, token = 56 /* BarBarToken */;
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 73 /* BarEqualsToken */;
- }
- pos++;
- return token = 51 /* BarToken */;
- case 125 /* closeBrace */:
- pos++;
- return token = 19 /* CloseBraceToken */;
- case 126 /* tilde */:
- pos++;
- return token = 54 /* TildeToken */;
- case 64 /* at */:
- pos++;
- return token = 59 /* AtToken */;
- case 92 /* backslash */:
- var extendedCookedChar = peekExtendedUnicodeEscape();
- if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
- pos += 3;
- tokenFlags |= 8 /* ExtendedUnicodeEscape */;
- tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
- return token = getIdentifierToken();
- }
- var cookedChar = peekUnicodeEscape();
- if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
- pos += 6;
- tokenFlags |= 1024 /* UnicodeEscape */;
- tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
- return token = getIdentifierToken();
- }
- error(ts.Diagnostics.Invalid_character);
- pos++;
- return token = 0 /* Unknown */;
- case 35 /* hash */:
- if (pos !== 0 && text[pos + 1] === "!") {
- error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
- pos++;
- return token = 0 /* Unknown */;
- }
- pos++;
- if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
- pos++;
- while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
- pos++;
- tokenValue = text.substring(tokenPos, pos);
- if (ch === 92 /* backslash */) {
- tokenValue += scanIdentifierParts();
- }
- }
- else {
- tokenValue = "#";
- error(ts.Diagnostics.Invalid_character);
- }
- return token = 76 /* PrivateIdentifier */;
- default:
- if (isIdentifierStart(ch, languageVersion)) {
- pos += charSize(ch);
- while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
- pos += charSize(ch);
- tokenValue = text.substring(tokenPos, pos);
- if (ch === 92 /* backslash */) {
- tokenValue += scanIdentifierParts();
- }
- return token = getIdentifierToken();
- }
- else if (isWhiteSpaceSingleLine(ch)) {
- pos += charSize(ch);
- continue;
- }
- else if (isLineBreak(ch)) {
- tokenFlags |= 1 /* PrecedingLineBreak */;
- pos += charSize(ch);
- continue;
- }
- error(ts.Diagnostics.Invalid_character);
- pos += charSize(ch);
- return token = 0 /* Unknown */;
- }
- }
- }
- function reScanGreaterToken() {
- if (token === 31 /* 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 = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
- }
- return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
- }
- if (text.charCodeAt(pos + 1) === 61 /* equals */) {
- return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
- }
- pos++;
- return token = 48 /* GreaterThanGreaterThanToken */;
- }
- if (text.charCodeAt(pos) === 61 /* equals */) {
- pos++;
- return token = 33 /* GreaterThanEqualsToken */;
- }
- }
- return token;
- }
- function reScanSlashToken() {
- if (token === 43 /* SlashToken */ || token === 67 /* 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 /* Unterminated */;
- error(ts.Diagnostics.Unterminated_regular_expression_literal);
- break;
- }
- var ch = text.charCodeAt(p);
- if (isLineBreak(ch)) {
- 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 /* 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 /* openBracket */) {
- inCharacterClass = true;
- }
- else if (ch === 92 /* backslash */) {
- inEscape = true;
- }
- else if (ch === 93 /* closeBracket */) {
- inCharacterClass = false;
- }
- p++;
- }
- while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
- p++;
- }
- pos = p;
- tokenValue = text.substring(tokenPos, pos);
- token = 13 /* RegularExpressionLiteral */;
- }
- return token;
- }
- function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
- var type = getDirectiveFromComment(text, commentDirectiveRegEx);
- if (type === undefined) {
- return commentDirectives;
- }
- return ts.append(commentDirectives, {
- range: { pos: lineStart, end: pos },
- type: type,
- });
- }
- function getDirectiveFromComment(text, commentDirectiveRegEx) {
- var match = commentDirectiveRegEx.exec(text);
- if (!match) {
- return undefined;
- }
- switch (match[1]) {
- case "ts-expect-error":
- return 0 /* ExpectError */;
- case "ts-ignore":
- return 1 /* Ignore */;
- }
- return undefined;
- }
- /**
- * Unconditionally back up and scan a template expression portion.
- */
- function reScanTemplateToken(isTaggedTemplate) {
- ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
- pos = tokenPos;
- return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
- }
- function reScanTemplateHeadOrNoSubstitutionTemplate() {
- pos = tokenPos;
- return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
- }
- function reScanJsxToken() {
- pos = tokenPos = startPos;
- return token = scanJsxToken();
- }
- function reScanLessThanToken() {
- if (token === 47 /* LessThanLessThanToken */) {
- pos = tokenPos + 1;
- return token = 29 /* LessThanToken */;
- }
- return token;
- }
- function reScanQuestionToken() {
- ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
- pos = tokenPos + 1;
- return token = 57 /* QuestionToken */;
- }
- function scanJsxToken() {
- startPos = tokenPos = pos;
- if (pos >= end) {
- return token = 1 /* EndOfFileToken */;
- }
- var char = text.charCodeAt(pos);
- if (char === 60 /* lessThan */) {
- if (text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- return token = 30 /* LessThanSlashToken */;
- }
- pos++;
- return token = 29 /* LessThanToken */;
- }
- if (char === 123 /* openBrace */) {
- pos++;
- return token = 18 /* OpenBraceToken */;
- }
- // First non-whitespace character on this line.
- var firstNonWhitespace = 0;
- var lastNonWhitespace = -1;
- // These initial values are special because the first line is:
- // firstNonWhitespace = 0 to indicate that we want leading whitespace,
- while (pos < end) {
- // We want to keep track of the last non-whitespace (but including
- // newlines character for hitting the end of the JSX Text region)
- if (!isWhiteSpaceSingleLine(char)) {
- lastNonWhitespace = pos;
- }
- char = text.charCodeAt(pos);
- if (char === 123 /* openBrace */) {
- break;
- }
- if (char === 60 /* lessThan */) {
- if (isConflictMarkerTrivia(text, pos)) {
- pos = scanConflictMarkerTrivia(text, pos, error);
- return token = 7 /* ConflictMarkerTrivia */;
- }
- break;
- }
- if (char === 62 /* greaterThan */) {
- error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
- }
- if (char === 125 /* closeBrace */) {
- error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
- }
- if (lastNonWhitespace > 0)
- lastNonWhitespace++;
- // 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;
- }
- else if (!isWhiteSpaceLike(char)) {
- firstNonWhitespace = pos;
- }
- pos++;
- }
- var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
- tokenValue = text.substring(startPos, endPosition);
- return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
- }
- // Scans a JSX identifier; these differ from normal identifiers in that
- // they allow dashes
- function scanJsxIdentifier() {
- if (tokenIsIdentifierOrKeyword(token)) {
- // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
- // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
- // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
- while (pos < end) {
- var ch = text.charCodeAt(pos);
- if (ch === 45 /* minus */) {
- tokenValue += "-";
- pos++;
- continue;
- }
- var oldPos = pos;
- tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
- if (pos === oldPos) {
- break;
- }
- }
- }
- return token;
- }
- function scanJsxAttributeValue() {
- startPos = pos;
- switch (text.charCodeAt(pos)) {
- case 34 /* doubleQuote */:
- case 39 /* singleQuote */:
- tokenValue = scanString(/*jsxAttributeString*/ true);
- return token = 10 /* StringLiteral */;
- default:
- // If this scans anything other than `{`, it's a parse error.
- return scan();
- }
- }
- function reScanJsxAttributeValue() {
- pos = tokenPos = startPos;
- return scanJsxAttributeValue();
- }
- function scanJsDocToken() {
- startPos = tokenPos = pos;
- tokenFlags = 0 /* None */;
- if (pos >= end) {
- return token = 1 /* EndOfFileToken */;
- }
- var ch = codePointAt(text, pos);
- pos += charSize(ch);
- switch (ch) {
- case 9 /* tab */:
- case 11 /* verticalTab */:
- case 12 /* formFeed */:
- case 32 /* space */:
- while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
- pos++;
- }
- return token = 5 /* WhitespaceTrivia */;
- case 64 /* at */:
- return token = 59 /* AtToken */;
- case 10 /* lineFeed */:
- case 13 /* carriageReturn */:
- tokenFlags |= 1 /* PrecedingLineBreak */;
- return token = 4 /* NewLineTrivia */;
- case 42 /* asterisk */:
- return token = 41 /* AsteriskToken */;
- case 123 /* openBrace */:
- return token = 18 /* OpenBraceToken */;
- case 125 /* closeBrace */:
- return token = 19 /* CloseBraceToken */;
- case 91 /* openBracket */:
- return token = 22 /* OpenBracketToken */;
- case 93 /* closeBracket */:
- return token = 23 /* CloseBracketToken */;
- case 60 /* lessThan */:
- return token = 29 /* LessThanToken */;
- case 62 /* greaterThan */:
- return token = 31 /* GreaterThanToken */;
- case 61 /* equals */:
- return token = 62 /* EqualsToken */;
- case 44 /* comma */:
- return token = 27 /* CommaToken */;
- case 46 /* dot */:
- return token = 24 /* DotToken */;
- case 96 /* backtick */:
- return token = 61 /* BacktickToken */;
- case 92 /* backslash */:
- pos--;
- var extendedCookedChar = peekExtendedUnicodeEscape();
- if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
- pos += 3;
- tokenFlags |= 8 /* ExtendedUnicodeEscape */;
- tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
- return token = getIdentifierToken();
- }
- var cookedChar = peekUnicodeEscape();
- if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
- pos += 6;
- tokenFlags |= 1024 /* UnicodeEscape */;
- tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
- return token = getIdentifierToken();
- }
- pos++;
- return token = 0 /* Unknown */;
- }
- if (isIdentifierStart(ch, languageVersion)) {
- var char = ch;
- while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
- pos += charSize(char);
- tokenValue = text.substring(tokenPos, pos);
- if (char === 92 /* backslash */) {
- tokenValue += scanIdentifierParts();
- }
- return token = getIdentifierToken();
- }
- else {
- return token = 0 /* Unknown */;
- }
- }
- function speculationHelper(callback, isLookahead) {
- var savePos = pos;
- var saveStartPos = startPos;
- var saveTokenPos = tokenPos;
- var saveToken = token;
- 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;
- tokenPos = saveTokenPos;
- token = saveToken;
- tokenValue = saveTokenValue;
- tokenFlags = saveTokenFlags;
- }
- return result;
- }
- function scanRange(start, length, callback) {
- var saveEnd = end;
- var savePos = pos;
- var saveStartPos = startPos;
- var saveTokenPos = tokenPos;
- var saveToken = token;
- var saveTokenValue = tokenValue;
- var saveTokenFlags = tokenFlags;
- var saveErrorExpectations = commentDirectives;
- setText(text, start, length);
- var result = callback();
- end = saveEnd;
- pos = savePos;
- startPos = saveStartPos;
- tokenPos = saveTokenPos;
- token = saveToken;
- tokenValue = saveTokenValue;
- tokenFlags = saveTokenFlags;
- commentDirectives = saveErrorExpectations;
- return result;
- }
- function lookAhead(callback) {
- return speculationHelper(callback, /*isLookahead*/ true);
- }
- function tryScan(callback) {
- return speculationHelper(callback, /*isLookahead*/ false);
- }
- function getText() {
- return text;
- }
- function clearCommentDirectives() {
- commentDirectives = undefined;
- }
- function setText(newText, start, length) {
- text = newText || "";
- end = length === undefined ? text.length : start + length;
- setTextPos(start || 0);
- }
- function setOnError(errorCallback) {
- onError = errorCallback;
- }
- function setScriptTarget(scriptTarget) {
- languageVersion = scriptTarget;
- }
- function setLanguageVariant(variant) {
- languageVariant = variant;
- }
- function setTextPos(textPos) {
- ts.Debug.assert(textPos >= 0);
- pos = textPos;
- startPos = textPos;
- tokenPos = textPos;
- token = 0 /* Unknown */;
- tokenValue = undefined;
- tokenFlags = 0 /* None */;
- }
- function setInJSDocType(inType) {
- inJSDocType += inType ? 1 : -1;
- }
- }
- ts.createScanner = createScanner;
- /* @internal */
- var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
- // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
- var size = str.length;
- // Account for out-of-bounds indices:
- if (i < 0 || i >= size) {
- return undefined; // String.codePointAt returns `undefined` for OOB indexes
- }
- // Get the first code unit
- var first = str.charCodeAt(i);
- // check if itâs the start of a surrogate pair
- if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
- var second = str.charCodeAt(i + 1);
- if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
- // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
- return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
- }
- }
- return first;
- };
- /* @internal */
- function charSize(ch) {
- if (ch >= 0x10000) {
- return 2;
- }
- return 1;
- }
- // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
- function utf16EncodeAsStringFallback(codePoint) {
- ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
- if (codePoint <= 65535) {
- return String.fromCharCode(codePoint);
- }
- var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
- var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
- return String.fromCharCode(codeUnit1, codeUnit2);
- }
- var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
- /* @internal */
- function utf16EncodeAsString(codePoint) {
- return utf16EncodeAsStringWorker(codePoint);
- }
- ts.utf16EncodeAsString = utf16EncodeAsString;
-})(ts || (ts = {}));
-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;
- function sortAndDeduplicateDiagnostics(diagnostics) {
- return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
- }
- ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
- function getDefaultLibFileName(options) {
- switch (options.target) {
- case 99 /* ESNext */:
- return "lib.esnext.full.d.ts";
- case 7 /* ES2020 */:
- return "lib.es2020.full.d.ts";
- case 6 /* ES2019 */:
- return "lib.es2019.full.d.ts";
- case 5 /* ES2018 */:
- return "lib.es2018.full.d.ts";
- case 4 /* ES2017 */:
- return "lib.es2017.full.d.ts";
- case 3 /* ES2016 */:
- return "lib.es2016.full.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";
- }
- }
- ts.getDefaultLibFileName = getDefaultLibFileName;
- function textSpanEnd(span) {
- return span.start + span.length;
- }
- ts.textSpanEnd = textSpanEnd;
- function textSpanIsEmpty(span) {
- return span.length === 0;
- }
- ts.textSpanIsEmpty = textSpanIsEmpty;
- function textSpanContainsPosition(span, position) {
- return position >= span.start && position < textSpanEnd(span);
- }
- ts.textSpanContainsPosition = textSpanContainsPosition;
- /* @internal */
- function textRangeContainsPositionInclusive(span, position) {
- return position >= span.pos && position <= span.end;
- }
- ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
- // Returns true if 'span' contains 'other'.
- function textSpanContainsTextSpan(span, other) {
- return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
- }
- ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
- function textSpanOverlapsWith(span, other) {
- return textSpanOverlap(span, other) !== undefined;
- }
- ts.textSpanOverlapsWith = textSpanOverlapsWith;
- function textSpanOverlap(span1, span2) {
- var overlap = textSpanIntersection(span1, span2);
- return overlap && overlap.length === 0 ? undefined : overlap;
- }
- ts.textSpanOverlap = textSpanOverlap;
- function textSpanIntersectsWithTextSpan(span, other) {
- return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
- }
- ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
- function textSpanIntersectsWith(span, start, length) {
- return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
- }
- ts.textSpanIntersectsWith = textSpanIntersectsWith;
- function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
- var end1 = start1 + length1;
- var end2 = start2 + length2;
- return start2 <= end1 && end2 >= start1;
- }
- ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
- function textSpanIntersectsWithPosition(span, position) {
- return position <= textSpanEnd(span) && position >= span.start;
- }
- ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
- function textSpanIntersection(span1, span2) {
- var start = Math.max(span1.start, span2.start);
- var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- return start <= end ? createTextSpanFromBounds(start, end) : undefined;
- }
- ts.textSpanIntersection = textSpanIntersection;
- function createTextSpan(start, length) {
- if (start < 0) {
- throw new Error("start < 0");
- }
- if (length < 0) {
- throw new Error("length < 0");
- }
- return { start: start, length: length };
- }
- ts.createTextSpan = createTextSpan;
- function createTextSpanFromBounds(start, end) {
- return createTextSpan(start, end - start);
- }
- ts.createTextSpanFromBounds = createTextSpanFromBounds;
- function textChangeRangeNewSpan(range) {
- return createTextSpan(range.span.start, range.newLength);
- }
- ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
- function textChangeRangeIsUnchanged(range) {
- return textSpanIsEmpty(range.span) && range.newLength === 0;
- }
- ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
- function createTextChangeRange(span, newLength) {
- if (newLength < 0) {
- throw new Error("newLength < 0");
- }
- return { span: span, newLength: newLength };
- }
- ts.createTextChangeRange = createTextChangeRange;
- ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
- /**
- * 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;
- }
- 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;
- var oldStart2 = nextChange.span.start;
- var oldEnd2 = textSpanEnd(nextChange.span);
- var newEnd2 = oldStart2 + nextChange.newLength;
- oldStartN = Math.min(oldStart1, oldStart2);
- oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
- newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
- }
- return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
- }
- ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
- function getTypeParameterOwner(d) {
- if (d && d.kind === 155 /* TypeParameter */) {
- for (var current = d; current; current = current.parent) {
- if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
- return current;
- }
- }
- }
- }
- ts.getTypeParameterOwner = getTypeParameterOwner;
- function isParameterPropertyDeclaration(node, parent) {
- return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
- }
- ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
- function isEmptyBindingPattern(node) {
- if (isBindingPattern(node)) {
- return ts.every(node.elements, isEmptyBindingElement);
- }
- return false;
- }
- ts.isEmptyBindingPattern = isEmptyBindingPattern;
- function isEmptyBindingElement(node) {
- if (isOmittedExpression(node)) {
- return true;
- }
- return isEmptyBindingPattern(node.name);
- }
- ts.isEmptyBindingElement = isEmptyBindingElement;
- function walkUpBindingElementsAndPatterns(binding) {
- var node = binding.parent;
- while (isBindingElement(node.parent)) {
- node = node.parent.parent;
- }
- return node.parent;
- }
- ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
- function getCombinedFlags(node, getFlags) {
- if (isBindingElement(node)) {
- node = walkUpBindingElementsAndPatterns(node);
- }
- var flags = getFlags(node);
- if (node.kind === 242 /* VariableDeclaration */) {
- node = node.parent;
- }
- if (node && node.kind === 243 /* VariableDeclarationList */) {
- flags |= getFlags(node);
- node = node.parent;
- }
- if (node && node.kind === 225 /* VariableStatement */) {
- flags |= getFlags(node);
- }
- return flags;
- }
- function getCombinedModifierFlags(node) {
- return getCombinedFlags(node, ts.getModifierFlags);
- }
- 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) {
- return getCombinedFlags(node, function (n) { return n.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) {
- if (errors) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
- }
- return;
- }
- 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, /*territory*/ undefined, errors);
- }
- // Set the UI locale for string collation
- ts.setUILocale(locale);
- function trySetLanguageAndTerritory(language, territory, errors) {
- var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
- var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
- var filePath = ts.combinePaths(containingDirectoryPath, language);
- if (territory) {
- filePath = filePath + "-" + territory;
- }
- filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
- if (!sys.fileExists(filePath)) {
- return false;
- }
- // TODO: Add codePage support for readFile?
- var fileContents = "";
- try {
- fileContents = sys.readFile(filePath);
- }
- catch (e) {
- if (errors) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
- }
- return false;
- }
- try {
- // this is a global mutation (or live binding update)!
- ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
- }
- catch (_a) {
- if (errors) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
- }
- return false;
- }
- return true;
- }
- }
- ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
- function getOriginalNode(node, nodeTest) {
- if (node) {
- while (node.original !== undefined) {
- node = node.original;
- }
- }
- 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 /* Synthesized */) === 0;
- }
- ts.isParseTreeNode = isParseTreeNode;
- function getParseTreeNode(node, nodeTest) {
- if (node === undefined || isParseTreeNode(node)) {
- return node;
- }
- node = getOriginalNode(node);
- if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
- return node;
- }
- return undefined;
- }
- ts.getParseTreeNode = getParseTreeNode;
- /** 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);
- }
- ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
- /**
- * 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;
- }
- ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
- function idText(identifierOrPrivateName) {
- return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
- }
- ts.idText = idText;
- function symbolName(symbol) {
- if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
- return idText(symbol.valueDeclaration.name);
- }
- return unescapeLeadingUnderscores(symbol.escapedName);
- }
- ts.symbolName = symbolName;
- /**
- * 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 (isDeclaration(hostNode)) {
- return getDeclarationIdentifier(hostNode);
- }
- // Covers remaining cases (returning undefined if none match).
- switch (hostNode.kind) {
- case 225 /* VariableStatement */:
- if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
- return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
- }
- break;
- case 226 /* ExpressionStatement */:
- var expr = hostNode.expression;
- if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
- expr = expr.left;
- }
- switch (expr.kind) {
- case 194 /* PropertyAccessExpression */:
- return expr.name;
- case 195 /* ElementAccessExpression */:
- var arg = expr.argumentExpression;
- if (isIdentifier(arg)) {
- return arg;
- }
- }
- break;
- case 200 /* ParenthesizedExpression */: {
- return getDeclarationIdentifier(hostNode.expression);
- }
- case 238 /* LabeledStatement */: {
- if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
- return getDeclarationIdentifier(hostNode.statement);
- }
- break;
- }
- }
- }
- function getDeclarationIdentifier(node) {
- var name = getNameOfDeclaration(node);
- return name && isIdentifier(name) ? name : undefined;
- }
- /** @internal */
- function nodeHasName(statement, name) {
- if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
- return true;
- }
- if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
- return true;
- }
- return false;
- }
- ts.nodeHasName = nodeHasName;
- function getNameOfJSDocTypedef(declaration) {
- return declaration.name || nameForNamelessJSDocTypedef(declaration);
- }
- ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
- /** @internal */
- function isNamedDeclaration(node) {
- return !!node.name; // A 'name' property should always be a DeclarationName.
- }
- ts.isNamedDeclaration = isNamedDeclaration;
- /** @internal */
- function getNonAssignedNameOfDeclaration(declaration) {
- switch (declaration.kind) {
- case 75 /* Identifier */:
- return declaration;
- case 323 /* JSDocPropertyTag */:
- case 317 /* JSDocParameterTag */: {
- var name = declaration.name;
- if (name.kind === 153 /* QualifiedName */) {
- return name.right;
- }
- break;
- }
- case 196 /* CallExpression */:
- case 209 /* BinaryExpression */: {
- var expr_1 = declaration;
- switch (ts.getAssignmentDeclarationKind(expr_1)) {
- case 1 /* ExportsProperty */:
- case 4 /* ThisProperty */:
- case 5 /* Property */:
- case 3 /* PrototypeProperty */:
- return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
- case 7 /* ObjectDefinePropertyValue */:
- case 8 /* ObjectDefinePropertyExports */:
- case 9 /* ObjectDefinePrototypeProperty */:
- return expr_1.arguments[1];
- default:
- return undefined;
- }
- }
- case 322 /* JSDocTypedefTag */:
- return getNameOfJSDocTypedef(declaration);
- case 316 /* JSDocEnumTag */:
- return nameForNamelessJSDocTypedef(declaration);
- case 259 /* ExportAssignment */: {
- var expression = declaration.expression;
- return isIdentifier(expression) ? expression : undefined;
- }
- case 195 /* ElementAccessExpression */:
- var expr = declaration;
- if (ts.isBindableStaticElementAccessExpression(expr)) {
- return expr.argumentExpression;
- }
- }
- return declaration.name;
- }
- ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
- function getNameOfDeclaration(declaration) {
- if (declaration === undefined)
- return undefined;
- return getNonAssignedNameOfDeclaration(declaration) ||
- (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
- }
- ts.getNameOfDeclaration = getNameOfDeclaration;
- function getAssignedName(node) {
- if (!node.parent) {
- return undefined;
- }
- else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
- return node.parent.name;
- }
- else if (isBinaryExpression(node.parent) && node === node.parent.right) {
- if (isIdentifier(node.parent.left)) {
- return node.parent.left;
- }
- else if (ts.isAccessExpression(node.parent.left)) {
- return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
- }
- }
- else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
- return node.parent.name;
- }
- }
- /**
- * Gets the JSDoc parameter tags for the node if present.
- *
- * @remarks Returns any JSDoc param tag whose name 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.
- *
- * For binding patterns, parameter tags are matched by position.
- */
- function getJSDocParameterTags(param) {
- if (param.name) {
- if (isIdentifier(param.name)) {
- var name_1 = param.name.escapedText;
- return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
- }
- else {
- var i = param.parent.parameters.indexOf(param);
- ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
- var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
- if (i < paramTags.length) {
- return [paramTags[i]];
- }
- }
- }
- // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
- return ts.emptyArray;
- }
- ts.getJSDocParameterTags = getJSDocParameterTags;
- /**
- * Gets the JSDoc type parameter tags for the node if present.
- *
- * @remarks Returns any JSDoc template tag whose names match the provided
- * parameter, whether a template tag on a containing function
- * expression, or a template 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 template
- * tag on the containing function expression would be first.
- */
- function getJSDocTypeParameterTags(param) {
- var name = param.name.escapedText;
- return getJSDocTags(param.parent).filter(function (tag) {
- return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
- });
- }
- ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
- /**
- * 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, isJSDocParameterTag);
- }
- ts.hasJSDocParameterTags = hasJSDocParameterTags;
- /** Gets the JSDoc augments tag for the node if present */
- function getJSDocAugmentsTag(node) {
- return getFirstJSDocTag(node, isJSDocAugmentsTag);
- }
- ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
- /** Gets the JSDoc implements tags for the node if present */
- function getJSDocImplementsTags(node) {
- return getAllJSDocTags(node, isJSDocImplementsTag);
- }
- ts.getJSDocImplementsTags = getJSDocImplementsTags;
- /** Gets the JSDoc class tag for the node if present */
- function getJSDocClassTag(node) {
- return getFirstJSDocTag(node, isJSDocClassTag);
- }
- ts.getJSDocClassTag = getJSDocClassTag;
- /** Gets the JSDoc public tag for the node if present */
- function getJSDocPublicTag(node) {
- return getFirstJSDocTag(node, isJSDocPublicTag);
- }
- ts.getJSDocPublicTag = getJSDocPublicTag;
- /** Gets the JSDoc private tag for the node if present */
- function getJSDocPrivateTag(node) {
- return getFirstJSDocTag(node, isJSDocPrivateTag);
- }
- ts.getJSDocPrivateTag = getJSDocPrivateTag;
- /** Gets the JSDoc protected tag for the node if present */
- function getJSDocProtectedTag(node) {
- return getFirstJSDocTag(node, isJSDocProtectedTag);
- }
- ts.getJSDocProtectedTag = getJSDocProtectedTag;
- /** Gets the JSDoc protected tag for the node if present */
- function getJSDocReadonlyTag(node) {
- return getFirstJSDocTag(node, isJSDocReadonlyTag);
- }
- ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
- /** Gets the JSDoc enum tag for the node if present */
- function getJSDocEnumTag(node) {
- return getFirstJSDocTag(node, isJSDocEnumTag);
- }
- ts.getJSDocEnumTag = getJSDocEnumTag;
- /** Gets the JSDoc this tag for the node if present */
- function getJSDocThisTag(node) {
- return getFirstJSDocTag(node, isJSDocThisTag);
- }
- ts.getJSDocThisTag = getJSDocThisTag;
- /** Gets the JSDoc return tag for the node if present */
- function getJSDocReturnTag(node) {
- return getFirstJSDocTag(node, isJSDocReturnTag);
- }
- ts.getJSDocReturnTag = getJSDocReturnTag;
- /** Gets the JSDoc template tag for the node if present */
- function getJSDocTemplateTag(node) {
- return getFirstJSDocTag(node, 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, isJSDocTypeTag);
- if (tag && tag.typeExpression && tag.typeExpression.type) {
- return tag;
- }
- 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, isJSDocTypeTag);
- if (!tag && isParameter(node)) {
- tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
- }
- return tag && tag.typeExpression && tag.typeExpression.type;
- }
- ts.getJSDocType = getJSDocType;
- /**
- * Gets the return type node for the node if provided via JSDoc return tag or type tag.
- *
- * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
- * gets the type from inside the braces, after the fat arrow, etc.
- */
- function getJSDocReturnType(node) {
- var returnTag = getJSDocReturnTag(node);
- if (returnTag && returnTag.typeExpression) {
- return returnTag.typeExpression.type;
- }
- var typeTag = getJSDocTypeTag(node);
- if (typeTag && typeTag.typeExpression) {
- var type = typeTag.typeExpression.type;
- if (isTypeLiteralNode(type)) {
- var sig = ts.find(type.members, isCallSignatureDeclaration);
- return sig && sig.type;
- }
- if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
- return type.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]);
- node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
- }
- 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 that match a specified predicate */
- function getAllJSDocTags(node, predicate) {
- return getJSDocTags(node).filter(predicate);
- }
- ts.getAllJSDocTags = getAllJSDocTags;
- /** Gets all JSDoc tags of a specified kind */
- function getAllJSDocTagsOfKind(node, kind) {
- return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
- }
- ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
- /**
- * 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 (isJSDocSignature(node)) {
- return ts.emptyArray;
- }
- if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
- return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
- }
- if (node.typeParameters) {
- return node.typeParameters;
- }
- if (ts.isInJSFile(node)) {
- var decls = ts.getJSDocTypeParameterDeclarations(node);
- if (decls.length) {
- return decls;
- }
- var typeTag = getJSDocType(node);
- if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
- return typeTag.typeParameters;
- }
- }
- return ts.emptyArray;
- }
- ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
- function getEffectiveConstraintOfTypeParameter(node) {
- return node.constraint ? node.constraint :
- isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
- undefined;
- }
- ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
- // #region
- // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
- // Literals
- function isNumericLiteral(node) {
- return node.kind === 8 /* NumericLiteral */;
- }
- ts.isNumericLiteral = isNumericLiteral;
- function isBigIntLiteral(node) {
- return node.kind === 9 /* BigIntLiteral */;
- }
- ts.isBigIntLiteral = isBigIntLiteral;
- function isStringLiteral(node) {
- return node.kind === 10 /* StringLiteral */;
- }
- ts.isStringLiteral = isStringLiteral;
- function isJsxText(node) {
- return node.kind === 11 /* JsxText */;
- }
- ts.isJsxText = isJsxText;
- function isRegularExpressionLiteral(node) {
- return node.kind === 13 /* RegularExpressionLiteral */;
- }
- ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
- function isNoSubstitutionTemplateLiteral(node) {
- return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
- }
- ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
- // Pseudo-literals
- function isTemplateHead(node) {
- return node.kind === 15 /* TemplateHead */;
- }
- ts.isTemplateHead = isTemplateHead;
- function isTemplateMiddle(node) {
- return node.kind === 16 /* TemplateMiddle */;
- }
- ts.isTemplateMiddle = isTemplateMiddle;
- function isTemplateTail(node) {
- return node.kind === 17 /* TemplateTail */;
- }
- ts.isTemplateTail = isTemplateTail;
- function isIdentifier(node) {
- return node.kind === 75 /* Identifier */;
- }
- ts.isIdentifier = isIdentifier;
- // Names
- function isQualifiedName(node) {
- return node.kind === 153 /* QualifiedName */;
- }
- ts.isQualifiedName = isQualifiedName;
- function isComputedPropertyName(node) {
- return node.kind === 154 /* ComputedPropertyName */;
- }
- ts.isComputedPropertyName = isComputedPropertyName;
- function isPrivateIdentifier(node) {
- return node.kind === 76 /* PrivateIdentifier */;
- }
- ts.isPrivateIdentifier = isPrivateIdentifier;
- function isIdentifierOrPrivateIdentifier(node) {
- return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
- }
- ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
- // Signature elements
- function isTypeParameterDeclaration(node) {
- return node.kind === 155 /* TypeParameter */;
- }
- ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
- function isParameter(node) {
- return node.kind === 156 /* Parameter */;
- }
- ts.isParameter = isParameter;
- function isDecorator(node) {
- return node.kind === 157 /* Decorator */;
- }
- ts.isDecorator = isDecorator;
- // TypeMember
- function isPropertySignature(node) {
- return node.kind === 158 /* PropertySignature */;
- }
- ts.isPropertySignature = isPropertySignature;
- function isPropertyDeclaration(node) {
- return node.kind === 159 /* PropertyDeclaration */;
- }
- ts.isPropertyDeclaration = isPropertyDeclaration;
- function isMethodSignature(node) {
- return node.kind === 160 /* MethodSignature */;
- }
- ts.isMethodSignature = isMethodSignature;
- function isMethodDeclaration(node) {
- return node.kind === 161 /* MethodDeclaration */;
- }
- ts.isMethodDeclaration = isMethodDeclaration;
- function isConstructorDeclaration(node) {
- return node.kind === 162 /* Constructor */;
- }
- ts.isConstructorDeclaration = isConstructorDeclaration;
- function isGetAccessorDeclaration(node) {
- return node.kind === 163 /* GetAccessor */;
- }
- ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
- function isSetAccessorDeclaration(node) {
- return node.kind === 164 /* SetAccessor */;
- }
- ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
- function isCallSignatureDeclaration(node) {
- return node.kind === 165 /* CallSignature */;
- }
- ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
- function isConstructSignatureDeclaration(node) {
- return node.kind === 166 /* ConstructSignature */;
- }
- ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
- function isIndexSignatureDeclaration(node) {
- return node.kind === 167 /* IndexSignature */;
- }
- ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
- /* @internal */
- function isGetOrSetAccessorDeclaration(node) {
- return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
- }
- ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
- // Type
- function isTypePredicateNode(node) {
- return node.kind === 168 /* TypePredicate */;
- }
- ts.isTypePredicateNode = isTypePredicateNode;
- function isTypeReferenceNode(node) {
- return node.kind === 169 /* TypeReference */;
- }
- ts.isTypeReferenceNode = isTypeReferenceNode;
- function isFunctionTypeNode(node) {
- return node.kind === 170 /* FunctionType */;
- }
- ts.isFunctionTypeNode = isFunctionTypeNode;
- function isConstructorTypeNode(node) {
- return node.kind === 171 /* ConstructorType */;
- }
- ts.isConstructorTypeNode = isConstructorTypeNode;
- function isTypeQueryNode(node) {
- return node.kind === 172 /* TypeQuery */;
- }
- ts.isTypeQueryNode = isTypeQueryNode;
- function isTypeLiteralNode(node) {
- return node.kind === 173 /* TypeLiteral */;
- }
- ts.isTypeLiteralNode = isTypeLiteralNode;
- function isArrayTypeNode(node) {
- return node.kind === 174 /* ArrayType */;
- }
- ts.isArrayTypeNode = isArrayTypeNode;
- function isTupleTypeNode(node) {
- return node.kind === 175 /* TupleType */;
- }
- ts.isTupleTypeNode = isTupleTypeNode;
- function isUnionTypeNode(node) {
- return node.kind === 178 /* UnionType */;
- }
- ts.isUnionTypeNode = isUnionTypeNode;
- function isIntersectionTypeNode(node) {
- return node.kind === 179 /* IntersectionType */;
- }
- ts.isIntersectionTypeNode = isIntersectionTypeNode;
- function isConditionalTypeNode(node) {
- return node.kind === 180 /* ConditionalType */;
- }
- ts.isConditionalTypeNode = isConditionalTypeNode;
- function isInferTypeNode(node) {
- return node.kind === 181 /* InferType */;
- }
- ts.isInferTypeNode = isInferTypeNode;
- function isParenthesizedTypeNode(node) {
- return node.kind === 182 /* ParenthesizedType */;
- }
- ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
- function isThisTypeNode(node) {
- return node.kind === 183 /* ThisType */;
- }
- ts.isThisTypeNode = isThisTypeNode;
- function isTypeOperatorNode(node) {
- return node.kind === 184 /* TypeOperator */;
- }
- ts.isTypeOperatorNode = isTypeOperatorNode;
- function isIndexedAccessTypeNode(node) {
- return node.kind === 185 /* IndexedAccessType */;
- }
- ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
- function isMappedTypeNode(node) {
- return node.kind === 186 /* MappedType */;
- }
- ts.isMappedTypeNode = isMappedTypeNode;
- function isLiteralTypeNode(node) {
- return node.kind === 187 /* LiteralType */;
- }
- ts.isLiteralTypeNode = isLiteralTypeNode;
- function isImportTypeNode(node) {
- return node.kind === 188 /* ImportType */;
- }
- ts.isImportTypeNode = isImportTypeNode;
- // Binding patterns
- function isObjectBindingPattern(node) {
- return node.kind === 189 /* ObjectBindingPattern */;
- }
- ts.isObjectBindingPattern = isObjectBindingPattern;
- function isArrayBindingPattern(node) {
- return node.kind === 190 /* ArrayBindingPattern */;
- }
- ts.isArrayBindingPattern = isArrayBindingPattern;
- function isBindingElement(node) {
- return node.kind === 191 /* BindingElement */;
- }
- ts.isBindingElement = isBindingElement;
- // Expression
- function isArrayLiteralExpression(node) {
- return node.kind === 192 /* ArrayLiteralExpression */;
- }
- ts.isArrayLiteralExpression = isArrayLiteralExpression;
- function isObjectLiteralExpression(node) {
- return node.kind === 193 /* ObjectLiteralExpression */;
- }
- ts.isObjectLiteralExpression = isObjectLiteralExpression;
- function isPropertyAccessExpression(node) {
- return node.kind === 194 /* PropertyAccessExpression */;
- }
- ts.isPropertyAccessExpression = isPropertyAccessExpression;
- function isPropertyAccessChain(node) {
- return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
- }
- ts.isPropertyAccessChain = isPropertyAccessChain;
- function isElementAccessExpression(node) {
- return node.kind === 195 /* ElementAccessExpression */;
- }
- ts.isElementAccessExpression = isElementAccessExpression;
- function isElementAccessChain(node) {
- return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
- }
- ts.isElementAccessChain = isElementAccessChain;
- function isCallExpression(node) {
- return node.kind === 196 /* CallExpression */;
- }
- ts.isCallExpression = isCallExpression;
- function isCallChain(node) {
- return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
- }
- ts.isCallChain = isCallChain;
- function isOptionalChain(node) {
- var kind = node.kind;
- return !!(node.flags & 32 /* OptionalChain */) &&
- (kind === 194 /* PropertyAccessExpression */
- || kind === 195 /* ElementAccessExpression */
- || kind === 196 /* CallExpression */
- || kind === 218 /* NonNullExpression */);
- }
- ts.isOptionalChain = isOptionalChain;
- /* @internal */
- function isOptionalChainRoot(node) {
- return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
- }
- ts.isOptionalChainRoot = isOptionalChainRoot;
- /**
- * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
- */
- /* @internal */
- function isExpressionOfOptionalChainRoot(node) {
- return isOptionalChainRoot(node.parent) && node.parent.expression === node;
- }
- ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
- /**
- * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
- *
- * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
- * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
- * 3. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain)
- * 4. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is
- * the end of the chain starting at `c?.`)
- * 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is
- * the end of the chain starting at `a?.`)
- */
- /* @internal */
- function isOutermostOptionalChain(node) {
- return !isOptionalChain(node.parent) // cases 1, 2, and 3
- || isOptionalChainRoot(node.parent) // case 4
- || node !== node.parent.expression; // case 5
- }
- ts.isOutermostOptionalChain = isOutermostOptionalChain;
- function isNullishCoalesce(node) {
- return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
- }
- ts.isNullishCoalesce = isNullishCoalesce;
- function isNewExpression(node) {
- return node.kind === 197 /* NewExpression */;
- }
- ts.isNewExpression = isNewExpression;
- function isTaggedTemplateExpression(node) {
- return node.kind === 198 /* TaggedTemplateExpression */;
- }
- ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
- function isTypeAssertion(node) {
- return node.kind === 199 /* TypeAssertionExpression */;
- }
- ts.isTypeAssertion = isTypeAssertion;
- function isConstTypeReference(node) {
- return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
- node.typeName.escapedText === "const" && !node.typeArguments;
- }
- ts.isConstTypeReference = isConstTypeReference;
- function isParenthesizedExpression(node) {
- return node.kind === 200 /* ParenthesizedExpression */;
- }
- ts.isParenthesizedExpression = isParenthesizedExpression;
- function skipPartiallyEmittedExpressions(node) {
- return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
- }
- ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
- function isFunctionExpression(node) {
- return node.kind === 201 /* FunctionExpression */;
- }
- ts.isFunctionExpression = isFunctionExpression;
- function isArrowFunction(node) {
- return node.kind === 202 /* ArrowFunction */;
- }
- ts.isArrowFunction = isArrowFunction;
- function isDeleteExpression(node) {
- return node.kind === 203 /* DeleteExpression */;
- }
- ts.isDeleteExpression = isDeleteExpression;
- function isTypeOfExpression(node) {
- return node.kind === 204 /* TypeOfExpression */;
- }
- ts.isTypeOfExpression = isTypeOfExpression;
- function isVoidExpression(node) {
- return node.kind === 205 /* VoidExpression */;
- }
- ts.isVoidExpression = isVoidExpression;
- function isAwaitExpression(node) {
- return node.kind === 206 /* AwaitExpression */;
- }
- ts.isAwaitExpression = isAwaitExpression;
- function isPrefixUnaryExpression(node) {
- return node.kind === 207 /* PrefixUnaryExpression */;
- }
- ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
- function isPostfixUnaryExpression(node) {
- return node.kind === 208 /* PostfixUnaryExpression */;
- }
- ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
- function isBinaryExpression(node) {
- return node.kind === 209 /* BinaryExpression */;
- }
- ts.isBinaryExpression = isBinaryExpression;
- function isConditionalExpression(node) {
- return node.kind === 210 /* ConditionalExpression */;
- }
- ts.isConditionalExpression = isConditionalExpression;
- function isTemplateExpression(node) {
- return node.kind === 211 /* TemplateExpression */;
- }
- ts.isTemplateExpression = isTemplateExpression;
- function isYieldExpression(node) {
- return node.kind === 212 /* YieldExpression */;
- }
- ts.isYieldExpression = isYieldExpression;
- function isSpreadElement(node) {
- return node.kind === 213 /* SpreadElement */;
- }
- ts.isSpreadElement = isSpreadElement;
- function isClassExpression(node) {
- return node.kind === 214 /* ClassExpression */;
- }
- ts.isClassExpression = isClassExpression;
- function isOmittedExpression(node) {
- return node.kind === 215 /* OmittedExpression */;
- }
- ts.isOmittedExpression = isOmittedExpression;
- function isExpressionWithTypeArguments(node) {
- return node.kind === 216 /* ExpressionWithTypeArguments */;
- }
- ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
- function isAsExpression(node) {
- return node.kind === 217 /* AsExpression */;
- }
- ts.isAsExpression = isAsExpression;
- function isNonNullExpression(node) {
- return node.kind === 218 /* NonNullExpression */;
- }
- ts.isNonNullExpression = isNonNullExpression;
- function isNonNullChain(node) {
- return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
- }
- ts.isNonNullChain = isNonNullChain;
- function isMetaProperty(node) {
- return node.kind === 219 /* MetaProperty */;
- }
- ts.isMetaProperty = isMetaProperty;
- // Misc
- function isTemplateSpan(node) {
- return node.kind === 221 /* TemplateSpan */;
- }
- ts.isTemplateSpan = isTemplateSpan;
- function isSemicolonClassElement(node) {
- return node.kind === 222 /* SemicolonClassElement */;
- }
- ts.isSemicolonClassElement = isSemicolonClassElement;
- // Block
- function isBlock(node) {
- return node.kind === 223 /* Block */;
- }
- ts.isBlock = isBlock;
- function isVariableStatement(node) {
- return node.kind === 225 /* VariableStatement */;
- }
- ts.isVariableStatement = isVariableStatement;
- function isEmptyStatement(node) {
- return node.kind === 224 /* EmptyStatement */;
- }
- ts.isEmptyStatement = isEmptyStatement;
- function isExpressionStatement(node) {
- return node.kind === 226 /* ExpressionStatement */;
- }
- ts.isExpressionStatement = isExpressionStatement;
- function isIfStatement(node) {
- return node.kind === 227 /* IfStatement */;
- }
- ts.isIfStatement = isIfStatement;
- function isDoStatement(node) {
- return node.kind === 228 /* DoStatement */;
- }
- ts.isDoStatement = isDoStatement;
- function isWhileStatement(node) {
- return node.kind === 229 /* WhileStatement */;
- }
- ts.isWhileStatement = isWhileStatement;
- function isForStatement(node) {
- return node.kind === 230 /* ForStatement */;
- }
- ts.isForStatement = isForStatement;
- function isForInStatement(node) {
- return node.kind === 231 /* ForInStatement */;
- }
- ts.isForInStatement = isForInStatement;
- function isForOfStatement(node) {
- return node.kind === 232 /* ForOfStatement */;
- }
- ts.isForOfStatement = isForOfStatement;
- function isContinueStatement(node) {
- return node.kind === 233 /* ContinueStatement */;
- }
- ts.isContinueStatement = isContinueStatement;
- function isBreakStatement(node) {
- return node.kind === 234 /* BreakStatement */;
- }
- ts.isBreakStatement = isBreakStatement;
- function isBreakOrContinueStatement(node) {
- return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
- }
- ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
- function isReturnStatement(node) {
- return node.kind === 235 /* ReturnStatement */;
- }
- ts.isReturnStatement = isReturnStatement;
- function isWithStatement(node) {
- return node.kind === 236 /* WithStatement */;
- }
- ts.isWithStatement = isWithStatement;
- function isSwitchStatement(node) {
- return node.kind === 237 /* SwitchStatement */;
- }
- ts.isSwitchStatement = isSwitchStatement;
- function isLabeledStatement(node) {
- return node.kind === 238 /* LabeledStatement */;
- }
- ts.isLabeledStatement = isLabeledStatement;
- function isThrowStatement(node) {
- return node.kind === 239 /* ThrowStatement */;
- }
- ts.isThrowStatement = isThrowStatement;
- function isTryStatement(node) {
- return node.kind === 240 /* TryStatement */;
- }
- ts.isTryStatement = isTryStatement;
- function isDebuggerStatement(node) {
- return node.kind === 241 /* DebuggerStatement */;
- }
- ts.isDebuggerStatement = isDebuggerStatement;
- function isVariableDeclaration(node) {
- return node.kind === 242 /* VariableDeclaration */;
- }
- ts.isVariableDeclaration = isVariableDeclaration;
- function isVariableDeclarationList(node) {
- return node.kind === 243 /* VariableDeclarationList */;
- }
- ts.isVariableDeclarationList = isVariableDeclarationList;
- function isFunctionDeclaration(node) {
- return node.kind === 244 /* FunctionDeclaration */;
- }
- ts.isFunctionDeclaration = isFunctionDeclaration;
- function isClassDeclaration(node) {
- return node.kind === 245 /* ClassDeclaration */;
- }
- ts.isClassDeclaration = isClassDeclaration;
- function isInterfaceDeclaration(node) {
- return node.kind === 246 /* InterfaceDeclaration */;
- }
- ts.isInterfaceDeclaration = isInterfaceDeclaration;
- function isTypeAliasDeclaration(node) {
- return node.kind === 247 /* TypeAliasDeclaration */;
- }
- ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
- function isEnumDeclaration(node) {
- return node.kind === 248 /* EnumDeclaration */;
- }
- ts.isEnumDeclaration = isEnumDeclaration;
- function isModuleDeclaration(node) {
- return node.kind === 249 /* ModuleDeclaration */;
- }
- ts.isModuleDeclaration = isModuleDeclaration;
- function isModuleBlock(node) {
- return node.kind === 250 /* ModuleBlock */;
- }
- ts.isModuleBlock = isModuleBlock;
- function isCaseBlock(node) {
- return node.kind === 251 /* CaseBlock */;
- }
- ts.isCaseBlock = isCaseBlock;
- function isNamespaceExportDeclaration(node) {
- return node.kind === 252 /* NamespaceExportDeclaration */;
- }
- ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
- function isImportEqualsDeclaration(node) {
- return node.kind === 253 /* ImportEqualsDeclaration */;
- }
- ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
- function isImportDeclaration(node) {
- return node.kind === 254 /* ImportDeclaration */;
- }
- ts.isImportDeclaration = isImportDeclaration;
- function isImportClause(node) {
- return node.kind === 255 /* ImportClause */;
- }
- ts.isImportClause = isImportClause;
- function isNamespaceImport(node) {
- return node.kind === 256 /* NamespaceImport */;
- }
- ts.isNamespaceImport = isNamespaceImport;
- function isNamespaceExport(node) {
- return node.kind === 262 /* NamespaceExport */;
- }
- ts.isNamespaceExport = isNamespaceExport;
- function isNamedExportBindings(node) {
- return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
- }
- ts.isNamedExportBindings = isNamedExportBindings;
- function isNamedImports(node) {
- return node.kind === 257 /* NamedImports */;
- }
- ts.isNamedImports = isNamedImports;
- function isImportSpecifier(node) {
- return node.kind === 258 /* ImportSpecifier */;
- }
- ts.isImportSpecifier = isImportSpecifier;
- function isExportAssignment(node) {
- return node.kind === 259 /* ExportAssignment */;
- }
- ts.isExportAssignment = isExportAssignment;
- function isExportDeclaration(node) {
- return node.kind === 260 /* ExportDeclaration */;
- }
- ts.isExportDeclaration = isExportDeclaration;
- function isNamedExports(node) {
- return node.kind === 261 /* NamedExports */;
- }
- ts.isNamedExports = isNamedExports;
- function isExportSpecifier(node) {
- return node.kind === 263 /* ExportSpecifier */;
- }
- ts.isExportSpecifier = isExportSpecifier;
- function isMissingDeclaration(node) {
- return node.kind === 264 /* MissingDeclaration */;
- }
- ts.isMissingDeclaration = isMissingDeclaration;
- // Module References
- function isExternalModuleReference(node) {
- return node.kind === 265 /* ExternalModuleReference */;
- }
- ts.isExternalModuleReference = isExternalModuleReference;
- // JSX
- function isJsxElement(node) {
- return node.kind === 266 /* JsxElement */;
- }
- ts.isJsxElement = isJsxElement;
- function isJsxSelfClosingElement(node) {
- return node.kind === 267 /* JsxSelfClosingElement */;
- }
- ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
- function isJsxOpeningElement(node) {
- return node.kind === 268 /* JsxOpeningElement */;
- }
- ts.isJsxOpeningElement = isJsxOpeningElement;
- function isJsxClosingElement(node) {
- return node.kind === 269 /* JsxClosingElement */;
- }
- ts.isJsxClosingElement = isJsxClosingElement;
- function isJsxFragment(node) {
- return node.kind === 270 /* JsxFragment */;
- }
- ts.isJsxFragment = isJsxFragment;
- function isJsxOpeningFragment(node) {
- return node.kind === 271 /* JsxOpeningFragment */;
- }
- ts.isJsxOpeningFragment = isJsxOpeningFragment;
- function isJsxClosingFragment(node) {
- return node.kind === 272 /* JsxClosingFragment */;
- }
- ts.isJsxClosingFragment = isJsxClosingFragment;
- function isJsxAttribute(node) {
- return node.kind === 273 /* JsxAttribute */;
- }
- ts.isJsxAttribute = isJsxAttribute;
- function isJsxAttributes(node) {
- return node.kind === 274 /* JsxAttributes */;
- }
- ts.isJsxAttributes = isJsxAttributes;
- function isJsxSpreadAttribute(node) {
- return node.kind === 275 /* JsxSpreadAttribute */;
- }
- ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
- function isJsxExpression(node) {
- return node.kind === 276 /* JsxExpression */;
- }
- ts.isJsxExpression = isJsxExpression;
- // Clauses
- function isCaseClause(node) {
- return node.kind === 277 /* CaseClause */;
- }
- ts.isCaseClause = isCaseClause;
- function isDefaultClause(node) {
- return node.kind === 278 /* DefaultClause */;
- }
- ts.isDefaultClause = isDefaultClause;
- function isHeritageClause(node) {
- return node.kind === 279 /* HeritageClause */;
- }
- ts.isHeritageClause = isHeritageClause;
- function isCatchClause(node) {
- return node.kind === 280 /* CatchClause */;
- }
- ts.isCatchClause = isCatchClause;
- // Property assignments
- function isPropertyAssignment(node) {
- return node.kind === 281 /* PropertyAssignment */;
- }
- ts.isPropertyAssignment = isPropertyAssignment;
- function isShorthandPropertyAssignment(node) {
- return node.kind === 282 /* ShorthandPropertyAssignment */;
- }
- ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
- function isSpreadAssignment(node) {
- return node.kind === 283 /* SpreadAssignment */;
- }
- ts.isSpreadAssignment = isSpreadAssignment;
- // Enum
- function isEnumMember(node) {
- return node.kind === 284 /* EnumMember */;
- }
- ts.isEnumMember = isEnumMember;
- // Top-level nodes
- function isSourceFile(node) {
- return node.kind === 290 /* SourceFile */;
- }
- ts.isSourceFile = isSourceFile;
- function isBundle(node) {
- return node.kind === 291 /* Bundle */;
- }
- ts.isBundle = isBundle;
- function isUnparsedSource(node) {
- return node.kind === 292 /* UnparsedSource */;
- }
- ts.isUnparsedSource = isUnparsedSource;
- function isUnparsedPrepend(node) {
- return node.kind === 286 /* UnparsedPrepend */;
- }
- ts.isUnparsedPrepend = isUnparsedPrepend;
- function isUnparsedTextLike(node) {
- switch (node.kind) {
- case 287 /* UnparsedText */:
- case 288 /* UnparsedInternalText */:
- return true;
- default:
- return false;
- }
- }
- ts.isUnparsedTextLike = isUnparsedTextLike;
- function isUnparsedNode(node) {
- return isUnparsedTextLike(node) ||
- node.kind === 285 /* UnparsedPrologue */ ||
- node.kind === 289 /* UnparsedSyntheticReference */;
- }
- ts.isUnparsedNode = isUnparsedNode;
- // JSDoc
- function isJSDocTypeExpression(node) {
- return node.kind === 294 /* JSDocTypeExpression */;
- }
- ts.isJSDocTypeExpression = isJSDocTypeExpression;
- function isJSDocAllType(node) {
- return node.kind === 295 /* JSDocAllType */;
- }
- ts.isJSDocAllType = isJSDocAllType;
- function isJSDocUnknownType(node) {
- return node.kind === 296 /* JSDocUnknownType */;
- }
- ts.isJSDocUnknownType = isJSDocUnknownType;
- function isJSDocNullableType(node) {
- return node.kind === 297 /* JSDocNullableType */;
- }
- ts.isJSDocNullableType = isJSDocNullableType;
- function isJSDocNonNullableType(node) {
- return node.kind === 298 /* JSDocNonNullableType */;
- }
- ts.isJSDocNonNullableType = isJSDocNonNullableType;
- function isJSDocOptionalType(node) {
- return node.kind === 299 /* JSDocOptionalType */;
- }
- ts.isJSDocOptionalType = isJSDocOptionalType;
- function isJSDocFunctionType(node) {
- return node.kind === 300 /* JSDocFunctionType */;
- }
- ts.isJSDocFunctionType = isJSDocFunctionType;
- function isJSDocVariadicType(node) {
- return node.kind === 301 /* JSDocVariadicType */;
- }
- ts.isJSDocVariadicType = isJSDocVariadicType;
- function isJSDoc(node) {
- return node.kind === 303 /* JSDocComment */;
- }
- ts.isJSDoc = isJSDoc;
- function isJSDocAuthorTag(node) {
- return node.kind === 309 /* JSDocAuthorTag */;
- }
- ts.isJSDocAuthorTag = isJSDocAuthorTag;
- function isJSDocAugmentsTag(node) {
- return node.kind === 307 /* JSDocAugmentsTag */;
- }
- ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
- function isJSDocImplementsTag(node) {
- return node.kind === 308 /* JSDocImplementsTag */;
- }
- ts.isJSDocImplementsTag = isJSDocImplementsTag;
- function isJSDocClassTag(node) {
- return node.kind === 310 /* JSDocClassTag */;
- }
- ts.isJSDocClassTag = isJSDocClassTag;
- function isJSDocPublicTag(node) {
- return node.kind === 311 /* JSDocPublicTag */;
- }
- ts.isJSDocPublicTag = isJSDocPublicTag;
- function isJSDocPrivateTag(node) {
- return node.kind === 312 /* JSDocPrivateTag */;
- }
- ts.isJSDocPrivateTag = isJSDocPrivateTag;
- function isJSDocProtectedTag(node) {
- return node.kind === 313 /* JSDocProtectedTag */;
- }
- ts.isJSDocProtectedTag = isJSDocProtectedTag;
- function isJSDocReadonlyTag(node) {
- return node.kind === 314 /* JSDocReadonlyTag */;
- }
- ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
- function isJSDocEnumTag(node) {
- return node.kind === 316 /* JSDocEnumTag */;
- }
- ts.isJSDocEnumTag = isJSDocEnumTag;
- function isJSDocThisTag(node) {
- return node.kind === 319 /* JSDocThisTag */;
- }
- ts.isJSDocThisTag = isJSDocThisTag;
- function isJSDocParameterTag(node) {
- return node.kind === 317 /* JSDocParameterTag */;
- }
- ts.isJSDocParameterTag = isJSDocParameterTag;
- function isJSDocReturnTag(node) {
- return node.kind === 318 /* JSDocReturnTag */;
- }
- ts.isJSDocReturnTag = isJSDocReturnTag;
- function isJSDocTypeTag(node) {
- return node.kind === 320 /* JSDocTypeTag */;
- }
- ts.isJSDocTypeTag = isJSDocTypeTag;
- function isJSDocTemplateTag(node) {
- return node.kind === 321 /* JSDocTemplateTag */;
- }
- ts.isJSDocTemplateTag = isJSDocTemplateTag;
- function isJSDocTypedefTag(node) {
- return node.kind === 322 /* JSDocTypedefTag */;
- }
- ts.isJSDocTypedefTag = isJSDocTypedefTag;
- function isJSDocPropertyTag(node) {
- return node.kind === 323 /* JSDocPropertyTag */;
- }
- ts.isJSDocPropertyTag = isJSDocPropertyTag;
- function isJSDocPropertyLikeTag(node) {
- return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
- }
- ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
- function isJSDocTypeLiteral(node) {
- return node.kind === 304 /* JSDocTypeLiteral */;
- }
- ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
- function isJSDocCallbackTag(node) {
- return node.kind === 315 /* JSDocCallbackTag */;
- }
- ts.isJSDocCallbackTag = isJSDocCallbackTag;
- function isJSDocSignature(node) {
- return node.kind === 305 /* JSDocSignature */;
- }
- ts.isJSDocSignature = isJSDocSignature;
- // #endregion
- // #region
- // Node tests
- //
- // All node tests in the following list should *not* reference parent pointers so that
- // they may be used with transformations.
- /* @internal */
- function isSyntaxList(n) {
- return n.kind === 324 /* SyntaxList */;
- }
- ts.isSyntaxList = isSyntaxList;
- /* @internal */
- function isNode(node) {
- return isNodeKind(node.kind);
- }
- ts.isNode = isNode;
- /* @internal */
- function isNodeKind(kind) {
- return kind >= 153 /* 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 /* FirstToken */ && n.kind <= 152 /* 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 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
- }
- ts.isLiteralKind = isLiteralKind;
- function isLiteralExpression(node) {
- return isLiteralKind(node.kind);
- }
- ts.isLiteralExpression = isLiteralExpression;
- // Pseudo-literals
- /* @internal */
- function isTemplateLiteralKind(kind) {
- return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
- }
- ts.isTemplateLiteralKind = isTemplateLiteralKind;
- function isTemplateLiteralToken(node) {
- return isTemplateLiteralKind(node.kind);
- }
- ts.isTemplateLiteralToken = isTemplateLiteralToken;
- function isTemplateMiddleOrTemplateTail(node) {
- var kind = node.kind;
- return kind === 16 /* TemplateMiddle */
- || kind === 17 /* TemplateTail */;
- }
- ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
- function isImportOrExportSpecifier(node) {
- return isImportSpecifier(node) || isExportSpecifier(node);
- }
- ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
- function isTypeOnlyImportOrExportDeclaration(node) {
- switch (node.kind) {
- case 258 /* ImportSpecifier */:
- case 263 /* ExportSpecifier */:
- return node.parent.parent.isTypeOnly;
- case 256 /* NamespaceImport */:
- return node.parent.isTypeOnly;
- case 255 /* ImportClause */:
- return node.isTypeOnly;
- default:
- return false;
- }
- }
- ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
- function isStringTextContainingNode(node) {
- return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
- }
- ts.isStringTextContainingNode = isStringTextContainingNode;
- // Identifiers
- /* @internal */
- function isGeneratedIdentifier(node) {
- return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
- }
- ts.isGeneratedIdentifier = isGeneratedIdentifier;
- // Private Identifiers
- /*@internal*/
- function isPrivateIdentifierPropertyDeclaration(node) {
- return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
- }
- ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
- /*@internal*/
- function isPrivateIdentifierPropertyAccessExpression(node) {
- return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
- }
- ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
- // Keywords
- /* @internal */
- function isModifierKind(token) {
- switch (token) {
- case 122 /* AbstractKeyword */:
- case 126 /* AsyncKeyword */:
- case 81 /* ConstKeyword */:
- case 130 /* DeclareKeyword */:
- case 84 /* DefaultKeyword */:
- case 89 /* ExportKeyword */:
- case 119 /* PublicKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 138 /* ReadonlyKeyword */:
- case 120 /* StaticKeyword */:
- return true;
- }
- return false;
- }
- ts.isModifierKind = isModifierKind;
- /* @internal */
- function isParameterPropertyModifier(kind) {
- return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
- }
- ts.isParameterPropertyModifier = isParameterPropertyModifier;
- /* @internal */
- function isClassMemberModifier(idToken) {
- return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
- }
- ts.isClassMemberModifier = isClassMemberModifier;
- function isModifier(node) {
- return isModifierKind(node.kind);
- }
- ts.isModifier = isModifier;
- function isEntityName(node) {
- var kind = node.kind;
- return kind === 153 /* QualifiedName */
- || kind === 75 /* Identifier */;
- }
- ts.isEntityName = isEntityName;
- function isPropertyName(node) {
- var kind = node.kind;
- return kind === 75 /* Identifier */
- || kind === 76 /* PrivateIdentifier */
- || kind === 10 /* StringLiteral */
- || kind === 8 /* NumericLiteral */
- || kind === 154 /* ComputedPropertyName */;
- }
- ts.isPropertyName = isPropertyName;
- function isBindingName(node) {
- var kind = node.kind;
- return kind === 75 /* Identifier */
- || kind === 189 /* ObjectBindingPattern */
- || kind === 190 /* 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 244 /* FunctionDeclaration */:
- case 161 /* MethodDeclaration */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- return true;
- default:
- return false;
- }
- }
- /* @internal */
- function isFunctionLikeKind(kind) {
- switch (kind) {
- case 160 /* MethodSignature */:
- case 165 /* CallSignature */:
- case 305 /* JSDocSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- case 170 /* FunctionType */:
- case 300 /* JSDocFunctionType */:
- case 171 /* ConstructorType */:
- return true;
- default:
- return isFunctionLikeDeclarationKind(kind);
- }
- }
- ts.isFunctionLikeKind = isFunctionLikeKind;
- /* @internal */
- function isFunctionOrModuleBlock(node) {
- return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
- }
- ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
- // Classes
- function isClassElement(node) {
- var kind = node.kind;
- return kind === 162 /* Constructor */
- || kind === 159 /* PropertyDeclaration */
- || kind === 161 /* MethodDeclaration */
- || kind === 163 /* GetAccessor */
- || kind === 164 /* SetAccessor */
- || kind === 167 /* IndexSignature */
- || kind === 222 /* SemicolonClassElement */;
- }
- ts.isClassElement = isClassElement;
- function isClassLike(node) {
- return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
- }
- ts.isClassLike = isClassLike;
- function isAccessor(node) {
- return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
- }
- ts.isAccessor = isAccessor;
- /* @internal */
- function isMethodOrAccessor(node) {
- switch (node.kind) {
- case 161 /* MethodDeclaration */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- return true;
- default:
- return false;
- }
- }
- ts.isMethodOrAccessor = isMethodOrAccessor;
- // Type members
- function isTypeElement(node) {
- var kind = node.kind;
- return kind === 166 /* ConstructSignature */
- || kind === 165 /* CallSignature */
- || kind === 158 /* PropertySignature */
- || kind === 160 /* MethodSignature */
- || kind === 167 /* IndexSignature */;
- }
- ts.isTypeElement = isTypeElement;
- function isClassOrTypeElement(node) {
- return isTypeElement(node) || isClassElement(node);
- }
- ts.isClassOrTypeElement = isClassOrTypeElement;
- function isObjectLiteralElementLike(node) {
- var kind = node.kind;
- return kind === 281 /* PropertyAssignment */
- || kind === 282 /* ShorthandPropertyAssignment */
- || kind === 283 /* SpreadAssignment */
- || kind === 161 /* MethodDeclaration */
- || kind === 163 /* GetAccessor */
- || kind === 164 /* SetAccessor */;
- }
- ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
- // Type
- /**
- * 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 ts.isTypeNodeKind(node.kind);
- }
- ts.isTypeNode = isTypeNode;
- function isFunctionOrConstructorTypeNode(node) {
- switch (node.kind) {
- case 170 /* FunctionType */:
- case 171 /* ConstructorType */:
- return true;
- }
- return false;
- }
- ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
- // Binding patterns
- /* @internal */
- function isBindingPattern(node) {
- if (node) {
- var kind = node.kind;
- return kind === 190 /* ArrayBindingPattern */
- || kind === 189 /* ObjectBindingPattern */;
- }
- return false;
- }
- ts.isBindingPattern = isBindingPattern;
- /* @internal */
- function isAssignmentPattern(node) {
- var kind = node.kind;
- return kind === 192 /* ArrayLiteralExpression */
- || kind === 193 /* ObjectLiteralExpression */;
- }
- ts.isAssignmentPattern = isAssignmentPattern;
- /* @internal */
- function isArrayBindingElement(node) {
- var kind = node.kind;
- return kind === 191 /* BindingElement */
- || kind === 215 /* OmittedExpression */;
- }
- ts.isArrayBindingElement = isArrayBindingElement;
- /**
- * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
- */
- /* @internal */
- function isDeclarationBindingElement(bindingElement) {
- switch (bindingElement.kind) {
- case 242 /* VariableDeclaration */:
- case 156 /* Parameter */:
- case 191 /* 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 189 /* ObjectBindingPattern */:
- case 193 /* ObjectLiteralExpression */:
- return true;
- }
- return false;
- }
- ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
- /**
- * Determines whether a node is an ArrayBindingOrAssignmentPattern
- */
- /* @internal */
- function isArrayBindingOrAssignmentPattern(node) {
- switch (node.kind) {
- case 190 /* ArrayBindingPattern */:
- case 192 /* ArrayLiteralExpression */:
- return true;
- }
- return false;
- }
- ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
- /* @internal */
- function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
- var kind = node.kind;
- return kind === 194 /* PropertyAccessExpression */
- || kind === 153 /* QualifiedName */
- || kind === 188 /* ImportType */;
- }
- ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
- // Expression
- function isPropertyAccessOrQualifiedName(node) {
- var kind = node.kind;
- return kind === 194 /* PropertyAccessExpression */
- || kind === 153 /* QualifiedName */;
- }
- ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
- function isCallLikeExpression(node) {
- switch (node.kind) {
- case 268 /* JsxOpeningElement */:
- case 267 /* JsxSelfClosingElement */:
- case 196 /* CallExpression */:
- case 197 /* NewExpression */:
- case 198 /* TaggedTemplateExpression */:
- case 157 /* Decorator */:
- return true;
- default:
- return false;
- }
- }
- ts.isCallLikeExpression = isCallLikeExpression;
- function isCallOrNewExpression(node) {
- return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
- }
- ts.isCallOrNewExpression = isCallOrNewExpression;
- function isTemplateLiteral(node) {
- var kind = node.kind;
- return kind === 211 /* TemplateExpression */
- || kind === 14 /* NoSubstitutionTemplateLiteral */;
- }
- ts.isTemplateLiteral = isTemplateLiteral;
- /* @internal */
- function isLeftHandSideExpression(node) {
- return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
- }
- ts.isLeftHandSideExpression = isLeftHandSideExpression;
- function isLeftHandSideExpressionKind(kind) {
- switch (kind) {
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- case 197 /* NewExpression */:
- case 196 /* CallExpression */:
- case 266 /* JsxElement */:
- case 267 /* JsxSelfClosingElement */:
- case 270 /* JsxFragment */:
- case 198 /* TaggedTemplateExpression */:
- case 192 /* ArrayLiteralExpression */:
- case 200 /* ParenthesizedExpression */:
- case 193 /* ObjectLiteralExpression */:
- case 214 /* ClassExpression */:
- case 201 /* FunctionExpression */:
- case 75 /* Identifier */:
- case 13 /* RegularExpressionLiteral */:
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 211 /* TemplateExpression */:
- case 91 /* FalseKeyword */:
- case 100 /* NullKeyword */:
- case 104 /* ThisKeyword */:
- case 106 /* TrueKeyword */:
- case 102 /* SuperKeyword */:
- case 218 /* NonNullExpression */:
- case 219 /* MetaProperty */:
- case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
- return true;
- default:
- return false;
- }
- }
- /* @internal */
- function isUnaryExpression(node) {
- return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
- }
- ts.isUnaryExpression = isUnaryExpression;
- function isUnaryExpressionKind(kind) {
- switch (kind) {
- case 207 /* PrefixUnaryExpression */:
- case 208 /* PostfixUnaryExpression */:
- case 203 /* DeleteExpression */:
- case 204 /* TypeOfExpression */:
- case 205 /* VoidExpression */:
- case 206 /* AwaitExpression */:
- case 199 /* TypeAssertionExpression */:
- return true;
- default:
- return isLeftHandSideExpressionKind(kind);
- }
- }
- /* @internal */
- function isUnaryExpressionWithWrite(expr) {
- switch (expr.kind) {
- case 208 /* PostfixUnaryExpression */:
- return true;
- case 207 /* PrefixUnaryExpression */:
- return expr.operator === 45 /* PlusPlusToken */ ||
- expr.operator === 46 /* 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(skipPartiallyEmittedExpressions(node).kind);
- }
- ts.isExpression = isExpression;
- function isExpressionKind(kind) {
- switch (kind) {
- case 210 /* ConditionalExpression */:
- case 212 /* YieldExpression */:
- case 202 /* ArrowFunction */:
- case 209 /* BinaryExpression */:
- case 213 /* SpreadElement */:
- case 217 /* AsExpression */:
- case 215 /* OmittedExpression */:
- case 327 /* CommaListExpression */:
- case 326 /* PartiallyEmittedExpression */:
- return true;
- default:
- return isUnaryExpressionKind(kind);
- }
- }
- function isAssertionExpression(node) {
- var kind = node.kind;
- return kind === 199 /* TypeAssertionExpression */
- || kind === 217 /* AsExpression */;
- }
- ts.isAssertionExpression = isAssertionExpression;
- /* @internal */
- function isPartiallyEmittedExpression(node) {
- return node.kind === 326 /* PartiallyEmittedExpression */;
- }
- ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
- /* @internal */
- function isNotEmittedStatement(node) {
- return node.kind === 325 /* NotEmittedStatement */;
- }
- ts.isNotEmittedStatement = isNotEmittedStatement;
- /* @internal */
- function isSyntheticReference(node) {
- return node.kind === 330 /* SyntheticReferenceExpression */;
- }
- ts.isSyntheticReference = isSyntheticReference;
- /* @internal */
- function isNotEmittedOrPartiallyEmittedNode(node) {
- return isNotEmittedStatement(node)
- || isPartiallyEmittedExpression(node);
- }
- ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
- function isIterationStatement(node, lookInLabeledStatements) {
- switch (node.kind) {
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- case 228 /* DoStatement */:
- case 229 /* WhileStatement */:
- return true;
- case 238 /* LabeledStatement */:
- return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
- }
- return false;
- }
- ts.isIterationStatement = isIterationStatement;
- /* @internal */
- function isScopeMarker(node) {
- return isExportAssignment(node) || isExportDeclaration(node);
- }
- ts.isScopeMarker = isScopeMarker;
- /* @internal */
- function hasScopeMarker(statements) {
- return ts.some(statements, isScopeMarker);
- }
- ts.hasScopeMarker = hasScopeMarker;
- /* @internal */
- function needsScopeMarker(result) {
- return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
- }
- ts.needsScopeMarker = needsScopeMarker;
- /* @internal */
- function isExternalModuleIndicator(result) {
- // Exported top-level member indicates moduleness
- return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
- }
- ts.isExternalModuleIndicator = isExternalModuleIndicator;
- /* @internal */
- function isForInOrOfStatement(node) {
- return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
- }
- ts.isForInOrOfStatement = isForInOrOfStatement;
- // Element
- /* @internal */
- function isConciseBody(node) {
- return isBlock(node)
- || isExpression(node);
- }
- ts.isConciseBody = isConciseBody;
- /* @internal */
- function isFunctionBody(node) {
- return isBlock(node);
- }
- ts.isFunctionBody = isFunctionBody;
- /* @internal */
- function isForInitializer(node) {
- return isVariableDeclarationList(node)
- || isExpression(node);
- }
- ts.isForInitializer = isForInitializer;
- /* @internal */
- function isModuleBody(node) {
- var kind = node.kind;
- return kind === 250 /* ModuleBlock */
- || kind === 249 /* ModuleDeclaration */
- || kind === 75 /* Identifier */;
- }
- ts.isModuleBody = isModuleBody;
- /* @internal */
- function isNamespaceBody(node) {
- var kind = node.kind;
- return kind === 250 /* ModuleBlock */
- || kind === 249 /* ModuleDeclaration */;
- }
- ts.isNamespaceBody = isNamespaceBody;
- /* @internal */
- function isJSDocNamespaceBody(node) {
- var kind = node.kind;
- return kind === 75 /* Identifier */
- || kind === 249 /* ModuleDeclaration */;
- }
- ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
- /* @internal */
- function isNamedImportBindings(node) {
- var kind = node.kind;
- return kind === 257 /* NamedImports */
- || kind === 256 /* NamespaceImport */;
- }
- ts.isNamedImportBindings = isNamedImportBindings;
- /* @internal */
- function isModuleOrEnumDeclaration(node) {
- return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
- }
- ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
- function isDeclarationKind(kind) {
- return kind === 202 /* ArrowFunction */
- || kind === 191 /* BindingElement */
- || kind === 245 /* ClassDeclaration */
- || kind === 214 /* ClassExpression */
- || kind === 162 /* Constructor */
- || kind === 248 /* EnumDeclaration */
- || kind === 284 /* EnumMember */
- || kind === 263 /* ExportSpecifier */
- || kind === 244 /* FunctionDeclaration */
- || kind === 201 /* FunctionExpression */
- || kind === 163 /* GetAccessor */
- || kind === 255 /* ImportClause */
- || kind === 253 /* ImportEqualsDeclaration */
- || kind === 258 /* ImportSpecifier */
- || kind === 246 /* InterfaceDeclaration */
- || kind === 273 /* JsxAttribute */
- || kind === 161 /* MethodDeclaration */
- || kind === 160 /* MethodSignature */
- || kind === 249 /* ModuleDeclaration */
- || kind === 252 /* NamespaceExportDeclaration */
- || kind === 256 /* NamespaceImport */
- || kind === 262 /* NamespaceExport */
- || kind === 156 /* Parameter */
- || kind === 281 /* PropertyAssignment */
- || kind === 159 /* PropertyDeclaration */
- || kind === 158 /* PropertySignature */
- || kind === 164 /* SetAccessor */
- || kind === 282 /* ShorthandPropertyAssignment */
- || kind === 247 /* TypeAliasDeclaration */
- || kind === 155 /* TypeParameter */
- || kind === 242 /* VariableDeclaration */
- || kind === 322 /* JSDocTypedefTag */
- || kind === 315 /* JSDocCallbackTag */
- || kind === 323 /* JSDocPropertyTag */;
- }
- function isDeclarationStatementKind(kind) {
- return kind === 244 /* FunctionDeclaration */
- || kind === 264 /* MissingDeclaration */
- || kind === 245 /* ClassDeclaration */
- || kind === 246 /* InterfaceDeclaration */
- || kind === 247 /* TypeAliasDeclaration */
- || kind === 248 /* EnumDeclaration */
- || kind === 249 /* ModuleDeclaration */
- || kind === 254 /* ImportDeclaration */
- || kind === 253 /* ImportEqualsDeclaration */
- || kind === 260 /* ExportDeclaration */
- || kind === 259 /* ExportAssignment */
- || kind === 252 /* NamespaceExportDeclaration */;
- }
- function isStatementKindButNotDeclarationKind(kind) {
- return kind === 234 /* BreakStatement */
- || kind === 233 /* ContinueStatement */
- || kind === 241 /* DebuggerStatement */
- || kind === 228 /* DoStatement */
- || kind === 226 /* ExpressionStatement */
- || kind === 224 /* EmptyStatement */
- || kind === 231 /* ForInStatement */
- || kind === 232 /* ForOfStatement */
- || kind === 230 /* ForStatement */
- || kind === 227 /* IfStatement */
- || kind === 238 /* LabeledStatement */
- || kind === 235 /* ReturnStatement */
- || kind === 237 /* SwitchStatement */
- || kind === 239 /* ThrowStatement */
- || kind === 240 /* TryStatement */
- || kind === 225 /* VariableStatement */
- || kind === 229 /* WhileStatement */
- || kind === 236 /* WithStatement */
- || kind === 325 /* NotEmittedStatement */
- || kind === 329 /* EndOfDeclarationMarker */
- || kind === 328 /* MergeDeclarationMarker */;
- }
- /* @internal */
- function isDeclaration(node) {
- if (node.kind === 155 /* TypeParameter */) {
- return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(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)
- || isDeclarationStatementKind(kind)
- || isBlockStatement(node);
- }
- ts.isStatement = isStatement;
- function isBlockStatement(node) {
- if (node.kind !== 223 /* Block */)
- return false;
- if (node.parent !== undefined) {
- if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
- return false;
- }
- }
- return !ts.isFunctionBlock(node);
- }
- // Module references
- /* @internal */
- function isModuleReference(node) {
- var kind = node.kind;
- return kind === 265 /* ExternalModuleReference */
- || kind === 153 /* QualifiedName */
- || kind === 75 /* Identifier */;
- }
- ts.isModuleReference = isModuleReference;
- // JSX
- /* @internal */
- function isJsxTagNameExpression(node) {
- var kind = node.kind;
- return kind === 104 /* ThisKeyword */
- || kind === 75 /* Identifier */
- || kind === 194 /* PropertyAccessExpression */;
- }
- ts.isJsxTagNameExpression = isJsxTagNameExpression;
- /* @internal */
- function isJsxChild(node) {
- var kind = node.kind;
- return kind === 266 /* JsxElement */
- || kind === 276 /* JsxExpression */
- || kind === 267 /* JsxSelfClosingElement */
- || kind === 11 /* JsxText */
- || kind === 270 /* JsxFragment */;
- }
- ts.isJsxChild = isJsxChild;
- /* @internal */
- function isJsxAttributeLike(node) {
- var kind = node.kind;
- return kind === 273 /* JsxAttribute */
- || kind === 275 /* JsxSpreadAttribute */;
- }
- ts.isJsxAttributeLike = isJsxAttributeLike;
- /* @internal */
- function isStringLiteralOrJsxExpression(node) {
- var kind = node.kind;
- return kind === 10 /* StringLiteral */
- || kind === 276 /* JsxExpression */;
- }
- ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
- function isJsxOpeningLikeElement(node) {
- var kind = node.kind;
- return kind === 268 /* JsxOpeningElement */
- || kind === 267 /* JsxSelfClosingElement */;
- }
- ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
- // Clauses
- function isCaseOrDefaultClause(node) {
- var kind = node.kind;
- return kind === 277 /* CaseClause */
- || kind === 278 /* DefaultClause */;
- }
- ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
- // JSDoc
- /** True if node is of some JSDoc syntax kind. */
- /* @internal */
- function isJSDocNode(node) {
- return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
- }
- ts.isJSDocNode = isJSDocNode;
- /** True if node is of a kind that may contain comment text. */
- function isJSDocCommentContainingNode(node) {
- return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
- }
- ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
- // TODO: determine what this does before making it public.
- /* @internal */
- function isJSDocTag(node) {
- return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
- }
- ts.isJSDocTag = isJSDocTag;
- function isSetAccessor(node) {
- return node.kind === 164 /* SetAccessor */;
- }
- ts.isSetAccessor = isSetAccessor;
- function isGetAccessor(node) {
- return node.kind === 163 /* 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 has initializer node attached to it. */
- /* @internal */
- function hasInitializer(node) {
- return !!node.initializer;
- }
- ts.hasInitializer = hasInitializer;
- /** True if has initializer node attached to it. */
- function hasOnlyExpressionInitializer(node) {
- switch (node.kind) {
- case 242 /* VariableDeclaration */:
- case 156 /* Parameter */:
- case 191 /* BindingElement */:
- case 158 /* PropertySignature */:
- case 159 /* PropertyDeclaration */:
- case 281 /* PropertyAssignment */:
- case 284 /* EnumMember */:
- return true;
- default:
- return false;
- }
- }
- ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
- function isObjectLiteralElement(node) {
- return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
- }
- ts.isObjectLiteralElement = isObjectLiteralElement;
- /* @internal */
- function isTypeReferenceType(node) {
- return node.kind === 169 /* TypeReference */ || node.kind === 216 /* 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++) {
- var line = lines_1[_i];
- if (!line.length) {
- continue;
- }
- var i = 0;
- for (; i < line.length && i < indentation; i++) {
- if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
- break;
- }
- }
- if (i < indentation) {
- indentation = i;
- }
- if (indentation === 0) {
- return 0;
- }
- }
- return indentation === MAX_SMI_X86 ? undefined : indentation;
- }
- ts.guessIndentation = guessIndentation;
- function isStringLiteralLike(node) {
- return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
- }
- ts.isStringLiteralLike = isStringLiteralLike;
- // #endregion
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- ts.resolvingEmptyArray = [];
- ts.emptyMap = ts.createMap();
- ts.emptyUnderscoreEscapedMap = ts.emptyMap;
- ts.externalHelpersModuleNameText = "tslib";
- ts.defaultMaximumTruncationLength = 160;
- ts.noTruncationMaximumTruncationLength = 1000000;
- function getDeclarationOfKind(symbol, kind) {
- var declarations = symbol.declarations;
- if (declarations) {
- for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
- var declaration = declarations_1[_i];
- if (declaration.kind === kind) {
- return declaration;
- }
- }
- }
- return undefined;
- }
- ts.getDeclarationOfKind = getDeclarationOfKind;
- /** Create a new escaped identifier map. */
- function createUnderscoreEscapedMap() {
- return new ts.Map();
- }
- ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
- function hasEntries(map) {
- return !!map && !!map.size;
- }
- ts.hasEntries = hasEntries;
- function createSymbolTable(symbols) {
- var result = ts.createMap();
- if (symbols) {
- for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
- var symbol = symbols_1[_i];
- result.set(symbol.escapedName, symbol);
- }
- }
- return result;
- }
- ts.createSymbolTable = createSymbolTable;
- function isTransientSymbol(symbol) {
- return (symbol.flags & 33554432 /* Transient */) !== 0;
- }
- ts.isTransientSymbol = isTransientSymbol;
- var stringWriter = createSingleLineStringWriter();
- function createSingleLineStringWriter() {
- var str = "";
- var writeText = function (text) { return str += text; };
- return {
- getText: function () { return str; },
- write: writeText,
- rawWrite: writeText,
- writeKeyword: writeText,
- writeOperator: writeText,
- writePunctuation: writeText,
- writeSpace: writeText,
- writeStringLiteral: writeText,
- writeLiteral: writeText,
- writeParameter: writeText,
- writeProperty: writeText,
- writeSymbol: function (s, _) { return writeText(s); },
- writeTrailingSemicolon: writeText,
- writeComment: writeText,
- getTextPos: function () { return str.length; },
- getLine: function () { return 0; },
- getColumn: function () { return 0; },
- getIndent: function () { return 0; },
- isAtStartOfLine: function () { return false; },
- hasTrailingComment: function () { return false; },
- hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
- // Completely ignore indentation for string writers. And map newlines to
- // a single space.
- writeLine: function () { return str += " "; },
- increaseIndent: ts.noop,
- decreaseIndent: ts.noop,
- clear: function () { return str = ""; },
- trackSymbol: ts.noop,
- reportInaccessibleThisError: ts.noop,
- reportInaccessibleUniqueSymbolError: ts.noop,
- reportPrivateInBaseOfClassExpression: ts.noop,
- };
- }
- function changesAffectModuleResolution(oldOptions, newOptions) {
- return oldOptions.configFilePath !== newOptions.configFilePath ||
- optionsHaveModuleResolutionChanges(oldOptions, newOptions);
- }
- ts.changesAffectModuleResolution = changesAffectModuleResolution;
- function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
- return ts.moduleResolutionOptionDeclarations.some(function (o) {
- return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
- });
- }
- ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
- function findAncestor(node, callback) {
- while (node) {
- var result = callback(node);
- if (result === "quit") {
- return undefined;
- }
- else if (result) {
- return node;
- }
- node = node.parent;
- }
- return undefined;
- }
- ts.findAncestor = findAncestor;
- function forEachAncestor(node, callback) {
- while (true) {
- var res = callback(node);
- if (res === "quit")
- return undefined;
- if (res !== undefined)
- return res;
- if (ts.isSourceFile(node))
- return undefined;
- node = node.parent;
- }
- }
- ts.forEachAncestor = forEachAncestor;
- function forEachEntry(map, callback) {
- var iterator = map.entries();
- for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
- var _a = iterResult.value, key = _a[0], value = _a[1];
- var result = callback(value, key);
- if (result) {
- return result;
- }
- }
- return undefined;
- }
- ts.forEachEntry = forEachEntry;
- function forEachKey(map, callback) {
- var iterator = map.keys();
- for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
- var result = callback(iterResult.value);
- if (result) {
- return result;
- }
- }
- return undefined;
- }
- ts.forEachKey = forEachKey;
- function copyEntries(source, target) {
- source.forEach(function (value, key) {
- target.set(key, value);
- });
- }
- ts.copyEntries = copyEntries;
- function arrayToSet(array, makeKey) {
- return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
- }
- ts.arrayToSet = arrayToSet;
- function cloneMap(map) {
- var clone = ts.createMap();
- copyEntries(map, clone);
- return clone;
- }
- ts.cloneMap = cloneMap;
- function usingSingleLineStringWriter(action) {
- var oldString = stringWriter.getText();
- try {
- action(stringWriter);
- return stringWriter.getText();
- }
- finally {
- stringWriter.clear();
- stringWriter.writeKeyword(oldString);
- }
- }
- ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
- function getFullWidth(node) {
- return node.end - node.pos;
- }
- ts.getFullWidth = getFullWidth;
- function getResolvedModule(sourceFile, moduleNameText) {
- return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
- }
- ts.getResolvedModule = getResolvedModule;
- function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
- if (!sourceFile.resolvedModules) {
- sourceFile.resolvedModules = ts.createMap();
- }
- sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
- }
- ts.setResolvedModule = setResolvedModule;
- function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
- if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
- sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
- }
- sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
- }
- ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
- function projectReferenceIsEqualTo(oldRef, newRef) {
- return oldRef.path === newRef.path &&
- !oldRef.prepend === !newRef.prepend &&
- !oldRef.circular === !newRef.circular;
- }
- ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
- function moduleResolutionIsEqualTo(oldResolution, newResolution) {
- return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
- oldResolution.extension === newResolution.extension &&
- oldResolution.resolvedFileName === newResolution.resolvedFileName &&
- oldResolution.originalPath === newResolution.originalPath &&
- packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
- }
- ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
- function packageIdIsEqual(a, b) {
- return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
- }
- function packageIdToString(_a) {
- var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
- var fullName = subModuleName ? name + "/" + subModuleName : name;
- return fullName + "@" + version;
- }
- ts.packageIdToString = packageIdToString;
- function typeDirectiveIsEqualTo(oldResolution, newResolution) {
- return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
- }
- ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
- function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
- ts.Debug.assert(names.length === newResolutions.length);
- for (var i = 0; i < names.length; i++) {
- var newResolution = newResolutions[i];
- var oldResolution = oldResolutions && oldResolutions.get(names[i]);
- var changed = oldResolution
- ? !newResolution || !comparer(oldResolution, newResolution)
- : newResolution;
- if (changed) {
- return true;
- }
- }
- 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 & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
- }
- ts.containsParseError = containsParseError;
- function aggregateChildData(node) {
- if (!(node.flags & 524288 /* 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 & 65536 /* ThisNodeHasError */) !== 0) ||
- ts.forEachChild(node, containsParseError);
- // If so, mark ourselves accordingly.
- if (thisNodeOrAnySubNodesHasError) {
- node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
- }
- // 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 |= 524288 /* HasAggregatedChildData */;
- }
- }
- function getSourceFileOfNode(node) {
- while (node && node.kind !== 290 /* SourceFile */) {
- node = node.parent;
- }
- return node;
- }
- ts.getSourceFileOfNode = getSourceFileOfNode;
- function isStatementWithLocals(node) {
- switch (node.kind) {
- case 223 /* Block */:
- case 251 /* CaseBlock */:
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- return true;
- }
- return false;
- }
- ts.isStatementWithLocals = isStatementWithLocals;
- function getStartPositionOfLine(line, sourceFile) {
- ts.Debug.assert(line >= 0);
- 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);
- return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
- }
- ts.nodePosToString = nodePosToString;
- function getEndLinePosition(line, sourceFile) {
- ts.Debug.assert(line >= 0);
- var lineStarts = ts.getLineStarts(sourceFile);
- 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--;
- }
- return pos;
- }
- }
- 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 /* EndOfFileToken */;
- }
- ts.nodeIsMissing = nodeIsMissing;
- function nodeIsPresent(node) {
- return !nodeIsMissing(node);
- }
- ts.nodeIsPresent = nodeIsPresent;
- function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
- if (from === undefined || from.length === 0)
- return to;
- var statementIndex = 0;
- // skip all prologue directives to insert at the correct position
- for (; statementIndex < to.length; ++statementIndex) {
- if (!isPrologueDirective(to[statementIndex])) {
- break;
- }
- }
- to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
- return to;
- }
- function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
- if (statement === undefined)
- return to;
- var statementIndex = 0;
- // skip all prologue directives to insert at the correct position
- for (; statementIndex < to.length; ++statementIndex) {
- if (!isPrologueDirective(to[statementIndex])) {
- break;
- }
- }
- to.splice(statementIndex, 0, statement);
- return to;
- }
- function isAnyPrologueDirective(node) {
- return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
- }
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function insertStatementsAfterStandardPrologue(to, from) {
- return insertStatementsAfterPrologue(to, from, isPrologueDirective);
- }
- ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
- function insertStatementsAfterCustomPrologue(to, from) {
- return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
- }
- ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function insertStatementAfterStandardPrologue(to, statement) {
- return insertStatementAfterPrologue(to, statement, isPrologueDirective);
- }
- ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
- function insertStatementAfterCustomPrologue(to, statement) {
- return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
- }
- ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
- /**
- * 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) {
- // 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 /* slash */) {
- var textSubStr = text.substring(commentPos, commentEnd);
- return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
- textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
- textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
- textSubStr.match(defaultLibReferenceRegEx) ?
- true : false;
- }
- return false;
- }
- ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
- function isPinnedComment(text, start) {
- return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
- text.charCodeAt(start + 2) === 33 /* exclamation */;
- }
- ts.isPinnedComment = isPinnedComment;
- function createCommentDirectivesMap(sourceFile, commentDirectives) {
- var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
- "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
- commentDirective,
- ]); }));
- var usedLines = ts.createMap();
- return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
- function getUnusedExpectations() {
- return ts.arrayFrom(directivesByLine.entries())
- .filter(function (_a) {
- var line = _a[0], directive = _a[1];
- return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
- })
- .map(function (_a) {
- var _ = _a[0], directive = _a[1];
- return directive;
- });
- }
- function markUsed(line) {
- if (!directivesByLine.has("" + line)) {
- return false;
- }
- usedLines.set("" + line, true);
- return true;
- }
- }
- ts.createCommentDirectivesMap = createCommentDirectivesMap;
- 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, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- }
- if (includeJsDoc && ts.hasJSDocNodes(node)) {
- return getTokenPosOfNode(node.jsDoc[0], sourceFile);
- }
- // 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 === 324 /* SyntaxList */ && node._children.length > 0) {
- return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
- }
- return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
- }
- ts.getTokenPosOfNode = getTokenPosOfNode;
- function getNonDecoratorTokenPosOfNode(node, sourceFile) {
- if (nodeIsMissing(node) || !node.decorators) {
- return getTokenPosOfNode(node, sourceFile);
- }
- return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
- }
- ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
- function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
- if (includeTrivia === void 0) { includeTrivia = false; }
- return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
- }
- ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
- function isJSDocTypeExpressionOrChild(node) {
- return !!findAncestor(node, ts.isJSDocTypeExpression);
- }
- function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
- if (includeTrivia === void 0) { includeTrivia = false; }
- if (nodeIsMissing(node)) {
- return "";
- }
- var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
- if (isJSDocTypeExpressionOrChild(node)) {
- // strip space + asterisk at line start
- text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
- }
- return text;
- }
- ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
- function getTextOfNode(node, includeTrivia) {
- if (includeTrivia === void 0) { includeTrivia = false; }
- return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
- }
- ts.getTextOfNode = getTextOfNode;
- 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, neverAsciiEscape, jsxAttributeEscape) {
- // 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 */) ||
- ts.isBigIntLiteral(node))) {
- return getSourceTextOfNodeFromSourceFile(sourceFile, node);
- }
- // 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 10 /* StringLiteral */: {
- var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
- neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
- escapeNonAsciiString;
- if (node.singleQuote) {
- return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
- }
- else {
- return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
- }
- }
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 15 /* TemplateHead */:
- case 16 /* TemplateMiddle */:
- case 17 /* TemplateTail */: {
- // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
- // had to include a backslash: `not \${a} substitution`.
- var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
- escapeNonAsciiString;
- var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
- switch (node.kind) {
- case 14 /* NoSubstitutionTemplateLiteral */:
- return "`" + rawText + "`";
- case 15 /* TemplateHead */:
- return "`" + rawText + "${";
- case 16 /* TemplateMiddle */:
- return "}" + rawText + "${";
- case 17 /* TemplateTail */:
- return "}" + rawText + "`";
- }
- break;
- }
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 13 /* RegularExpressionLiteral */:
- return node.text;
- }
- return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
- }
- ts.getLiteralText = getLiteralText;
- function getTextOfConstantValue(value) {
- return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
- }
- ts.getTextOfConstantValue = getTextOfConstantValue;
- // 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 /* BlockScoped */) !== 0 ||
- isCatchClauseVariableDeclarationOrBindingElement(declaration);
- }
- ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
- function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
- var node = getRootDeclaration(declaration);
- return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
- }
- ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
- function isAmbientModule(node) {
- return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
- }
- ts.isAmbientModule = isAmbientModule;
- function isModuleWithStringLiteralName(node) {
- return ts.isModuleDeclaration(node) && node.name.kind === 10 /* 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) {
- // The only kind of module that can be missing a body is a shorthand ambient module.
- return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
- }
- function isBlockScopedContainerTopLevel(node) {
- return node.kind === 290 /* SourceFile */ ||
- node.kind === 249 /* ModuleDeclaration */ ||
- ts.isFunctionLike(node);
- }
- ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
- function isGlobalScopeAugmentation(module) {
- return !!(module.flags & 1024 /* GlobalAugmentation */);
- }
- ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
- function isExternalModuleAugmentation(node) {
- return isAmbientModule(node) && isModuleAugmentationExternal(node);
- }
- 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 290 /* SourceFile */:
- return ts.isExternalModule(node.parent);
- case 250 /* ModuleBlock */:
- return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
- }
- return false;
- }
- ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
- function getNonAugmentationDeclaration(symbol) {
- return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
- }
- ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
- function isEffectiveExternalModule(node, compilerOptions) {
- return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
- }
- ts.isEffectiveExternalModule = isEffectiveExternalModule;
- /**
- * Returns whether the source file will be treated as if it were in strict mode at runtime.
- */
- function isEffectiveStrictModeSourceFile(node, compilerOptions) {
- // We can only verify strict mode for JS/TS files
- switch (node.scriptKind) {
- case 1 /* JS */:
- case 3 /* TS */:
- case 2 /* JSX */:
- case 4 /* TSX */:
- break;
- default:
- return false;
- }
- // Strict mode does not matter for declaration files.
- if (node.isDeclarationFile) {
- return false;
- }
- // If `alwaysStrict` is set, then treat the file as strict.
- if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
- return true;
- }
- // Starting with a "use strict" directive indicates the file is strict.
- if (ts.startsWithUseStrict(node.statements)) {
- return true;
- }
- if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
- // ECMAScript Modules are always strict.
- if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
- return true;
- }
- // Other modules are strict unless otherwise specified.
- return !compilerOptions.noImplicitUseStrict;
- }
- return false;
- }
- ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
- function isBlockScope(node, parentNode) {
- switch (node.kind) {
- case 290 /* SourceFile */:
- case 251 /* CaseBlock */:
- case 280 /* CatchClause */:
- case 249 /* ModuleDeclaration */:
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- case 162 /* Constructor */:
- case 161 /* MethodDeclaration */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- return true;
- case 223 /* 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;
- }
- ts.isBlockScope = isBlockScope;
- function isDeclarationWithTypeParameters(node) {
- switch (node.kind) {
- case 315 /* JSDocCallbackTag */:
- case 322 /* JSDocTypedefTag */:
- case 305 /* JSDocSignature */:
- return true;
- default:
- ts.assertType(node);
- return isDeclarationWithTypeParameterChildren(node);
- }
- }
- ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
- function isDeclarationWithTypeParameterChildren(node) {
- switch (node.kind) {
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 160 /* MethodSignature */:
- case 167 /* IndexSignature */:
- case 170 /* FunctionType */:
- case 171 /* ConstructorType */:
- case 300 /* JSDocFunctionType */:
- case 245 /* ClassDeclaration */:
- case 214 /* ClassExpression */:
- case 246 /* InterfaceDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- case 321 /* JSDocTemplateTag */:
- case 244 /* FunctionDeclaration */:
- case 161 /* MethodDeclaration */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- return true;
- default:
- ts.assertType(node);
- return false;
- }
- }
- ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
- function isAnyImportSyntax(node) {
- switch (node.kind) {
- case 254 /* ImportDeclaration */:
- case 253 /* ImportEqualsDeclaration */:
- return true;
- default:
- return false;
- }
- }
- ts.isAnyImportSyntax = isAnyImportSyntax;
- function isLateVisibilityPaintedStatement(node) {
- switch (node.kind) {
- case 254 /* ImportDeclaration */:
- case 253 /* ImportEqualsDeclaration */:
- case 225 /* VariableStatement */:
- case 245 /* ClassDeclaration */:
- case 244 /* FunctionDeclaration */:
- case 249 /* ModuleDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- case 246 /* InterfaceDeclaration */:
- case 248 /* EnumDeclaration */:
- return true;
- default:
- return false;
- }
- }
- ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
- function isAnyImportOrReExport(node) {
- 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 !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
- }
- ts.declarationNameToString = declarationNameToString;
- function getNameFromIndexInfo(info) {
- return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
- }
- ts.getNameFromIndexInfo = getNameFromIndexInfo;
- function isComputedNonLiteralName(name) {
- return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
- }
- ts.isComputedNonLiteralName = isComputedNonLiteralName;
- function getTextOfPropertyName(name) {
- switch (name.kind) {
- case 75 /* Identifier */:
- case 76 /* PrivateIdentifier */:
- return name.escapedText;
- case 10 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- return ts.escapeLeadingUnderscores(name.text);
- case 154 /* ComputedPropertyName */:
- if (isStringOrNumericLiteralLike(name.expression))
- return ts.escapeLeadingUnderscores(name.expression.text);
- return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
- default:
- return ts.Debug.assertNever(name);
- }
- }
- ts.getTextOfPropertyName = getTextOfPropertyName;
- function entityNameToString(name) {
- switch (name.kind) {
- case 104 /* ThisKeyword */:
- return "this";
- case 76 /* PrivateIdentifier */:
- case 75 /* Identifier */:
- return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
- case 153 /* QualifiedName */:
- return entityNameToString(name.left) + "." + entityNameToString(name.right);
- case 194 /* PropertyAccessExpression */:
- if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
- return entityNameToString(name.expression) + "." + entityNameToString(name.name);
- }
- else {
- return ts.Debug.assertNever(name.name);
- }
- default:
- return ts.Debug.assertNever(name);
- }
- }
- ts.entityNameToString = entityNameToString;
- function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
- var sourceFile = getSourceFileOfNode(node);
- return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
- }
- ts.createDiagnosticForNode = createDiagnosticForNode;
- function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
- var start = ts.skipTrivia(sourceFile.text, nodes.pos);
- return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
- }
- ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
- function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
- var span = getErrorSpanForNode(sourceFile, node);
- return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
- }
- ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
- function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
- var sourceFile = getSourceFileOfNode(node);
- var span = getErrorSpanForNode(sourceFile, node);
- return {
- file: sourceFile,
- start: span.start,
- length: span.length,
- code: messageChain.code,
- category: messageChain.category,
- messageText: messageChain.next ? messageChain : messageChain.messageText,
- relatedInformation: relatedInformation
- };
- }
- ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
- function createDiagnosticForRange(sourceFile, range, message) {
- return {
- file: sourceFile,
- start: range.pos,
- length: range.end - range.pos,
- code: message.code,
- category: message.category,
- messageText: message.message,
- };
- }
- ts.createDiagnosticForRange = createDiagnosticForRange;
- function getSpanOfTokenAtPosition(sourceFile, 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());
- }
- ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
- function getErrorSpanForArrowFunction(sourceFile, node) {
- var pos = ts.skipTrivia(sourceFile.text, node.pos);
- if (node.body && node.body.kind === 223 /* 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);
- }
- }
- return ts.createTextSpanFromBounds(pos, node.end);
- }
- function getErrorSpanForNode(sourceFile, node) {
- var errorNode = node;
- switch (node.kind) {
- case 290 /* 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);
- // This list is a work in progress. Add missing node kinds to improve their error
- // spans.
- case 242 /* VariableDeclaration */:
- case 191 /* BindingElement */:
- case 245 /* ClassDeclaration */:
- case 214 /* ClassExpression */:
- case 246 /* InterfaceDeclaration */:
- case 249 /* ModuleDeclaration */:
- case 248 /* EnumDeclaration */:
- case 284 /* EnumMember */:
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 161 /* MethodDeclaration */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 247 /* TypeAliasDeclaration */:
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- errorNode = node.name;
- break;
- case 202 /* ArrowFunction */:
- return getErrorSpanForArrowFunction(sourceFile, node);
- case 277 /* CaseClause */:
- case 278 /* DefaultClause */:
- var start = ts.skipTrivia(sourceFile.text, node.pos);
- var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
- return ts.createTextSpanFromBounds(start, end);
- }
- 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);
- }
- ts.Debug.assert(!ts.isJSDoc(errorNode));
- var isMissing = nodeIsMissing(errorNode);
- var pos = isMissing || ts.isJsxText(node)
- ? 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");
- }
- else {
- 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");
- }
- return ts.createTextSpanFromBounds(pos, errorNode.end);
- }
- ts.getErrorSpanForNode = getErrorSpanForNode;
- function isExternalOrCommonJsModule(file) {
- return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
- }
- ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
- function isJsonSourceFile(file) {
- return file.scriptKind === 6 /* JSON */;
- }
- ts.isJsonSourceFile = isJsonSourceFile;
- function isEnumConst(node) {
- return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
- }
- ts.isEnumConst = isEnumConst;
- function isDeclarationReadonly(declaration) {
- return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
- }
- ts.isDeclarationReadonly = isDeclarationReadonly;
- function isVarConst(node) {
- return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
- }
- ts.isVarConst = isVarConst;
- function isLet(node) {
- return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
- }
- ts.isLet = isLet;
- function isSuperCall(n) {
- return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
- }
- ts.isSuperCall = isSuperCall;
- function isImportCall(n) {
- return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
- }
- ts.isImportCall = isImportCall;
- function isImportMeta(n) {
- return ts.isMetaProperty(n)
- && n.keywordToken === 96 /* ImportKeyword */
- && n.name.escapedText === "meta";
- }
- ts.isImportMeta = isImportMeta;
- function isLiteralImportTypeNode(n) {
- return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
- }
- ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
- function isPrologueDirective(node) {
- return node.kind === 226 /* ExpressionStatement */
- && node.expression.kind === 10 /* StringLiteral */;
- }
- ts.isPrologueDirective = isPrologueDirective;
- function isCustomPrologue(node) {
- return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
- }
- ts.isCustomPrologue = isCustomPrologue;
- function isHoistedFunction(node) {
- return isCustomPrologue(node)
- && ts.isFunctionDeclaration(node);
- }
- ts.isHoistedFunction = isHoistedFunction;
- function isHoistedVariable(node) {
- return ts.isIdentifier(node.name)
- && !node.initializer;
- }
- function isHoistedVariableStatement(node) {
- return isCustomPrologue(node)
- && ts.isVariableStatement(node)
- && ts.every(node.declarationList.declarations, isHoistedVariable);
- }
- ts.isHoistedVariableStatement = isHoistedVariableStatement;
- function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
- return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
- }
- ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
- function getJSDocCommentRanges(node, text) {
- var commentRanges = (node.kind === 156 /* Parameter */ ||
- node.kind === 155 /* TypeParameter */ ||
- node.kind === 201 /* FunctionExpression */ ||
- node.kind === 202 /* ArrowFunction */ ||
- node.kind === 200 /* 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 /* asterisk */ &&
- text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
- text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
- });
- }
- ts.getJSDocCommentRanges = getJSDocCommentRanges;
- ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/;
- var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/;
- ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
- var defaultLibReferenceRegEx = /^(\/\/\/\s*/;
- function isPartOfTypeNode(node) {
- if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
- return true;
- }
- switch (node.kind) {
- case 125 /* AnyKeyword */:
- case 148 /* UnknownKeyword */:
- case 140 /* NumberKeyword */:
- case 151 /* BigIntKeyword */:
- case 143 /* StringKeyword */:
- case 128 /* BooleanKeyword */:
- case 144 /* SymbolKeyword */:
- case 141 /* ObjectKeyword */:
- case 146 /* UndefinedKeyword */:
- case 137 /* NeverKeyword */:
- return true;
- case 110 /* VoidKeyword */:
- return node.parent.kind !== 205 /* VoidExpression */;
- case 216 /* ExpressionWithTypeArguments */:
- return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
- case 155 /* TypeParameter */:
- return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
- // Identifiers and qualified names may be type nodes, depending on their context. Climb
- // above them to find the lowest container
- case 75 /* Identifier */:
- // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
- if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
- node = node.parent;
- }
- else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
- node = node.parent;
- }
- // At this point, node is either a qualified name or an identifier
- ts.Debug.assert(node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */ || node.kind === 194 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
- // falls through
- case 153 /* QualifiedName */:
- case 194 /* PropertyAccessExpression */:
- case 104 /* ThisKeyword */: {
- var parent = node.parent;
- if (parent.kind === 172 /* TypeQuery */) {
- return false;
- }
- if (parent.kind === 188 /* ImportType */) {
- return !parent.isTypeOf;
- }
- // 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 (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
- return true;
- }
- switch (parent.kind) {
- case 216 /* ExpressionWithTypeArguments */:
- return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
- case 155 /* TypeParameter */:
- return node === parent.constraint;
- case 321 /* JSDocTemplateTag */:
- return node === parent.constraint;
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- case 156 /* Parameter */:
- case 242 /* VariableDeclaration */:
- return node === parent.type;
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- case 162 /* Constructor */:
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- return node === parent.type;
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- return node === parent.type;
- case 199 /* TypeAssertionExpression */:
- return node === parent.type;
- case 196 /* CallExpression */:
- case 197 /* NewExpression */:
- return ts.contains(parent.typeArguments, node);
- case 198 /* TaggedTemplateExpression */:
- // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
- return false;
- }
- }
- }
- return false;
- }
- ts.isPartOfTypeNode = isPartOfTypeNode;
- function isChildOfNodeWithKind(node, kind) {
- while (node) {
- if (node.kind === kind) {
- return true;
- }
- node = node.parent;
- }
- 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 235 /* ReturnStatement */:
- return visitor(node);
- case 251 /* CaseBlock */:
- case 223 /* Block */:
- case 227 /* IfStatement */:
- case 228 /* DoStatement */:
- case 229 /* WhileStatement */:
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- case 236 /* WithStatement */:
- case 237 /* SwitchStatement */:
- case 277 /* CaseClause */:
- case 278 /* DefaultClause */:
- case 238 /* LabeledStatement */:
- case 240 /* TryStatement */:
- case 280 /* CatchClause */:
- return ts.forEachChild(node, traverse);
- }
- }
- }
- ts.forEachReturnStatement = forEachReturnStatement;
- function forEachYieldExpression(body, visitor) {
- return traverse(body);
- function traverse(node) {
- switch (node.kind) {
- case 212 /* YieldExpression */:
- visitor(node);
- var operand = node.expression;
- if (operand) {
- traverse(operand);
- }
- return;
- case 248 /* EnumDeclaration */:
- case 246 /* InterfaceDeclaration */:
- case 249 /* ModuleDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- // These are not allowed inside a generator now, but eventually they may be allowed
- // as local types. Regardless, skip them to avoid the work.
- return;
- default:
- if (ts.isFunctionLike(node)) {
- if (node.name && node.name.kind === 154 /* 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 === 174 /* ArrayType */) {
- return node.elementType;
- }
- else if (node && node.kind === 169 /* TypeReference */) {
- return ts.singleOrUndefined(node.typeArguments);
- }
- else {
- return undefined;
- }
- }
- ts.getRestParameterElementType = getRestParameterElementType;
- function getMembersOfDeclaration(node) {
- switch (node.kind) {
- case 246 /* InterfaceDeclaration */:
- case 245 /* ClassDeclaration */:
- case 214 /* ClassExpression */:
- case 173 /* TypeLiteral */:
- return node.members;
- case 193 /* ObjectLiteralExpression */:
- return node.properties;
- }
- }
- ts.getMembersOfDeclaration = getMembersOfDeclaration;
- function isVariableLike(node) {
- if (node) {
- switch (node.kind) {
- case 191 /* BindingElement */:
- case 284 /* EnumMember */:
- case 156 /* Parameter */:
- case 281 /* PropertyAssignment */:
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- case 282 /* ShorthandPropertyAssignment */:
- case 242 /* VariableDeclaration */:
- return true;
- }
- }
- return false;
- }
- ts.isVariableLike = isVariableLike;
- function isVariableLikeOrAccessor(node) {
- return isVariableLike(node) || ts.isAccessor(node);
- }
- ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
- function isVariableDeclarationInVariableStatement(node) {
- return node.parent.kind === 243 /* VariableDeclarationList */
- && node.parent.parent.kind === 225 /* VariableStatement */;
- }
- ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
- function isValidESSymbolDeclaration(node) {
- return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
- ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
- ts.isPropertySignature(node) && hasReadonlyModifier(node);
- }
- ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
- function introducesArgumentsExoticObject(node) {
- switch (node.kind) {
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- return true;
- }
- return false;
- }
- ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
- function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
- while (true) {
- if (beforeUnwrapLabelCallback) {
- beforeUnwrapLabelCallback(node);
- }
- if (node.statement.kind !== 238 /* LabeledStatement */) {
- return node.statement;
- }
- node = node.statement;
- }
- }
- ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
- function isFunctionBlock(node) {
- return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
- }
- ts.isFunctionBlock = isFunctionBlock;
- function isObjectLiteralMethod(node) {
- return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
- }
- ts.isObjectLiteralMethod = isObjectLiteralMethod;
- function isObjectLiteralOrClassExpressionMethod(node) {
- return node.kind === 161 /* MethodDeclaration */ &&
- (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
- node.parent.kind === 214 /* ClassExpression */);
- }
- ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
- function isIdentifierTypePredicate(predicate) {
- return predicate && predicate.kind === 1 /* Identifier */;
- }
- ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
- function isThisTypePredicate(predicate) {
- return predicate && predicate.kind === 0 /* This */;
- }
- ts.isThisTypePredicate = isThisTypePredicate;
- function getPropertyAssignment(objectLiteral, key, key2) {
- return objectLiteral.properties.filter(function (property) {
- if (property.kind === 281 /* PropertyAssignment */) {
- var propName = getTextOfPropertyName(property.name);
- return key === propName || (!!key2 && key2 === propName);
- }
- return false;
- });
- }
- ts.getPropertyAssignment = getPropertyAssignment;
- function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
- if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
- var expression = tsConfigSourceFile.statements[0].expression;
- return ts.tryCast(expression, ts.isObjectLiteralExpression);
- }
- }
- ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
- function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
- return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
- return ts.isArrayLiteralExpression(property.initializer) ?
- ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
- undefined;
- });
- }
- ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
- function getTsConfigPropArray(tsConfigSourceFile, propKey) {
- var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
- return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
- }
- ts.getTsConfigPropArray = getTsConfigPropArray;
- function getContainingFunction(node) {
- return findAncestor(node.parent, ts.isFunctionLike);
- }
- ts.getContainingFunction = getContainingFunction;
- function getContainingFunctionDeclaration(node) {
- return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
- }
- ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
- function getContainingClass(node) {
- return findAncestor(node.parent, ts.isClassLike);
- }
- ts.getContainingClass = getContainingClass;
- function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 290 /* SourceFile */);
- while (true) {
- node = node.parent;
- if (!node) {
- 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 154 /* 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 157 /* Decorator */:
- // Decorators are always applied outside of the body of a class or method.
- if (node.parent.kind === 156 /* 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 202 /* ArrowFunction */:
- if (!includeArrowFunctions) {
- continue;
- }
- // falls through
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 249 /* ModuleDeclaration */:
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- case 248 /* EnumDeclaration */:
- case 290 /* SourceFile */:
- return node;
- }
- }
- }
- ts.getThisContainer = getThisContainer;
- function getNewTargetContainer(node) {
- var container = getThisContainer(node, /*includeArrowFunctions*/ false);
- if (container) {
- switch (container.kind) {
- case 162 /* Constructor */:
- case 244 /* FunctionDeclaration */:
- case 201 /* 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;
- if (!node) {
- return node;
- }
- switch (node.kind) {
- case 154 /* ComputedPropertyName */:
- node = node.parent;
- break;
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- if (!stopOnFunctions) {
- continue;
- }
- // falls through
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- return node;
- case 157 /* Decorator */:
- // Decorators are always applied outside of the body of a class or method.
- if (node.parent.kind === 156 /* 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;
- }
- }
- }
- ts.getSuperContainer = getSuperContainer;
- function getImmediatelyInvokedFunctionExpression(func) {
- if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
- var prev = func;
- var parent = func.parent;
- while (parent.kind === 200 /* ParenthesizedExpression */) {
- prev = parent;
- parent = parent.parent;
- }
- if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
- return parent;
- }
- }
- }
- ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
- function isSuperOrSuperProperty(node) {
- return node.kind === 102 /* SuperKeyword */
- || isSuperProperty(node);
- }
- ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
- /**
- * Determines whether a node is a property or element access expression for `super`.
- */
- function isSuperProperty(node) {
- var kind = node.kind;
- return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
- && node.expression.kind === 102 /* 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 === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
- && node.expression.kind === 104 /* ThisKeyword */;
- }
- ts.isThisProperty = isThisProperty;
- function getEntityNameFromTypeNode(node) {
- switch (node.kind) {
- case 169 /* TypeReference */:
- return node.typeName;
- case 216 /* ExpressionWithTypeArguments */:
- return isEntityNameExpression(node.expression)
- ? node.expression
- : undefined;
- case 75 /* Identifier */:
- case 153 /* QualifiedName */:
- return node;
- }
- return undefined;
- }
- ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
- function getInvokedExpression(node) {
- switch (node.kind) {
- case 198 /* TaggedTemplateExpression */:
- return node.tag;
- case 268 /* JsxOpeningElement */:
- case 267 /* JsxSelfClosingElement */:
- return node.tagName;
- default:
- return node.expression;
- }
- }
- ts.getInvokedExpression = getInvokedExpression;
- function nodeCanBeDecorated(node, parent, grandparent) {
- // private names cannot be used with decorators yet
- if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
- return false;
- }
- switch (node.kind) {
- case 245 /* ClassDeclaration */:
- // classes are valid targets
- return true;
- case 159 /* PropertyDeclaration */:
- // property declarations are valid if their parent is a class declaration.
- return parent.kind === 245 /* ClassDeclaration */;
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 161 /* 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 === 245 /* ClassDeclaration */;
- case 156 /* 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 === 162 /* Constructor */
- || parent.kind === 161 /* MethodDeclaration */
- || parent.kind === 164 /* SetAccessor */)
- && grandparent.kind === 245 /* ClassDeclaration */;
- }
- return false;
- }
- ts.nodeCanBeDecorated = nodeCanBeDecorated;
- function nodeIsDecorated(node, parent, grandparent) {
- return node.decorators !== undefined
- && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
- }
- ts.nodeIsDecorated = nodeIsDecorated;
- function nodeOrChildIsDecorated(node, parent, grandparent) {
- return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
- }
- ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
- function childIsDecorated(node, parent) {
- switch (node.kind) {
- case 245 /* ClassDeclaration */:
- return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
- case 161 /* MethodDeclaration */:
- case 164 /* SetAccessor */:
- return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
- default:
- return false;
- }
- }
- ts.childIsDecorated = childIsDecorated;
- function isJSXTagName(node) {
- var parent = node.parent;
- if (parent.kind === 268 /* JsxOpeningElement */ ||
- parent.kind === 267 /* JsxSelfClosingElement */ ||
- parent.kind === 269 /* JsxClosingElement */) {
- return parent.tagName === node;
- }
- return false;
- }
- ts.isJSXTagName = isJSXTagName;
- function isExpressionNode(node) {
- switch (node.kind) {
- case 102 /* SuperKeyword */:
- case 100 /* NullKeyword */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- case 13 /* RegularExpressionLiteral */:
- case 192 /* ArrayLiteralExpression */:
- case 193 /* ObjectLiteralExpression */:
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- case 196 /* CallExpression */:
- case 197 /* NewExpression */:
- case 198 /* TaggedTemplateExpression */:
- case 217 /* AsExpression */:
- case 199 /* TypeAssertionExpression */:
- case 218 /* NonNullExpression */:
- case 200 /* ParenthesizedExpression */:
- case 201 /* FunctionExpression */:
- case 214 /* ClassExpression */:
- case 202 /* ArrowFunction */:
- case 205 /* VoidExpression */:
- case 203 /* DeleteExpression */:
- case 204 /* TypeOfExpression */:
- case 207 /* PrefixUnaryExpression */:
- case 208 /* PostfixUnaryExpression */:
- case 209 /* BinaryExpression */:
- case 210 /* ConditionalExpression */:
- case 213 /* SpreadElement */:
- case 211 /* TemplateExpression */:
- case 215 /* OmittedExpression */:
- case 266 /* JsxElement */:
- case 267 /* JsxSelfClosingElement */:
- case 270 /* JsxFragment */:
- case 212 /* YieldExpression */:
- case 206 /* AwaitExpression */:
- case 219 /* MetaProperty */:
- return true;
- case 153 /* QualifiedName */:
- while (node.parent.kind === 153 /* QualifiedName */) {
- node = node.parent;
- }
- return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
- case 75 /* Identifier */:
- if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
- return true;
- }
- // falls through
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 104 /* ThisKeyword */:
- return isInExpressionContext(node);
- default:
- return false;
- }
- }
- ts.isExpressionNode = isExpressionNode;
- function isInExpressionContext(node) {
- var parent = node.parent;
- switch (parent.kind) {
- case 242 /* VariableDeclaration */:
- case 156 /* Parameter */:
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- case 284 /* EnumMember */:
- case 281 /* PropertyAssignment */:
- case 191 /* BindingElement */:
- return parent.initializer === node;
- case 226 /* ExpressionStatement */:
- case 227 /* IfStatement */:
- case 228 /* DoStatement */:
- case 229 /* WhileStatement */:
- case 235 /* ReturnStatement */:
- case 236 /* WithStatement */:
- case 237 /* SwitchStatement */:
- case 277 /* CaseClause */:
- case 239 /* ThrowStatement */:
- return parent.expression === node;
- case 230 /* ForStatement */:
- var forStatement = parent;
- return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
- forStatement.condition === node ||
- forStatement.incrementor === node;
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- var forInStatement = parent;
- return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
- forInStatement.expression === node;
- case 199 /* TypeAssertionExpression */:
- case 217 /* AsExpression */:
- return node === parent.expression;
- case 221 /* TemplateSpan */:
- return node === parent.expression;
- case 154 /* ComputedPropertyName */:
- return node === parent.expression;
- case 157 /* Decorator */:
- case 276 /* JsxExpression */:
- case 275 /* JsxSpreadAttribute */:
- case 283 /* SpreadAssignment */:
- return true;
- case 216 /* ExpressionWithTypeArguments */:
- return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
- case 282 /* ShorthandPropertyAssignment */:
- return parent.objectAssignmentInitializer === node;
- default:
- return isExpressionNode(parent);
- }
- }
- ts.isInExpressionContext = isInExpressionContext;
- function isPartOfTypeQuery(node) {
- while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
- node = node.parent;
- }
- return node.kind === 172 /* TypeQuery */;
- }
- ts.isPartOfTypeQuery = isPartOfTypeQuery;
- function isExternalModuleImportEqualsDeclaration(node) {
- return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
- }
- ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
- function getExternalModuleImportEqualsDeclarationExpression(node) {
- ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
- return node.moduleReference.expression;
- }
- ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
- function isInternalModuleImportEqualsDeclaration(node) {
- return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
- }
- ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
- function isSourceFileJS(file) {
- return isInJSFile(file);
- }
- ts.isSourceFileJS = isSourceFileJS;
- function isSourceFileNotJS(file) {
- return !isInJSFile(file);
- }
- ts.isSourceFileNotJS = isSourceFileNotJS;
- function isInJSFile(node) {
- return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
- }
- ts.isInJSFile = isInJSFile;
- function isInJsonFile(node) {
- return !!node && !!(node.flags & 33554432 /* JsonFile */);
- }
- ts.isInJsonFile = isInJsonFile;
- function isSourceFileNotJson(file) {
- return !isJsonSourceFile(file);
- }
- ts.isSourceFileNotJson = isSourceFileNotJson;
- function isInJSDoc(node) {
- return !!node && !!(node.flags & 4194304 /* JSDoc */);
- }
- ts.isInJSDoc = isInJSDoc;
- function isJSDocIndexSignature(node) {
- return ts.isTypeReferenceNode(node) &&
- ts.isIdentifier(node.typeName) &&
- node.typeName.escapedText === "Object" &&
- node.typeArguments && node.typeArguments.length === 2 &&
- (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
- }
- ts.isJSDocIndexSignature = isJSDocIndexSignature;
- function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
- if (callExpression.kind !== 196 /* CallExpression */) {
- return false;
- }
- var _a = callExpression, expression = _a.expression, args = _a.arguments;
- if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
- return false;
- }
- if (args.length !== 1) {
- return false;
- }
- var arg = args[0];
- return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
- }
- ts.isRequireCall = isRequireCall;
- function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
- return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
- }
- ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
- function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
- if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
- return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
- }
- ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
- function isSingleOrDoubleQuote(charCode) {
- return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
- }
- ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
- function isStringDoubleQuoted(str, sourceFile) {
- return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
- }
- ts.isStringDoubleQuoted = isStringDoubleQuoted;
- function getDeclarationOfExpando(node) {
- if (!node.parent) {
- return undefined;
- }
- var name;
- var decl;
- if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
- if (!isInJSFile(node) && !isVarConst(node.parent)) {
- return undefined;
- }
- name = node.parent.name;
- decl = node.parent;
- }
- else if (ts.isBinaryExpression(node.parent)) {
- var parentNode = node.parent;
- var parentNodeOperator = node.parent.operatorToken.kind;
- if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
- name = parentNode.left;
- decl = name;
- }
- else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
- if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
- name = parentNode.parent.name;
- decl = parentNode.parent;
- }
- else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
- name = parentNode.parent.left;
- decl = name;
- }
- if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
- return undefined;
- }
- }
- }
- if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
- return undefined;
- }
- return decl;
- }
- ts.getDeclarationOfExpando = getDeclarationOfExpando;
- function isAssignmentDeclaration(decl) {
- return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
- }
- ts.isAssignmentDeclaration = isAssignmentDeclaration;
- /** Get the initializer, taking into account defaulted Javascript initializers */
- function getEffectiveInitializer(node) {
- if (isInJSFile(node) && node.initializer &&
- ts.isBinaryExpression(node.initializer) &&
- (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
- 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 getExpandoInitializer). */
- function getDeclaredExpandoInitializer(node) {
- var init = getEffectiveInitializer(node);
- return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
- }
- ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
- function hasExpandoValueProperty(node, isPrototypeAssignment) {
- return ts.forEach(node.properties, function (p) {
- return ts.isPropertyAssignment(p) &&
- ts.isIdentifier(p.name) &&
- p.name.escapedText === "value" &&
- p.initializer &&
- getExpandoInitializer(p.initializer, isPrototypeAssignment);
- });
- }
- /**
- * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
- * We treat the right hand side of assignments with container-like initalizers as declarations.
- */
- function getAssignedExpandoInitializer(node) {
- if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
- var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
- return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
- getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
- }
- if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
- var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
- if (result) {
- return result;
- }
- }
- }
- ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
- /**
- * Recognized expando 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 getExpandoInitializer(initializer, isPrototypeAssignment) {
- if (ts.isCallExpression(initializer)) {
- var e = skipParentheses(initializer.expression);
- return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
- }
- if (initializer.kind === 201 /* FunctionExpression */ ||
- initializer.kind === 214 /* ClassExpression */ ||
- initializer.kind === 202 /* ArrowFunction */) {
- return initializer;
- }
- if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
- return initializer;
- }
- }
- ts.getExpandoInitializer = getExpandoInitializer;
- /**
- * A defaulted expando initializer matches the pattern
- * `Lhs = Lhs || ExpandoInitializer`
- * or `var Lhs = Lhs || ExpandoInitializer`
- *
- * 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 getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
- var e = ts.isBinaryExpression(initializer)
- && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
- && getExpandoInitializer(initializer.right, isPrototypeAssignment);
- if (e && isSameEntityName(name, initializer.left)) {
- return e;
- }
- }
- function isDefaultedExpandoInitializer(node) {
- var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
- ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
- undefined;
- return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
- }
- ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
- /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
- function getNameOfExpando(node) {
- if (ts.isBinaryExpression(node.parent)) {
- var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
- if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
- return parent.left;
- }
- }
- else if (ts.isVariableDeclaration(node.parent)) {
- return node.parent.name;
- }
- }
- ts.getNameOfExpando = getNameOfExpando;
- /**
- * 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 (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
- return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
- }
- if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
- (initializer.expression.kind === 104 /* ThisKeyword */ ||
- ts.isIdentifier(initializer.expression) &&
- (initializer.expression.escapedText === "window" ||
- initializer.expression.escapedText === "self" ||
- initializer.expression.escapedText === "global"))) {
- var nameOrArgument = getNameOrArgument(initializer);
- if (ts.isPrivateIdentifier(nameOrArgument)) {
- ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
- }
- return isSameEntityName(name, nameOrArgument);
- }
- if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
- return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
- && isSameEntityName(name.expression, initializer.expression);
- }
- return false;
- }
- function getRightMostAssignedExpression(node) {
- while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
- node = node.right;
- }
- return node;
- }
- ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
- function isExportsIdentifier(node) {
- return ts.isIdentifier(node) && node.escapedText === "exports";
- }
- ts.isExportsIdentifier = isExportsIdentifier;
- function isModuleIdentifier(node) {
- return ts.isIdentifier(node) && node.escapedText === "module";
- }
- ts.isModuleIdentifier = isModuleIdentifier;
- function isModuleExportsAccessExpression(node) {
- return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
- && isModuleIdentifier(node.expression)
- && getElementOrPropertyAccessName(node) === "exports";
- }
- ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
- /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
- /// assignments we treat as special in the binder
- function getAssignmentDeclarationKind(expr) {
- var special = getAssignmentDeclarationKindWorker(expr);
- return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
- }
- ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
- function isBindableObjectDefinePropertyCall(expr) {
- return ts.length(expr.arguments) === 3 &&
- ts.isPropertyAccessExpression(expr.expression) &&
- ts.isIdentifier(expr.expression.expression) &&
- ts.idText(expr.expression.expression) === "Object" &&
- ts.idText(expr.expression.name) === "defineProperty" &&
- isStringOrNumericLiteralLike(expr.arguments[1]) &&
- isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
- }
- ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
- /** x.y OR x[0] */
- function isLiteralLikeAccess(node) {
- return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
- }
- ts.isLiteralLikeAccess = isLiteralLikeAccess;
- /** x[0] OR x['a'] OR x[Symbol.y] */
- function isLiteralLikeElementAccess(node) {
- return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
- isWellKnownSymbolSyntactically(node.argumentExpression));
- }
- ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
- /** Any series of property and element accesses. */
- function isBindableStaticAccessExpression(node, excludeThisKeyword) {
- return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
- || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
- }
- ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
- /** Any series of property and element accesses, ending in a literal element access */
- function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
- return isLiteralLikeElementAccess(node)
- && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
- isEntityNameExpression(node.expression) ||
- isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
- }
- ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
- function isBindableStaticNameExpression(node, excludeThisKeyword) {
- return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
- }
- ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
- function getNameOrArgument(expr) {
- if (ts.isPropertyAccessExpression(expr)) {
- return expr.name;
- }
- return expr.argumentExpression;
- }
- ts.getNameOrArgument = getNameOrArgument;
- function getAssignmentDeclarationKindWorker(expr) {
- if (ts.isCallExpression(expr)) {
- if (!isBindableObjectDefinePropertyCall(expr)) {
- return 0 /* None */;
- }
- var entityName = expr.arguments[0];
- if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
- return 8 /* ObjectDefinePropertyExports */;
- }
- if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
- return 9 /* ObjectDefinePrototypeProperty */;
- }
- return 7 /* ObjectDefinePropertyValue */;
- }
- if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
- return 0 /* None */;
- }
- if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
- // F.prototype = { ... }
- return 6 /* Prototype */;
- }
- return getAssignmentDeclarationPropertyAccessKind(expr.left);
- }
- /**
- * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
- * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
- */
- /* @internal */
- function getElementOrPropertyAccessArgumentExpressionOrName(node) {
- if (ts.isPropertyAccessExpression(node)) {
- return node.name;
- }
- var arg = skipParentheses(node.argumentExpression);
- if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
- return arg;
- }
- return node;
- }
- ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
- function getElementOrPropertyAccessName(node) {
- var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
- if (name) {
- if (ts.isIdentifier(name)) {
- return name.escapedText;
- }
- if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
- return ts.escapeLeadingUnderscores(name.text);
- }
- }
- if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
- return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
- }
- return undefined;
- }
- ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
- function getAssignmentDeclarationPropertyAccessKind(lhs) {
- if (lhs.expression.kind === 104 /* ThisKeyword */) {
- return 4 /* ThisProperty */;
- }
- else if (isModuleExportsAccessExpression(lhs)) {
- // module.exports = expr
- return 2 /* ModuleExports */;
- }
- else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
- if (isPrototypeAccess(lhs.expression)) {
- // F.G....prototype.x = expr
- return 3 /* PrototypeProperty */;
- }
- var nextToLast = lhs;
- while (!ts.isIdentifier(nextToLast.expression)) {
- nextToLast = nextToLast.expression;
- }
- var id = nextToLast.expression;
- if ((id.escapedText === "exports" ||
- id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
- // ExportsProperty does not support binding with computed names
- isBindableStaticAccessExpression(lhs)) {
- // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
- return 1 /* ExportsProperty */;
- }
- if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
- // F.G...x = expr
- return 5 /* Property */;
- }
- }
- return 0 /* None */;
- }
- ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
- function getInitializerOfBinaryExpression(expr) {
- while (ts.isBinaryExpression(expr.right)) {
- expr = expr.right;
- }
- return expr.right;
- }
- ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
- function isPrototypePropertyAssignment(node) {
- return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
- }
- ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
- function isSpecialPropertyDeclaration(expr) {
- return isInJSFile(expr) &&
- expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
- (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
- !!ts.getJSDocTypeTag(expr.parent);
- }
- ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
- function setValueDeclaration(symbol, node) {
- var valueDeclaration = symbol.valueDeclaration;
- if (!valueDeclaration ||
- !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
- (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
- (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
- // other kinds of value declarations take precedence over modules and assignment declarations
- symbol.valueDeclaration = node;
- }
- }
- ts.setValueDeclaration = setValueDeclaration;
- function isFunctionSymbol(symbol) {
- if (!symbol || !symbol.valueDeclaration) {
- return false;
- }
- var decl = symbol.valueDeclaration;
- return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
- }
- ts.isFunctionSymbol = isFunctionSymbol;
- function importFromModuleSpecifier(node) {
- return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
- }
- ts.importFromModuleSpecifier = importFromModuleSpecifier;
- function tryGetImportFromModuleSpecifier(node) {
- switch (node.parent.kind) {
- case 254 /* ImportDeclaration */:
- case 260 /* ExportDeclaration */:
- return node.parent;
- case 265 /* ExternalModuleReference */:
- return node.parent.parent;
- case 196 /* CallExpression */:
- return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
- case 187 /* LiteralType */:
- ts.Debug.assert(ts.isStringLiteral(node));
- return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
- default:
- return undefined;
- }
- }
- ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
- function getExternalModuleName(node) {
- switch (node.kind) {
- case 254 /* ImportDeclaration */:
- case 260 /* ExportDeclaration */:
- return node.moduleSpecifier;
- case 253 /* ImportEqualsDeclaration */:
- return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
- case 188 /* ImportType */:
- return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
- default:
- return ts.Debug.assertNever(node);
- }
- }
- ts.getExternalModuleName = getExternalModuleName;
- function getNamespaceDeclarationNode(node) {
- switch (node.kind) {
- case 254 /* ImportDeclaration */:
- return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
- case 253 /* ImportEqualsDeclaration */:
- return node;
- case 260 /* ExportDeclaration */:
- return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
- default:
- return ts.Debug.assertNever(node);
- }
- }
- ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
- function isDefaultImport(node) {
- return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
- }
- ts.isDefaultImport = isDefaultImport;
- function forEachImportClauseDeclaration(node, action) {
- if (node.name) {
- var result = action(node);
- if (result)
- return result;
- }
- if (node.namedBindings) {
- var result = ts.isNamespaceImport(node.namedBindings)
- ? action(node.namedBindings)
- : ts.forEach(node.namedBindings.elements, action);
- if (result)
- return result;
- }
- }
- ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
- function hasQuestionToken(node) {
- if (node) {
- switch (node.kind) {
- case 156 /* Parameter */:
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 282 /* ShorthandPropertyAssignment */:
- case 281 /* PropertyAssignment */:
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- return node.questionToken !== undefined;
- }
- }
- return false;
- }
- ts.hasQuestionToken = hasQuestionToken;
- function isJSDocConstructSignature(node) {
- var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
- var name = ts.tryCast(param && param.name, ts.isIdentifier);
- return !!name && name.escapedText === "new";
- }
- ts.isJSDocConstructSignature = isJSDocConstructSignature;
- function isJSDocTypeAlias(node) {
- return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
- }
- ts.isJSDocTypeAlias = isJSDocTypeAlias;
- function isTypeAlias(node) {
- return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
- }
- ts.isTypeAlias = isTypeAlias;
- function getSourceOfAssignment(node) {
- return ts.isExpressionStatement(node) &&
- ts.isBinaryExpression(node.expression) &&
- node.expression.operatorToken.kind === 62 /* EqualsToken */
- ? getRightMostAssignedExpression(node.expression)
- : undefined;
- }
- function getSourceOfDefaultedAssignment(node) {
- return ts.isExpressionStatement(node) &&
- ts.isBinaryExpression(node.expression) &&
- getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
- ts.isBinaryExpression(node.expression.right) &&
- (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
- ? node.expression.right.right
- : undefined;
- }
- function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
- switch (node.kind) {
- case 225 /* VariableStatement */:
- var v = getSingleVariableOfVariableStatement(node);
- return v && v.initializer;
- case 159 /* PropertyDeclaration */:
- return node.initializer;
- case 281 /* PropertyAssignment */:
- return node.initializer;
- }
- }
- ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
- function getSingleVariableOfVariableStatement(node) {
- return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
- }
- function getNestedModuleDeclaration(node) {
- return ts.isModuleDeclaration(node) &&
- node.body &&
- node.body.kind === 249 /* ModuleDeclaration */
- ? node.body
- : undefined;
- }
- function getJSDocCommentsAndTags(hostNode) {
- var result;
- // Pull parameter comments from declaring function as well
- if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
- result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
- }
- var node = hostNode;
- while (node && node.parent) {
- if (ts.hasJSDocNodes(node)) {
- result = ts.append(result, ts.last(node.jsDoc));
- }
- if (node.kind === 156 /* Parameter */) {
- result = ts.addRange(result, ts.getJSDocParameterTags(node));
- break;
- }
- if (node.kind === 155 /* TypeParameter */) {
- result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
- break;
- }
- node = getNextJSDocCommentLocation(node);
- }
- return result || ts.emptyArray;
- }
- ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
- function getNextJSDocCommentLocation(node) {
- var parent = node.parent;
- if (parent.kind === 281 /* PropertyAssignment */ ||
- parent.kind === 259 /* ExportAssignment */ ||
- parent.kind === 159 /* PropertyDeclaration */ ||
- parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
- getNestedModuleDeclaration(parent) ||
- ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
- return 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; }
- else if (parent.parent &&
- (getSingleVariableOfVariableStatement(parent.parent) === node ||
- ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
- return parent.parent;
- }
- else if (parent.parent && parent.parent.parent &&
- (getSingleVariableOfVariableStatement(parent.parent.parent) ||
- getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
- getSourceOfDefaultedAssignment(parent.parent.parent))) {
- return parent.parent.parent;
- }
- }
- /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
- function getParameterSymbolFromJSDoc(node) {
- if (node.symbol) {
- return node.symbol;
- }
- if (!ts.isIdentifier(node.name)) {
- return undefined;
- }
- var name = node.name.escapedText;
- var decl = getHostSignatureFromJSDoc(node);
- if (!decl) {
- return undefined;
- }
- var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
- return parameter && parameter.symbol;
- }
- ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
- function getHostSignatureFromJSDoc(node) {
- var host = getEffectiveJSDocHost(node);
- return host && ts.isFunctionLike(host) ? host : undefined;
- }
- ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
- function getEffectiveJSDocHost(node) {
- var host = getJSDocHost(node);
- var decl = getSourceOfDefaultedAssignment(host) ||
- getSourceOfAssignment(host) ||
- getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
- getSingleVariableOfVariableStatement(host) ||
- getNestedModuleDeclaration(host) ||
- host;
- return decl;
- }
- ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
- /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
- function getJSDocHost(node) {
- return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
- }
- ts.getJSDocHost = getJSDocHost;
- function getTypeParameterFromJsDoc(node) {
- var name = node.name.escapedText;
- var typeParameters = node.parent.parent.parent.typeParameters;
- return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
- }
- ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
- function hasRestParameter(s) {
- var last = ts.lastOrUndefined(s.parameters);
- return !!last && isRestParameter(last);
- }
- 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 === 301 /* JSDocVariadicType */;
- }
- ts.isRestParameter = isRestParameter;
- function hasTypeArguments(node) {
- return !!node.typeArguments;
- }
- ts.hasTypeArguments = hasTypeArguments;
- var AssignmentKind;
- (function (AssignmentKind) {
- AssignmentKind[AssignmentKind["None"] = 0] = "None";
- AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
- AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
- })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
- function getAssignmentTargetKind(node) {
- var parent = node.parent;
- while (true) {
- switch (parent.kind) {
- case 209 /* BinaryExpression */:
- var binaryOperator = parent.operatorToken.kind;
- return isAssignmentOperator(binaryOperator) && parent.left === node ?
- binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
- 0 /* None */;
- case 207 /* PrefixUnaryExpression */:
- case 208 /* PostfixUnaryExpression */:
- var unaryOperator = parent.operator;
- return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
- case 200 /* ParenthesizedExpression */:
- case 192 /* ArrayLiteralExpression */:
- case 213 /* SpreadElement */:
- case 218 /* NonNullExpression */:
- node = parent;
- break;
- case 282 /* ShorthandPropertyAssignment */:
- if (parent.name !== node) {
- return 0 /* None */;
- }
- node = parent.parent;
- break;
- case 281 /* PropertyAssignment */:
- if (parent.name === node) {
- return 0 /* None */;
- }
- node = parent.parent;
- break;
- default:
- 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 /* 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 223 /* Block */:
- case 225 /* VariableStatement */:
- case 236 /* WithStatement */:
- case 227 /* IfStatement */:
- case 237 /* SwitchStatement */:
- case 251 /* CaseBlock */:
- case 277 /* CaseClause */:
- case 278 /* DefaultClause */:
- case 238 /* LabeledStatement */:
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- case 228 /* DoStatement */:
- case 229 /* WhileStatement */:
- case 240 /* TryStatement */:
- case 280 /* CatchClause */:
- return true;
- }
- return false;
- }
- ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
- function isValueSignatureDeclaration(node) {
- return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
- }
- ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
- function walkUp(node, kind) {
- while (node && node.kind === kind) {
- node = node.parent;
- }
- return node;
- }
- function walkUpParenthesizedTypes(node) {
- return walkUp(node, 182 /* ParenthesizedType */);
- }
- ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
- function walkUpParenthesizedExpressions(node) {
- return walkUp(node, 200 /* ParenthesizedExpression */);
- }
- ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
- function skipParentheses(node) {
- return ts.skipOuterExpressions(node, 1 /* Parentheses */);
- }
- ts.skipParentheses = skipParentheses;
- function skipParenthesesUp(node) {
- while (node.kind === 200 /* ParenthesizedExpression */) {
- node = node.parent;
- }
- return node;
- }
- // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
- function isDeleteTarget(node) {
- if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
- return false;
- }
- node = walkUpParenthesizedExpressions(node.parent);
- return node && node.kind === 203 /* DeleteExpression */;
- }
- ts.isDeleteTarget = isDeleteTarget;
- function isNodeDescendantOf(node, ancestor) {
- while (node) {
- if (node === ancestor)
- return true;
- node = node.parent;
- }
- 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 getDeclarationFromName(name) {
- var parent = name.parent;
- switch (name.kind) {
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 8 /* NumericLiteral */:
- if (ts.isComputedPropertyName(parent))
- return parent.parent;
- // falls through
- case 75 /* Identifier */:
- if (ts.isDeclaration(parent)) {
- return parent.name === name ? parent : undefined;
- }
- else if (ts.isQualifiedName(parent)) {
- var tag = parent.parent;
- return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
- }
- else {
- var binExp = parent.parent;
- return ts.isBinaryExpression(binExp) &&
- getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
- (binExp.left.symbol || binExp.symbol) &&
- ts.getNameOfDeclaration(binExp) === name
- ? binExp
- : undefined;
- }
- case 76 /* PrivateIdentifier */:
- return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
- default:
- return undefined;
- }
- }
- ts.getDeclarationFromName = getDeclarationFromName;
- function isLiteralComputedPropertyDeclarationName(node) {
- return isStringOrNumericLiteralLike(node) &&
- node.parent.kind === 154 /* 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 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 284 /* EnumMember */:
- case 281 /* PropertyAssignment */:
- case 194 /* PropertyAccessExpression */:
- // Name in member declaration or property name in property access
- return parent.name === node;
- case 153 /* QualifiedName */:
- // Name on right hand side of dot in a type query or type reference
- if (parent.right === node) {
- while (parent.kind === 153 /* QualifiedName */) {
- parent = parent.parent;
- }
- return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
- }
- return false;
- case 191 /* BindingElement */:
- case 258 /* ImportSpecifier */:
- // Property name in binding element or import specifier
- return parent.propertyName === node;
- case 263 /* ExportSpecifier */:
- case 273 /* 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 * as ns from ...
- // export =
- // export default
- // module.exports =
- // {}
- // {name: }
- function isAliasSymbolDeclaration(node) {
- return node.kind === 253 /* ImportEqualsDeclaration */ ||
- node.kind === 252 /* NamespaceExportDeclaration */ ||
- node.kind === 255 /* ImportClause */ && !!node.name ||
- node.kind === 256 /* NamespaceImport */ ||
- node.kind === 262 /* NamespaceExport */ ||
- node.kind === 258 /* ImportSpecifier */ ||
- node.kind === 263 /* ExportSpecifier */ ||
- node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
- ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
- ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
- node.kind === 282 /* ShorthandPropertyAssignment */ ||
- node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
- }
- ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
- function getAliasDeclarationFromName(node) {
- switch (node.parent.kind) {
- case 255 /* ImportClause */:
- case 258 /* ImportSpecifier */:
- case 256 /* NamespaceImport */:
- case 263 /* ExportSpecifier */:
- case 259 /* ExportAssignment */:
- case 253 /* ImportEqualsDeclaration */:
- return node.parent;
- case 153 /* QualifiedName */:
- do {
- node = node.parent;
- } while (node.parent.kind === 153 /* QualifiedName */);
- return getAliasDeclarationFromName(node);
- }
- }
- ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
- function isAliasableExpression(e) {
- return isEntityNameExpression(e) || ts.isClassExpression(e);
- }
- ts.isAliasableExpression = isAliasableExpression;
- function exportAssignmentIsAlias(node) {
- var e = getExportAssignmentExpression(node);
- return isAliasableExpression(e);
- }
- ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
- function getExportAssignmentExpression(node) {
- return ts.isExportAssignment(node) ? node.expression : node.right;
- }
- ts.getExportAssignmentExpression = getExportAssignmentExpression;
- function getPropertyAssignmentAliasLikeExpression(node) {
- return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
- node.parent.right;
- }
- ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
- function getEffectiveBaseTypeNode(node) {
- var baseType = getClassExtendsHeritageElement(node);
- if (baseType && isInJSFile(node)) {
- // Prefer an @augments tag because it may have type parameters.
- var tag = ts.getJSDocAugmentsTag(node);
- if (tag) {
- return tag.class;
- }
- }
- return baseType;
- }
- ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
- function getClassExtendsHeritageElement(node) {
- var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
- return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
- }
- ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
- function getEffectiveImplementsTypeNodes(node) {
- if (isInJSFile(node)) {
- return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
- }
- else {
- var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
- return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
- }
- }
- ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
- /** 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(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
- ts.emptyArray;
- }
- ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
- function getInterfaceBaseTypeNodes(node) {
- var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
- return heritageClause ? heritageClause.types : undefined;
- }
- ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
- function getHeritageClause(clauses, kind) {
- if (clauses) {
- for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
- var clause = clauses_1[_i];
- if (clause.token === kind) {
- return clause;
- }
- }
- }
- return undefined;
- }
- ts.getHeritageClause = getHeritageClause;
- function getAncestor(node, kind) {
- while (node) {
- if (node.kind === kind) {
- return node;
- }
- node = node.parent;
- }
- return undefined;
- }
- ts.getAncestor = getAncestor;
- function isKeyword(token) {
- return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
- }
- ts.isKeyword = isKeyword;
- function isContextualKeyword(token) {
- return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
- }
- ts.isContextualKeyword = isContextualKeyword;
- function isNonContextualKeyword(token) {
- return isKeyword(token) && !isContextualKeyword(token);
- }
- ts.isNonContextualKeyword = isNonContextualKeyword;
- function isFutureReservedKeyword(token) {
- return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
- }
- ts.isFutureReservedKeyword = isFutureReservedKeyword;
- function isStringANonContextualKeyword(name) {
- var token = ts.stringToToken(name);
- return token !== undefined && isNonContextualKeyword(token);
- }
- ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
- function isStringAKeyword(name) {
- var token = ts.stringToToken(name);
- return token !== undefined && isKeyword(token);
- }
- ts.isStringAKeyword = isStringAKeyword;
- function isIdentifierANonContextualKeyword(_a) {
- var originalKeywordKind = _a.originalKeywordKind;
- return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
- }
- ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
- function isTrivia(token) {
- return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
- }
- ts.isTrivia = isTrivia;
- var FunctionFlags;
- (function (FunctionFlags) {
- FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
- FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
- FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
- FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
- FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
- })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
- function getFunctionFlags(node) {
- if (!node) {
- return 4 /* Invalid */;
- }
- var flags = 0 /* Normal */;
- switch (node.kind) {
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 161 /* MethodDeclaration */:
- if (node.asteriskToken) {
- flags |= 1 /* Generator */;
- }
- // falls through
- case 202 /* ArrowFunction */:
- if (hasModifier(node, 256 /* Async */)) {
- flags |= 2 /* Async */;
- }
- break;
- }
- if (!node.body) {
- flags |= 4 /* Invalid */;
- }
- return flags;
- }
- ts.getFunctionFlags = getFunctionFlags;
- function isAsyncFunction(node) {
- switch (node.kind) {
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- case 161 /* MethodDeclaration */:
- return node.body !== undefined
- && node.asteriskToken === undefined
- && hasModifier(node, 256 /* Async */);
- }
- return false;
- }
- ts.isAsyncFunction = isAsyncFunction;
- function isStringOrNumericLiteralLike(node) {
- return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
- }
- ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
- function isSignedNumericLiteral(node) {
- return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
- }
- ts.isSignedNumericLiteral = isSignedNumericLiteral;
- /**
- * A declaration has a dynamic name if all of the following are true:
- * 1. The declaration has a computed property name.
- * 2. The computed name is *not* expressed as a StringLiteral.
- * 3. The computed name is *not* expressed as a NumericLiteral.
- * 4. The computed name is *not* expressed as a PlusToken or MinusToken
- * immediately followed by a NumericLiteral.
- * 5. The computed name is *not* expressed as `Symbol.`, where ``
- * 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) {
- if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
- return false;
- }
- var expr = ts.isElementAccessExpression(name) ? name.argumentExpression : name.expression;
- return !isStringOrNumericLiteralLike(expr) &&
- !isSignedNumericLiteral(expr) &&
- !isWellKnownSymbolSyntactically(expr);
- }
- 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) {
- switch (name.kind) {
- case 75 /* Identifier */:
- case 76 /* PrivateIdentifier */:
- return name.escapedText;
- case 10 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- return ts.escapeLeadingUnderscores(name.text);
- case 154 /* ComputedPropertyName */:
- var nameExpression = name.expression;
- if (isWellKnownSymbolSyntactically(nameExpression)) {
- return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
- }
- else if (isStringOrNumericLiteralLike(nameExpression)) {
- return ts.escapeLeadingUnderscores(nameExpression.text);
- }
- return undefined;
- default:
- return ts.Debug.assertNever(name);
- }
- }
- ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
- function isPropertyNameLiteral(node) {
- switch (node.kind) {
- case 75 /* Identifier */:
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 8 /* NumericLiteral */:
- return true;
- default:
- return false;
- }
- }
- ts.isPropertyNameLiteral = isPropertyNameLiteral;
- function getTextOfIdentifierOrLiteral(node) {
- return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
- }
- ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
- function getEscapedTextOfIdentifierOrLiteral(node) {
- return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
- }
- ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
- function getPropertyNameForUniqueESSymbol(symbol) {
- return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
- }
- ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
- function getPropertyNameForKnownSymbolName(symbolName) {
- return "__@" + symbolName;
- }
- ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
- function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
- return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
- }
- ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
- function isKnownSymbol(symbol) {
- return ts.startsWith(symbol.escapedName, "__@");
- }
- ts.isKnownSymbol = isKnownSymbol;
- /**
- * Includes the word "Symbol" with unicode escapes
- */
- function isESSymbolIdentifier(node) {
- return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
- }
- ts.isESSymbolIdentifier = isESSymbolIdentifier;
- function isPushOrUnshiftIdentifier(node) {
- return node.escapedText === "push" || node.escapedText === "unshift";
- }
- ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
- function isParameterDeclaration(node) {
- var root = getRootDeclaration(node);
- return root.kind === 156 /* Parameter */;
- }
- ts.isParameterDeclaration = isParameterDeclaration;
- function getRootDeclaration(node) {
- while (node.kind === 191 /* BindingElement */) {
- node = node.parent.parent;
- }
- return node;
- }
- ts.getRootDeclaration = getRootDeclaration;
- function nodeStartsNewLexicalEnvironment(node) {
- var kind = node.kind;
- return kind === 162 /* Constructor */
- || kind === 201 /* FunctionExpression */
- || kind === 244 /* FunctionDeclaration */
- || kind === 202 /* ArrowFunction */
- || kind === 161 /* MethodDeclaration */
- || kind === 163 /* GetAccessor */
- || kind === 164 /* SetAccessor */
- || kind === 249 /* ModuleDeclaration */
- || kind === 290 /* SourceFile */;
- }
- ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
- function nodeIsSynthesized(range) {
- return positionIsSynthesized(range.pos)
- || positionIsSynthesized(range.end);
- }
- ts.nodeIsSynthesized = nodeIsSynthesized;
- function getOriginalSourceFile(sourceFile) {
- return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
- }
- ts.getOriginalSourceFile = getOriginalSourceFile;
- var Associativity;
- (function (Associativity) {
- Associativity[Associativity["Left"] = 0] = "Left";
- Associativity[Associativity["Right"] = 1] = "Right";
- })(Associativity = ts.Associativity || (ts.Associativity = {}));
- function getExpressionAssociativity(expression) {
- var operator = getOperator(expression);
- var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
- return getOperatorAssociativity(expression.kind, operator, hasArguments);
- }
- ts.getExpressionAssociativity = getExpressionAssociativity;
- function getOperatorAssociativity(kind, operator, hasArguments) {
- switch (kind) {
- case 197 /* NewExpression */:
- return hasArguments ? 0 /* Left */ : 1 /* Right */;
- case 207 /* PrefixUnaryExpression */:
- case 204 /* TypeOfExpression */:
- case 205 /* VoidExpression */:
- case 203 /* DeleteExpression */:
- case 206 /* AwaitExpression */:
- case 210 /* ConditionalExpression */:
- case 212 /* YieldExpression */:
- return 1 /* Right */;
- case 209 /* BinaryExpression */:
- switch (operator) {
- case 42 /* AsteriskAsteriskToken */:
- case 62 /* EqualsToken */:
- case 63 /* PlusEqualsToken */:
- case 64 /* MinusEqualsToken */:
- case 66 /* AsteriskAsteriskEqualsToken */:
- case 65 /* AsteriskEqualsToken */:
- case 67 /* SlashEqualsToken */:
- case 68 /* PercentEqualsToken */:
- case 69 /* LessThanLessThanEqualsToken */:
- case 70 /* GreaterThanGreaterThanEqualsToken */:
- case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
- case 72 /* AmpersandEqualsToken */:
- case 74 /* CaretEqualsToken */:
- case 73 /* BarEqualsToken */:
- return 1 /* Right */;
- }
- }
- return 0 /* Left */;
- }
- ts.getOperatorAssociativity = getOperatorAssociativity;
- function getExpressionPrecedence(expression) {
- var operator = getOperator(expression);
- var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
- return getOperatorPrecedence(expression.kind, operator, hasArguments);
- }
- ts.getExpressionPrecedence = getExpressionPrecedence;
- function getOperator(expression) {
- if (expression.kind === 209 /* BinaryExpression */) {
- return expression.operatorToken.kind;
- }
- else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
- return expression.operator;
- }
- else {
- return expression.kind;
- }
- }
- ts.getOperator = getOperator;
- function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
- switch (nodeKind) {
- case 327 /* CommaListExpression */:
- return 0;
- case 213 /* SpreadElement */:
- return 1;
- case 212 /* YieldExpression */:
- return 2;
- case 210 /* ConditionalExpression */:
- return 4;
- case 209 /* BinaryExpression */:
- switch (operatorKind) {
- case 27 /* CommaToken */:
- return 0;
- case 62 /* EqualsToken */:
- case 63 /* PlusEqualsToken */:
- case 64 /* MinusEqualsToken */:
- case 66 /* AsteriskAsteriskEqualsToken */:
- case 65 /* AsteriskEqualsToken */:
- case 67 /* SlashEqualsToken */:
- case 68 /* PercentEqualsToken */:
- case 69 /* LessThanLessThanEqualsToken */:
- case 70 /* GreaterThanGreaterThanEqualsToken */:
- case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
- case 72 /* AmpersandEqualsToken */:
- case 74 /* CaretEqualsToken */:
- case 73 /* BarEqualsToken */:
- return 3;
- default:
- return getBinaryOperatorPrecedence(operatorKind);
- }
- case 207 /* PrefixUnaryExpression */:
- case 204 /* TypeOfExpression */:
- case 205 /* VoidExpression */:
- case 203 /* DeleteExpression */:
- case 206 /* AwaitExpression */:
- return 16;
- case 208 /* PostfixUnaryExpression */:
- return 17;
- case 196 /* CallExpression */:
- return 18;
- case 197 /* NewExpression */:
- return hasArguments ? 19 : 18;
- case 198 /* TaggedTemplateExpression */:
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- return 19;
- case 104 /* ThisKeyword */:
- case 102 /* SuperKeyword */:
- case 75 /* Identifier */:
- case 100 /* NullKeyword */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 10 /* StringLiteral */:
- case 192 /* ArrayLiteralExpression */:
- case 193 /* ObjectLiteralExpression */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- case 214 /* ClassExpression */:
- case 266 /* JsxElement */:
- case 267 /* JsxSelfClosingElement */:
- case 270 /* JsxFragment */:
- case 13 /* RegularExpressionLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 211 /* TemplateExpression */:
- case 200 /* ParenthesizedExpression */:
- case 215 /* OmittedExpression */:
- return 20;
- default:
- return -1;
- }
- }
- ts.getOperatorPrecedence = getOperatorPrecedence;
- function getBinaryOperatorPrecedence(kind) {
- switch (kind) {
- case 60 /* QuestionQuestionToken */:
- return 4;
- case 56 /* BarBarToken */:
- return 5;
- case 55 /* AmpersandAmpersandToken */:
- return 6;
- case 51 /* BarToken */:
- return 7;
- case 52 /* CaretToken */:
- return 8;
- case 50 /* AmpersandToken */:
- return 9;
- case 34 /* EqualsEqualsToken */:
- case 35 /* ExclamationEqualsToken */:
- case 36 /* EqualsEqualsEqualsToken */:
- case 37 /* ExclamationEqualsEqualsToken */:
- return 10;
- case 29 /* LessThanToken */:
- case 31 /* GreaterThanToken */:
- case 32 /* LessThanEqualsToken */:
- case 33 /* GreaterThanEqualsToken */:
- case 98 /* InstanceOfKeyword */:
- case 97 /* InKeyword */:
- case 123 /* AsKeyword */:
- return 11;
- case 47 /* LessThanLessThanToken */:
- case 48 /* GreaterThanGreaterThanToken */:
- case 49 /* GreaterThanGreaterThanGreaterThanToken */:
- return 12;
- case 39 /* PlusToken */:
- case 40 /* MinusToken */:
- return 13;
- case 41 /* AsteriskToken */:
- case 43 /* SlashToken */:
- case 44 /* PercentToken */:
- return 14;
- case 42 /* 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 = []; // See GH#19873
- var filesWithDiagnostics = [];
- var fileDiagnostics = ts.createMap();
- var hasReadNonFileDiagnostics = false;
- return {
- add: add,
- lookup: lookup,
- getGlobalDiagnostics: getGlobalDiagnostics,
- getDiagnostics: getDiagnostics,
- reattachFileDiagnostics: reattachFileDiagnostics
- };
- function reattachFileDiagnostics(newFile) {
- ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
- }
- function lookup(diagnostic) {
- var diagnostics;
- if (diagnostic.file) {
- diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
- }
- else {
- diagnostics = nonFileDiagnostics;
- }
- if (!diagnostics) {
- return undefined;
- }
- var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
- if (result >= 0) {
- return diagnostics[result];
- }
- return undefined;
- }
- function add(diagnostic) {
- var diagnostics;
- if (diagnostic.file) {
- diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
- if (!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();
- }
- diagnostics = nonFileDiagnostics;
- }
- ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
- }
- function getGlobalDiagnostics() {
- hasReadNonFileDiagnostics = true;
- return nonFileDiagnostics;
- }
- function getDiagnostics(fileName) {
- if (fileName) {
- return fileDiagnostics.get(fileName) || [];
- }
- var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
- if (!nonFileDiagnostics.length) {
- return fileDiags;
- }
- fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
- return fileDiags;
- }
- }
- ts.createDiagnosticCollection = createDiagnosticCollection;
- var templateSubstitutionRegExp = /\$\{/g;
- function escapeTemplateSubstitution(str) {
- return str.replace(templateSubstitutionRegExp, "\\${");
- }
- /** @internal */
- function hasInvalidEscape(template) {
- return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
- ? template.templateFlags
- : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
- }
- ts.hasInvalidEscape = hasInvalidEscape;
- // 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;
- // Template strings should be preserved as much as possible
- var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
- var escapedCharsMap = ts.createMapFromTemplate({
- "\t": "\\t",
- "\v": "\\v",
- "\f": "\\f",
- "\b": "\\b",
- "\r": "\\r",
- "\n": "\\n",
- "\\": "\\\\",
- "\"": "\\\"",
- "\'": "\\\'",
- "\`": "\\\`",
- "\u2028": "\\u2028",
- "\u2029": "\\u2029",
- "\u0085": "\\u0085" // nextLine
- });
- function encodeUtf16EscapeSequence(charCode) {
- var hexCharCode = charCode.toString(16).toUpperCase();
- var paddedHexCode = ("0000" + hexCharCode).slice(-4);
- return "\\u" + paddedHexCode;
- }
- function getReplacement(c, offset, input) {
- if (c.charCodeAt(0) === 0 /* nullCharacter */) {
- var lookAhead = input.charCodeAt(offset + c.length);
- 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) || encodeUtf16EscapeSequence(c.charCodeAt(0));
- }
- /**
- * 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 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
- quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
- doubleQuoteEscapedCharsRegExp;
- return s.replace(escapedCharsRegExp, getReplacement);
- }
- ts.escapeString = escapeString;
- 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 encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
- s;
- }
- ts.escapeNonAsciiString = escapeNonAsciiString;
- // This consists of the first 19 unprintable ASCII characters, JSX 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.
- var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
- var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
- var jsxEscapedCharsMap = ts.createMapFromTemplate({
- "\"": """,
- "\'": "'"
- });
- function encodeJsxCharacterEntity(charCode) {
- var hexCharCode = charCode.toString(16).toUpperCase();
- return "" + hexCharCode + ";";
- }
- function getJsxAttributeStringReplacement(c) {
- if (c.charCodeAt(0) === 0 /* nullCharacter */) {
- return "";
- }
- return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
- }
- function escapeJsxAttributeString(s, quoteChar) {
- var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
- jsxDoubleQuoteEscapedCharsRegExp;
- return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
- }
- ts.escapeJsxAttributeString = escapeJsxAttributeString;
- /**
- * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
- *
- * @return non-quoted string
- */
- function stripQuotes(name) {
- var length = name.length;
- if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
- return name.substring(1, length - 1);
- }
- return name;
- }
- ts.stripQuotes = stripQuotes;
- function isQuoteOrBacktick(charCode) {
- return charCode === 39 /* singleQuote */ ||
- charCode === 34 /* doubleQuote */ ||
- charCode === 96 /* backtick */;
- }
- function isIntrinsicJsxName(name) {
- var ch = name.charCodeAt(0);
- return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
- }
- ts.isIntrinsicJsxName = isIntrinsicJsxName;
- var indentStrings = ["", " "];
- function getIndentString(level) {
- if (indentStrings[level] === undefined) {
- indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
- }
- return indentStrings[level];
- }
- ts.getIndentString = getIndentString;
- function getIndentSize() {
- return indentStrings[1].length;
- }
- ts.getIndentSize = getIndentSize;
- function createTextWriter(newLine) {
- var output;
- var indent;
- var lineStart;
- var lineCount;
- var linePos;
- var hasTrailingComment = false;
- function updateLineCountAndPosFor(s) {
- var lineStartsOfS = ts.computeLineStarts(s);
- if (lineStartsOfS.length > 1) {
- lineCount = lineCount + lineStartsOfS.length - 1;
- linePos = output.length - s.length + ts.last(lineStartsOfS);
- lineStart = (linePos - output.length) === 0;
- }
- else {
- lineStart = false;
- }
- }
- function writeText(s) {
- if (s && s.length) {
- if (lineStart) {
- s = getIndentString(indent) + s;
- lineStart = false;
- }
- output += s;
- updateLineCountAndPosFor(s);
- }
- }
- function write(s) {
- if (s)
- hasTrailingComment = false;
- writeText(s);
- }
- function writeComment(s) {
- if (s)
- hasTrailingComment = true;
- writeText(s);
- }
- function reset() {
- output = "";
- indent = 0;
- lineStart = true;
- lineCount = 0;
- linePos = 0;
- hasTrailingComment = false;
- }
- function rawWrite(s) {
- if (s !== undefined) {
- output += s;
- updateLineCountAndPosFor(s);
- hasTrailingComment = false;
- }
- }
- function writeLiteral(s) {
- if (s && s.length) {
- write(s);
- }
- }
- function writeLine(force) {
- if (!lineStart || force) {
- output += newLine;
- lineCount++;
- linePos = output.length;
- lineStart = true;
- hasTrailingComment = false;
- }
- }
- function getTextPosWithWriteLine() {
- return lineStart ? output.length : (output.length + newLine.length);
- }
- reset();
- return {
- write: write,
- rawWrite: rawWrite,
- writeLiteral: writeLiteral,
- writeLine: writeLine,
- increaseIndent: function () { indent++; },
- decreaseIndent: function () { indent--; },
- getIndent: function () { return indent; },
- getTextPos: function () { return output.length; },
- getLine: function () { return lineCount; },
- getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
- getText: function () { return output; },
- isAtStartOfLine: function () { return lineStart; },
- hasTrailingComment: function () { return hasTrailingComment; },
- hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
- clear: reset,
- reportInaccessibleThisError: ts.noop,
- reportPrivateInBaseOfClassExpression: ts.noop,
- reportInaccessibleUniqueSymbolError: ts.noop,
- trackSymbol: ts.noop,
- writeKeyword: write,
- writeOperator: write,
- writeParameter: write,
- writeProperty: write,
- writePunctuation: write,
- writeSpace: write,
- writeStringLiteral: write,
- writeSymbol: function (s, _) { return write(s); },
- writeTrailingSemicolon: write,
- writeComment: writeComment,
- getTextPosWithWriteLine: getTextPosWithWriteLine
- };
- }
- ts.createTextWriter = createTextWriter;
- function getTrailingSemicolonDeferringWriter(writer) {
- var pendingTrailingSemicolon = false;
- function commitPendingTrailingSemicolon() {
- if (pendingTrailingSemicolon) {
- writer.writeTrailingSemicolon(";");
- pendingTrailingSemicolon = false;
- }
- }
- return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
- pendingTrailingSemicolon = true;
- },
- writeLiteral: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeLiteral(s);
- },
- writeStringLiteral: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeStringLiteral(s);
- },
- writeSymbol: function (s, sym) {
- commitPendingTrailingSemicolon();
- writer.writeSymbol(s, sym);
- },
- writePunctuation: function (s) {
- commitPendingTrailingSemicolon();
- writer.writePunctuation(s);
- },
- writeKeyword: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeKeyword(s);
- },
- writeOperator: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeOperator(s);
- },
- writeParameter: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeParameter(s);
- },
- writeSpace: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeSpace(s);
- },
- writeProperty: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeProperty(s);
- },
- writeComment: function (s) {
- commitPendingTrailingSemicolon();
- writer.writeComment(s);
- },
- writeLine: function () {
- commitPendingTrailingSemicolon();
- writer.writeLine();
- },
- increaseIndent: function () {
- commitPendingTrailingSemicolon();
- writer.increaseIndent();
- },
- decreaseIndent: function () {
- commitPendingTrailingSemicolon();
- writer.decreaseIndent();
- } });
- }
- ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
- function hostUsesCaseSensitiveFileNames(host) {
- return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
- }
- ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
- function hostGetCanonicalFileName(host) {
- return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
- }
- ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
- function getResolvedExternalModuleName(host, file, referenceFile) {
- return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
- }
- ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
- function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
- var file = resolver.getExternalModuleFileFromDeclaration(declaration);
- if (!file || file.isDeclarationFile) {
- return undefined;
- }
- 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 = ts.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, /*isAbsolutePathAnUrl*/ false);
- var extensionless = removeFileExtension(relativePath);
- return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
- }
- ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
- function getOwnEmitOutputFilePath(fileName, host, extension) {
- var compilerOptions = host.getCompilerOptions();
- var emitOutputFilePathWithoutExtension;
- if (compilerOptions.outDir) {
- emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
- }
- else {
- emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
- }
- return emitOutputFilePathWithoutExtension + extension;
- }
- ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
- function getDeclarationEmitOutputFilePath(fileName, host) {
- return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
- }
- ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
- function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
- var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
- var path = outputDir
- ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
- : fileName;
- return removeFileExtension(path) + ".d.ts" /* Dts */;
- }
- ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
- /**
- * 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, forceDtsEmit) {
- var options = host.getCompilerOptions();
- if (options.outFile || options.out) {
- var moduleKind = getEmitModuleKind(options);
- var moduleEmitEnabled_1 = options.emitDeclarationOnly || 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, host, forceDtsEmit);
- });
- }
- else {
- var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
- }
- }
- ts.getSourceFilesToEmit = getSourceFilesToEmit;
- /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
- var options = host.getCompilerOptions();
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
- !sourceFile.isDeclarationFile &&
- !host.isSourceFileFromExternalLibrary(sourceFile) &&
- !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
- (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
- }
- ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
- function getSourceFilePathInNewDir(fileName, host, newDirPath) {
- return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
- }
- ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
- function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
- var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
- var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
- sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
- return ts.combinePaths(newDirPath, sourceFilePath);
- }
- ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
- function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
- host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
- diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
- }, sourceFiles);
- }
- ts.writeFile = writeFile;
- function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
- if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
- var parentDirectory = ts.getDirectoryPath(directoryPath);
- ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
- createDirectory(directoryPath);
- }
- }
- function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
- // PERF: Checking for directory existence is expensive. Instead, assume the directory exists
- // and fall back to creating it if the file write fails.
- try {
- writeFile(path, data, writeByteOrderMark);
- }
- catch (_a) {
- ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
- writeFile(path, data, writeByteOrderMark);
- }
- }
- ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
- function getLineOfLocalPosition(sourceFile, pos) {
- var lineStarts = ts.getLineStarts(sourceFile);
- return ts.computeLineOfPosition(lineStarts, pos);
- }
- ts.getLineOfLocalPosition = getLineOfLocalPosition;
- function getLineOfLocalPositionFromLineMap(lineMap, pos) {
- return ts.computeLineOfPosition(lineMap, pos);
- }
- ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
- function getFirstConstructorWithBody(node) {
- return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
- }
- ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
- function getSetAccessorValueParameter(accessor) {
- if (accessor && accessor.parameters.length > 0) {
- var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
- return accessor.parameters[hasThis ? 1 : 0];
- }
- }
- ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
- /** 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)) {
- return thisParameter;
- }
- }
- }
- ts.getThisParameter = getThisParameter;
- function parameterIsThisKeyword(parameter) {
- return isThisIdentifier(parameter.name);
- }
- ts.parameterIsThisKeyword = parameterIsThisKeyword;
- function isThisIdentifier(node) {
- return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
- }
- ts.isThisIdentifier = isThisIdentifier;
- function identifierIsThisKeyword(id) {
- return id.originalKeywordKind === 104 /* 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 === 163 /* GetAccessor */) {
- getAccessor = accessor;
- }
- else if (accessor.kind === 164 /* SetAccessor */) {
- setAccessor = accessor;
- }
- else {
- ts.Debug.fail("Accessor has wrong kind");
- }
- }
- else {
- ts.forEach(declarations, function (member) {
- if (ts.isAccessor(member)
- && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
- var memberName = getPropertyNameForPropertyNameNode(member.name);
- var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
- if (memberName === accessorName) {
- if (!firstAccessor) {
- firstAccessor = member;
- }
- else if (!secondAccessor) {
- secondAccessor = member;
- }
- if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
- // eslint-disable-next-line
- getAccessor = member;
- }
- if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
- // eslint-disable-next-line
- setAccessor = member;
- }
- }
- }
- });
- }
- return {
- firstAccessor: firstAccessor,
- secondAccessor: secondAccessor,
- getAccessor: getAccessor,
- setAccessor: setAccessor
- };
- }
- 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. Also gets the type of
- * functions only the JSDoc case.
- */
- function getEffectiveTypeAnnotationNode(node) {
- if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
- return undefined;
- var type = node.type;
- if (type || !isInJSFile(node))
- return type;
- return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
- }
- ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
- function getTypeAnnotationNode(node) {
- 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) {
- return ts.isJSDocSignature(node) ?
- node.type && node.type.typeExpression && node.type.typeExpression.type :
- node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
- }
- ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
- function getJSDocTypeParameterDeclarations(node) {
- 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 === 303 /* 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);
- }
- ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
- function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
- emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
- }
- 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();
- }
- }
- 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();
- }
- }
- ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
- function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
- if (comments && comments.length > 0) {
- if (leadingSeparator) {
- writer.writeSpace(" ");
- }
- var emitInterveningSeparator = false;
- for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
- var comment = comments_1[_i];
- if (emitInterveningSeparator) {
- writer.writeSpace(" ");
- emitInterveningSeparator = false;
- }
- writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
- if (comment.hasTrailingNewLine) {
- writer.writeLine();
- }
- else {
- emitInterveningSeparator = true;
- }
- }
- if (emitInterveningSeparator && trailingSeparator) {
- writer.writeSpace(" ");
- }
- }
- }
- 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) {
- var detachedComments = [];
- var lastComment = void 0;
- for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
- var comment = leadingComments_1[_i];
- if (lastComment) {
- 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;
- }
- }
- detachedComments.push(comment);
- 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, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
- currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
- }
- }
- }
- return currentDetachedCommentInfo;
- function isPinnedCommentLocal(comment) {
- return isPinnedComment(text, comment.pos);
- }
- }
- ts.emitDetachedComments = emitDetachedComments;
- function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
- if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
- var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
- var lineCount = lineMap.length;
- var firstCommentLineIndent = void 0;
- for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
- var nextLineStart = (currentLine + 1) === lineCount
- ? 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.writeComment(text.substring(commentPos, commentEnd));
- }
- }
- ts.writeCommentRange = writeCommentRange;
- function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
- 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.writeComment(currentLineText);
- if (end !== commentEnd) {
- writer.writeLine();
- }
- }
- else {
- // Empty string - make sure we write empty line
- writer.rawWrite(newLine);
- }
- }
- function calculateIndent(text, pos, end) {
- var currentLineIndent = 0;
- for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
- if (text.charCodeAt(pos) === 9 /* tab */) {
- // Tabs = TabSize = indent size and go to next tabStop
- currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
- }
- else {
- // Single space
- currentLineIndent++;
- }
- }
- return currentLineIndent;
- }
- function hasModifiers(node) {
- return getModifierFlags(node) !== 0 /* None */;
- }
- ts.hasModifiers = hasModifiers;
- function hasModifier(node, flags) {
- return !!getSelectedModifierFlags(node, flags);
- }
- ts.hasModifier = hasModifier;
- function hasStaticModifier(node) {
- return hasModifier(node, 32 /* Static */);
- }
- ts.hasStaticModifier = hasStaticModifier;
- function hasReadonlyModifier(node) {
- return hasModifier(node, 64 /* Readonly */);
- }
- ts.hasReadonlyModifier = hasReadonlyModifier;
- function getSelectedModifierFlags(node, flags) {
- return getModifierFlags(node) & flags;
- }
- ts.getSelectedModifierFlags = getSelectedModifierFlags;
- function getModifierFlags(node) {
- if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
- return 0 /* None */;
- }
- if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
- return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
- }
- var flags = getModifierFlagsNoCache(node);
- node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
- return flags;
- }
- ts.getModifierFlags = getModifierFlags;
- function getModifierFlagsNoCache(node) {
- 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 (isInJSFile(node) && !!node.parent) {
- // getModifierFlagsNoCache should only be called when parent pointers are set,
- // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
- var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
- | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
- | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
- | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
- flags |= tags;
- }
- if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
- flags |= 1 /* Export */;
- }
- return flags;
- }
- ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
- function modifierToFlag(token) {
- switch (token) {
- case 120 /* StaticKeyword */: return 32 /* Static */;
- case 119 /* PublicKeyword */: return 4 /* Public */;
- case 118 /* ProtectedKeyword */: return 16 /* Protected */;
- case 117 /* PrivateKeyword */: return 8 /* Private */;
- case 122 /* AbstractKeyword */: return 128 /* Abstract */;
- case 89 /* ExportKeyword */: return 1 /* Export */;
- case 130 /* DeclareKeyword */: return 2 /* Ambient */;
- case 81 /* ConstKeyword */: return 2048 /* Const */;
- case 84 /* DefaultKeyword */: return 512 /* Default */;
- case 126 /* AsyncKeyword */: return 256 /* Async */;
- case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
- }
- return 0 /* None */;
- }
- ts.modifierToFlag = modifierToFlag;
- function isLogicalOperator(token) {
- return token === 56 /* BarBarToken */
- || token === 55 /* AmpersandAmpersandToken */
- || token === 53 /* ExclamationToken */;
- }
- ts.isLogicalOperator = isLogicalOperator;
- function isAssignmentOperator(token) {
- return token >= 62 /* FirstAssignment */ && token <= 74 /* 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) {
- var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
- return cls && !cls.isImplements ? cls.class : undefined;
- }
- ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
- function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
- return ts.isExpressionWithTypeArguments(node)
- && ts.isHeritageClause(node.parent)
- && ts.isClassLike(node.parent.parent)
- ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
- : undefined;
- }
- ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
- function isAssignmentExpression(node, excludeCompoundAssignment) {
- return ts.isBinaryExpression(node)
- && (excludeCompoundAssignment
- ? node.operatorToken.kind === 62 /* EqualsToken */
- : isAssignmentOperator(node.operatorToken.kind))
- && ts.isLeftHandSideExpression(node.left);
- }
- ts.isAssignmentExpression = isAssignmentExpression;
- function isDestructuringAssignment(node) {
- if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
- var kind = node.left.kind;
- return kind === 193 /* ObjectLiteralExpression */
- || kind === 192 /* ArrayLiteralExpression */;
- }
- return false;
- }
- ts.isDestructuringAssignment = isDestructuringAssignment;
- function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
- return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
- }
- ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
- function isEntityNameExpression(node) {
- return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
- }
- ts.isEntityNameExpression = isEntityNameExpression;
- function getFirstIdentifier(node) {
- switch (node.kind) {
- case 75 /* Identifier */:
- return node;
- case 153 /* QualifiedName */:
- do {
- node = node.left;
- } while (node.kind !== 75 /* Identifier */);
- return node;
- case 194 /* PropertyAccessExpression */:
- do {
- node = node.expression;
- } while (node.kind !== 75 /* Identifier */);
- return node;
- }
- }
- ts.getFirstIdentifier = getFirstIdentifier;
- function isDottedName(node) {
- return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
- node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
- node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
- }
- ts.isDottedName = isDottedName;
- function isPropertyAccessEntityNameExpression(node) {
- return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
- }
- ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
- function tryGetPropertyAccessOrIdentifierToString(expr) {
- if (ts.isPropertyAccessExpression(expr)) {
- var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
- if (baseStr !== undefined) {
- return baseStr + "." + expr.name;
- }
- }
- else if (ts.isIdentifier(expr)) {
- return ts.unescapeLeadingUnderscores(expr.escapedText);
- }
- return undefined;
- }
- ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
- function isPrototypeAccess(node) {
- return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
- }
- ts.isPrototypeAccess = isPrototypeAccess;
- function isRightSideOfQualifiedNameOrPropertyAccess(node) {
- return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
- (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
- }
- ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
- function isEmptyObjectLiteral(expression) {
- return expression.kind === 193 /* ObjectLiteralExpression */ &&
- expression.properties.length === 0;
- }
- ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
- function isEmptyArrayLiteral(expression) {
- return expression.kind === 192 /* ArrayLiteralExpression */ &&
- expression.elements.length === 0;
- }
- ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
- function getLocalSymbolForExportDefault(symbol) {
- return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
- }
- ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
- function isExportDefaultSymbol(symbol) {
- 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 tryExtractTSExtension(fileName) {
- return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
- }
- ts.tryExtractTSExtension = tryExtractTSExtension;
- /**
- * 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);
- }
- else if (charCode < 0x800) {
- output.push((charCode >> 6) | 192);
- output.push((charCode & 63) | 128);
- }
- else if (charCode < 0x10000) {
- output.push((charCode >> 12) | 224);
- output.push(((charCode >> 6) & 63) | 128);
- output.push((charCode & 63) | 128);
- }
- else if (charCode < 0x20000) {
- output.push((charCode >> 18) | 240);
- output.push(((charCode >> 12) & 63) | 128);
- output.push(((charCode >> 6) & 63) | 128);
- output.push((charCode & 63) | 128);
- }
- else {
- ts.Debug.assert(false, "Unexpected code point");
- }
- }
- return output;
- }
- var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- /**
- * Converts a string to a base-64 encoded ASCII string.
- */
- function convertToBase64(input) {
- var result = "";
- var charCodes = getExpandedCharCodes(input);
- var i = 0;
- 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;
- }
- return result;
- }
- ts.convertToBase64 = convertToBase64;
- function getStringFromExpandedCharCodes(codes) {
- var output = "";
- var i = 0;
- var length = codes.length;
- while (i < length) {
- var charCode = codes[i];
- if (charCode < 0x80) {
- output += String.fromCharCode(charCode);
- i++;
- }
- else if ((charCode & 192) === 192) {
- var value = charCode & 63;
- i++;
- var nextCode = codes[i];
- while ((nextCode & 192) === 128) {
- value = (value << 6) | (nextCode & 63);
- 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++;
- }
- }
- return output;
- }
- function base64encode(host, input) {
- if (host && host.base64encode) {
- return host.base64encode(input);
- }
- return convertToBase64(input);
- }
- ts.base64encode = base64encode;
- function base64decode(host, input) {
- if (host && host.base64decode) {
- return host.base64decode(input);
- }
- var length = input.length;
- 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]);
- var ch4 = base64Digits.indexOf(input[i + 3]);
- 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) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
- expandedCharCodes.push(code1);
- }
- else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
- expandedCharCodes.push(code1, code2);
- }
- else {
- expandedCharCodes.push(code1, code2, code3);
- }
- i += 4;
- }
- return getStringFromExpandedCharCodes(expandedCharCodes);
- }
- ts.base64decode = base64decode;
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- if (!jsonText)
- return {};
- var result = ts.parseConfigFileTextToJson(path, jsonText);
- if (result.error) {
- return {};
- }
- return result.config;
- }
- catch (e) {
- // gracefully handle if readFile fails or returns not JSON
- return {};
- }
- }
- ts.readJson = readJson;
- function directoryProbablyExists(directoryName, host) {
- // if host does not support 'directoryExists' assume that directory will exist
- return !host.directoryExists || host.directoryExists(directoryName);
- }
- ts.directoryProbablyExists = directoryProbablyExists;
- var carriageReturnLineFeed = "\r\n";
- var lineFeed = "\n";
- function getNewLineCharacter(options, getNewLine) {
- switch (options.newLine) {
- case 0 /* CarriageReturnLineFeed */:
- return carriageReturnLineFeed;
- case 1 /* LineFeed */:
- return lineFeed;
- }
- return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
- }
- ts.getNewLineCharacter = getNewLineCharacter;
- /**
- * Creates a new TextRange from the provided pos and end.
- *
- * @param pos The start position.
- * @param end The end position.
- */
- function createRange(pos, end) {
- if (end === void 0) { end = pos; }
- ts.Debug.assert(end >= pos || end === -1);
- 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);
- }
- ts.createTokenRange = createTokenRange;
- function rangeIsOnSingleLine(range, sourceFile) {
- return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
- }
- ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
- function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
- return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
- }
- ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
- function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
- return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
- }
- ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
- function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
- return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
- }
- ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
- function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
- return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
- }
- ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
- function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
- var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
- return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
- }
- ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
- function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
- return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
- }
- ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
- function isNodeArrayMultiLine(list, sourceFile) {
- return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
- }
- ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
- function positionsAreOnSameLine(pos1, pos2, sourceFile) {
- return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
- }
- ts.positionsAreOnSameLine = positionsAreOnSameLine;
- function getStartPositionOfRange(range, sourceFile, includeComments) {
- return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
- }
- ts.getStartPositionOfRange = getStartPositionOfRange;
- function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
- var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
- var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
- return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
- }
- ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
- function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
- var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
- return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
- }
- ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
- function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
- if (stopPos === void 0) { stopPos = 0; }
- while (pos-- > stopPos) {
- if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
- return pos;
- }
- }
- }
- /**
- * 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 248 /* EnumDeclaration */:
- case 249 /* ModuleDeclaration */:
- return parseNode === parseNode.parent.name;
- }
- }
- return false;
- }
- ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
- function getInitializedVariables(node) {
- return ts.filter(node.declarations, isInitializedVariable);
- }
- ts.getInitializedVariables = getInitializedVariables;
- function isInitializedVariable(node) {
- return node.initializer !== undefined;
- }
- function isWatchSet(options) {
- // Firefox has Object.prototype.watch
- return options.watch && options.hasOwnProperty("watch");
- }
- ts.isWatchSet = isWatchSet;
- function closeFileWatcher(watcher) {
- watcher.close();
- }
- ts.closeFileWatcher = closeFileWatcher;
- function getCheckFlags(symbol) {
- 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 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
- }
- if (getCheckFlags(s) & 6 /* Synthetic */) {
- var checkFlags = s.checkFlags;
- var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
- checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
- 16 /* Protected */;
- var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
- return accessModifier | staticModifier;
- }
- if (s.flags & 4194304 /* Prototype */) {
- return 4 /* Public */ | 32 /* Static */;
- }
- return 0;
- }
- ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
- function skipAlias(symbol, checker) {
- 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 /* Write */;
- }
- ts.isWriteOnlyAccess = isWriteOnlyAccess;
- function isWriteAccess(node) {
- 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 /* Read */;
- switch (parent.kind) {
- case 200 /* ParenthesizedExpression */:
- return accessKind(parent);
- case 208 /* PostfixUnaryExpression */:
- case 207 /* PrefixUnaryExpression */:
- var operator = parent.operator;
- return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
- case 209 /* BinaryExpression */:
- var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
- return left === node && isAssignmentOperator(operatorToken.kind) ?
- operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
- : 0 /* Read */;
- case 194 /* PropertyAccessExpression */:
- return parent.name !== node ? 0 /* Read */ : accessKind(parent);
- case 281 /* PropertyAssignment */: {
- var parentAccess = accessKind(parent.parent);
- // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
- return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
- }
- case 282 /* ShorthandPropertyAssignment */:
- // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
- return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
- case 192 /* ArrayLiteralExpression */:
- return accessKind(parent);
- default:
- return 0 /* Read */;
- }
- function writeOrReadWrite() {
- // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
- return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
- }
- }
- function reverseAccessKind(a) {
- switch (a) {
- case 0 /* Read */:
- return 1 /* Write */;
- case 1 /* Write */:
- return 0 /* Read */;
- case 2 /* ReadWrite */:
- return 2 /* ReadWrite */;
- default:
- return ts.Debug.assertNever(a);
- }
- }
- function compareDataObjects(dst, src) {
- if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
- return false;
- }
- for (var e in dst) {
- if (typeof dst[e] === "object") {
- if (!compareDataObjects(dst[e], src[e])) {
- return false;
- }
- }
- else if (typeof dst[e] !== "function") {
- if (dst[e] !== src[e]) {
- return false;
- }
- }
- }
- 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 mutateMapSkippingNewValues(map, newMap, options) {
- var 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);
- }
- });
- }
- ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
- /**
- * Mutates the map with newMap such that keys in map will be same as newMap.
- */
- function mutateMap(map, newMap, options) {
- // Needs update
- mutateMapSkippingNewValues(map, newMap, options);
- var createNewValue = options.createNewValue;
- // 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;
- // Return true if the given type is the constructor type for an abstract class
- function isAbstractConstructorType(type) {
- return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
- }
- ts.isAbstractConstructorType = isAbstractConstructorType;
- function isAbstractConstructorSymbol(symbol) {
- if (symbol.flags & 32 /* Class */) {
- var declaration = getClassLikeDeclarationOfSymbol(symbol);
- return !!declaration && hasModifier(declaration, 128 /* Abstract */);
- }
- return false;
- }
- ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
- function getClassLikeDeclarationOfSymbol(symbol) {
- return ts.find(symbol.declarations, ts.isClassLike);
- }
- ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
- function getObjectFlags(type) {
- return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
- }
- ts.getObjectFlags = getObjectFlags;
- function typeHasCallOrConstructSignatures(type, checker) {
- return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
- }
- ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
- function forSomeAncestorDirectory(directory, callback) {
- return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
- }
- ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
- function isUMDExportSymbol(symbol) {
- return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
- }
- ts.isUMDExportSymbol = isUMDExportSymbol;
- function showModuleSpecifier(_a) {
- var moduleSpecifier = _a.moduleSpecifier;
- return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
- }
- ts.showModuleSpecifier = showModuleSpecifier;
- function getLastChild(node) {
- var lastChild;
- ts.forEachChild(node, function (child) {
- 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];
- break;
- }
- }
- });
- return lastChild;
- }
- ts.getLastChild = getLastChild;
- function addToSeen(seen, key, value) {
- if (value === void 0) { value = true; }
- key = String(key);
- if (seen.has(key)) {
- return false;
- }
- seen.set(key, value);
- return true;
- }
- ts.addToSeen = addToSeen;
- function isObjectTypeDeclaration(node) {
- return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
- }
- ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
- function isTypeNodeKind(kind) {
- return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
- || kind === 125 /* AnyKeyword */
- || kind === 148 /* UnknownKeyword */
- || kind === 140 /* NumberKeyword */
- || kind === 151 /* BigIntKeyword */
- || kind === 141 /* ObjectKeyword */
- || kind === 128 /* BooleanKeyword */
- || kind === 143 /* StringKeyword */
- || kind === 144 /* SymbolKeyword */
- || kind === 104 /* ThisKeyword */
- || kind === 110 /* VoidKeyword */
- || kind === 146 /* UndefinedKeyword */
- || kind === 100 /* NullKeyword */
- || kind === 137 /* NeverKeyword */
- || kind === 216 /* ExpressionWithTypeArguments */
- || kind === 295 /* JSDocAllType */
- || kind === 296 /* JSDocUnknownType */
- || kind === 297 /* JSDocNullableType */
- || kind === 298 /* JSDocNonNullableType */
- || kind === 299 /* JSDocOptionalType */
- || kind === 300 /* JSDocFunctionType */
- || kind === 301 /* JSDocVariadicType */;
- }
- ts.isTypeNodeKind = isTypeNodeKind;
- function isAccessExpression(node) {
- return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
- }
- ts.isAccessExpression = isAccessExpression;
- function getNameOfAccessExpression(node) {
- if (node.kind === 194 /* PropertyAccessExpression */) {
- return node.name;
- }
- ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
- return node.argumentExpression;
- }
- ts.getNameOfAccessExpression = getNameOfAccessExpression;
- function isBundleFileTextLike(section) {
- switch (section.kind) {
- case "text" /* Text */:
- case "internal" /* Internal */:
- return true;
- default:
- return false;
- }
- }
- ts.isBundleFileTextLike = isBundleFileTextLike;
- function isNamedImportsOrExports(node) {
- return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
- }
- ts.isNamedImportsOrExports = isNamedImportsOrExports;
- function Symbol(flags, name) {
- this.flags = flags;
- this.escapedName = name;
- this.declarations = undefined;
- this.valueDeclaration = undefined;
- this.id = undefined;
- this.mergeId = undefined;
- this.parent = undefined;
- }
- function Type(checker, flags) {
- this.flags = flags;
- if (ts.Debug.isDebugging) {
- this.checker = checker;
- }
- }
- function Signature(checker, flags) {
- this.flags = flags;
- if (ts.Debug.isDebugging) {
- this.checker = checker;
- }
- }
- function Node(kind, pos, end) {
- this.pos = pos;
- this.end = end;
- this.kind = kind;
- this.id = 0;
- this.flags = 0 /* None */;
- this.modifierFlagsCache = 0 /* None */;
- this.transformFlags = 0 /* None */;
- this.parent = undefined;
- this.original = undefined;
- }
- function Token(kind, pos, end) {
- this.pos = pos;
- this.end = end;
- this.kind = kind;
- this.id = 0;
- this.flags = 0 /* None */;
- this.transformFlags = 0 /* None */;
- this.parent = undefined;
- }
- function Identifier(kind, pos, end) {
- this.pos = pos;
- this.end = end;
- this.kind = kind;
- this.id = 0;
- this.flags = 0 /* None */;
- this.transformFlags = 0 /* None */;
- this.parent = undefined;
- this.original = undefined;
- this.flowNode = undefined;
- }
- function SourceMapSource(fileName, text, skipTrivia) {
- this.fileName = fileName;
- this.text = text;
- this.skipTrivia = skipTrivia || (function (pos) { return pos; });
- }
- // eslint-disable-next-line prefer-const
- ts.objectAllocator = {
- getNodeConstructor: function () { return Node; },
- getTokenConstructor: function () { return Token; },
- getIdentifierConstructor: function () { return Identifier; },
- getPrivateIdentifierConstructor: function () { return Node; },
- getSourceFileConstructor: function () { return Node; },
- getSymbolConstructor: function () { return Symbol; },
- getTypeConstructor: function () { return Type; },
- getSignatureConstructor: function () { return Signature; },
- getSourceMapSourceConstructor: function () { return SourceMapSource; },
- };
- function setObjectAllocator(alloc) {
- ts.objectAllocator = alloc;
- }
- ts.setObjectAllocator = setObjectAllocator;
- function formatStringFromArgs(text, args, baseIndex) {
- if (baseIndex === void 0) { baseIndex = 0; }
- return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
- }
- ts.formatStringFromArgs = formatStringFromArgs;
- /* @internal */
- function setLocalizedDiagnosticMessages(messages) {
- ts.localizedDiagnosticMessages = messages;
- }
- ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
- function getLocaleSpecificMessage(message) {
- return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
- }
- ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
- function createFileDiagnostic(file, start, length, message) {
- ts.Debug.assertGreaterThanOrEqual(start, 0);
- ts.Debug.assertGreaterThanOrEqual(length, 0);
- if (file) {
- ts.Debug.assertLessThanOrEqual(start, file.text.length);
- ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
- }
- var text = getLocaleSpecificMessage(message);
- if (arguments.length > 4) {
- text = formatStringFromArgs(text, arguments, 4);
- }
- return {
- file: file,
- start: start,
- length: length,
- messageText: text,
- category: message.category,
- code: message.code,
- reportsUnnecessary: message.reportsUnnecessary,
- };
- }
- ts.createFileDiagnostic = createFileDiagnostic;
- function formatMessage(_dummy, message) {
- var text = getLocaleSpecificMessage(message);
- if (arguments.length > 2) {
- text = formatStringFromArgs(text, arguments, 2);
- }
- return text;
- }
- ts.formatMessage = formatMessage;
- function createCompilerDiagnostic(message) {
- var text = getLocaleSpecificMessage(message);
- if (arguments.length > 1) {
- text = formatStringFromArgs(text, arguments, 1);
- }
- return {
- file: undefined,
- start: undefined,
- length: undefined,
- messageText: text,
- category: message.category,
- code: message.code,
- reportsUnnecessary: message.reportsUnnecessary,
- };
- }
- ts.createCompilerDiagnostic = createCompilerDiagnostic;
- function createCompilerDiagnosticFromMessageChain(chain) {
- return {
- file: undefined,
- start: undefined,
- length: undefined,
- code: chain.code,
- category: chain.category,
- messageText: chain.next ? chain : chain.messageText,
- };
- }
- ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
- function chainDiagnosticMessages(details, message) {
- var text = getLocaleSpecificMessage(message);
- if (arguments.length > 2) {
- text = formatStringFromArgs(text, arguments, 2);
- }
- return {
- messageText: text,
- category: message.category,
- code: message.code,
- next: details === undefined || Array.isArray(details) ? details : [details]
- };
- }
- ts.chainDiagnosticMessages = chainDiagnosticMessages;
- function concatenateDiagnosticMessageChains(headChain, tailChain) {
- var lastChain = headChain;
- while (lastChain.next) {
- lastChain = lastChain.next[0];
- }
- lastChain.next = [tailChain];
- }
- ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
- function getDiagnosticFilePath(diagnostic) {
- return diagnostic.file ? diagnostic.file.path : undefined;
- }
- function compareDiagnostics(d1, d2) {
- return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
- compareRelatedInformation(d1, d2) ||
- 0 /* EqualTo */;
- }
- ts.compareDiagnostics = compareDiagnostics;
- function compareDiagnosticsSkipRelatedInformation(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 /* EqualTo */;
- }
- ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
- function compareRelatedInformation(d1, d2) {
- if (!d1.relatedInformation && !d2.relatedInformation) {
- return 0 /* EqualTo */;
- }
- if (d1.relatedInformation && d2.relatedInformation) {
- return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
- var d2i = d2.relatedInformation[index];
- return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
- }) || 0 /* EqualTo */;
- }
- return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
- }
- function compareMessageText(t1, t2) {
- if (typeof t1 === "string" && typeof t2 === "string") {
- return ts.compareStringsCaseSensitive(t1, t2);
- }
- else if (typeof t1 === "string") {
- return -1 /* LessThan */;
- }
- else if (typeof t2 === "string") {
- return 1 /* GreaterThan */;
- }
- var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
- if (res) {
- return res;
- }
- if (!t1.next && !t2.next) {
- return 0 /* EqualTo */;
- }
- if (!t1.next) {
- return -1 /* LessThan */;
- }
- if (!t2.next) {
- return 1 /* GreaterThan */;
- }
- var len = Math.min(t1.next.length, t2.next.length);
- for (var i = 0; i < len; i++) {
- res = compareMessageText(t1.next[i], t2.next[i]);
- if (res) {
- return res;
- }
- }
- if (t1.next.length < t2.next.length) {
- return -1 /* LessThan */;
- }
- else if (t1.next.length > t2.next.length) {
- return 1 /* GreaterThan */;
- }
- return 0 /* EqualTo */;
- }
- function getEmitScriptTarget(compilerOptions) {
- return compilerOptions.target || 0 /* ES3 */;
- }
- ts.getEmitScriptTarget = getEmitScriptTarget;
- function getEmitModuleKind(compilerOptions) {
- return typeof compilerOptions.module === "number" ?
- compilerOptions.module :
- getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
- }
- ts.getEmitModuleKind = getEmitModuleKind;
- function getEmitModuleResolutionKind(compilerOptions) {
- var moduleResolution = compilerOptions.moduleResolution;
- if (moduleResolution === undefined) {
- moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
- }
- return moduleResolution;
- }
- ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
- function hasJsonModuleEmitEnabled(options) {
- switch (getEmitModuleKind(options)) {
- case ts.ModuleKind.CommonJS:
- case ts.ModuleKind.AMD:
- case ts.ModuleKind.ES2015:
- case ts.ModuleKind.ES2020:
- case ts.ModuleKind.ESNext:
- return true;
- default:
- return false;
- }
- }
- ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
- function unreachableCodeIsError(options) {
- return options.allowUnreachableCode === false;
- }
- ts.unreachableCodeIsError = unreachableCodeIsError;
- function unusedLabelIsError(options) {
- return options.allowUnusedLabels === false;
- }
- ts.unusedLabelIsError = unusedLabelIsError;
- function getAreDeclarationMapsEnabled(options) {
- return !!(getEmitDeclarations(options) && options.declarationMap);
- }
- ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
- function getAllowSyntheticDefaultImports(compilerOptions) {
- var moduleKind = getEmitModuleKind(compilerOptions);
- return compilerOptions.allowSyntheticDefaultImports !== undefined
- ? compilerOptions.allowSyntheticDefaultImports
- : compilerOptions.esModuleInterop ||
- moduleKind === ts.ModuleKind.System;
- }
- ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
- function getEmitDeclarations(compilerOptions) {
- return !!(compilerOptions.declaration || compilerOptions.composite);
- }
- ts.getEmitDeclarations = getEmitDeclarations;
- function isIncrementalCompilation(options) {
- return !!(options.incremental || options.composite);
- }
- ts.isIncrementalCompilation = isIncrementalCompilation;
- function getStrictOptionValue(compilerOptions, flag) {
- return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
- }
- ts.getStrictOptionValue = getStrictOptionValue;
- function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
- return oldOptions !== newOptions &&
- ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
- }
- ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
- function compilerOptionsAffectEmit(newOptions, oldOptions) {
- return oldOptions !== newOptions &&
- ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
- }
- ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
- function getCompilerOptionValue(options, option) {
- return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
- }
- ts.getCompilerOptionValue = getCompilerOptionValue;
- function hasZeroOrOneAsteriskCharacter(str) {
- var seenAsterisk = false;
- for (var i = 0; i < str.length; i++) {
- if (str.charCodeAt(i) === 42 /* asterisk */) {
- if (!seenAsterisk) {
- seenAsterisk = true;
- }
- else {
- // have already seen asterisk
- return false;
- }
- }
- }
- return true;
- }
- ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
- function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
- var result = ts.createMap();
- var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
- return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
- return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
- })));
- }));
- for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
- var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
- var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
- result.set(commonOriginal, commonResolved);
- }
- return result;
- }
- ts.discoverProbableSymlinks = discoverProbableSymlinks;
- function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
- var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
- var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
- while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
- !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
- getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
- aParts.pop();
- bParts.pop();
- }
- return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
- }
- // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
- // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
- function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
- return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
- }
- function stripLeadingDirectorySeparator(s) {
- return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
- }
- function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
- var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
- return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
- }
- 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;
- function regExpEscape(text) {
- return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
- }
- ts.regExpEscape = regExpEscape;
- function escapeRegExpCharacter(match) {
- return "\\" + match;
- }
- var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
- 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); }
- };
- var excludeMatcher = {
- singleAsteriskRegexFragment: "[^/]*",
- doubleAsteriskRegexFragment: "(/.+?)?",
- replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
- };
- var wildcardMatchers = {
- files: filesMatcher,
- directories: directoriesMatcher,
- exclude: excludeMatcher
- };
- function getRegularExpressionForWildcard(specs, basePath, usage) {
- var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
- if (!patterns || !patterns.length) {
- 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;
- }
- ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
- function getRegularExpressionsForWildcards(specs, basePath, usage) {
- if (specs === undefined || specs.length === 0) {
- return undefined;
- }
- return ts.flatMap(specs, function (spec) {
- return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
- });
- }
- ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
- /**
- * 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);
- }
- ts.isImplicitGlob = isImplicitGlob;
- function getSubPatternFromSpec(spec, basePath, usage, _a) {
- var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
- var subpattern = "";
- var hasWrittenComponent = false;
- var components = ts.getNormalizedPathComponents(spec, basePath);
- var lastComponent = ts.last(components);
- 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] = ts.removeTrailingDirectorySeparator(components[0]);
- if (isImplicitGlob(lastComponent)) {
- components.push("**", "*");
- }
- var optionalCount = 0;
- for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
- var component = components_1[_i];
- if (component === "**") {
- subpattern += doubleAsteriskRegexFragment;
- }
- else {
- if (usage === "directories") {
- subpattern += "(";
- optionalCount++;
- }
- if (hasWrittenComponent) {
- subpattern += ts.directorySeparator;
- }
- if (usage !== "exclude") {
- var componentPattern = "";
- // 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 /* 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;
- }
- subpattern += componentPattern;
- }
- else {
- subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
- }
- }
- hasWrittenComponent = true;
- }
- while (optionalCount > 0) {
- subpattern += ")?";
- optionalCount--;
- }
- return subpattern;
- }
- 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);
- var absolutePath = ts.combinePaths(currentDirectory, path);
- return {
- includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
- includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
- includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
- excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
- basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
- };
- }
- ts.getFileMatcherPatterns = getFileMatcherPatterns;
- function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
- 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, realpath) {
- path = ts.normalizePath(path);
- currentDirectory = ts.normalizePath(currentDirectory);
- var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
- 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 []; }) : [[]];
- var visited = ts.createMap();
- var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
- for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
- var basePath = _a[_i];
- visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
- }
- return ts.flatten(results);
- function visitDirectory(path, absolutePath, depth) {
- var canonicalPath = toCanonical(realpath(absolutePath));
- if (visited.has(canonicalPath))
- return;
- visited.set(canonicalPath, true);
- var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
- var _loop_1 = function (current) {
- var name = ts.combinePaths(path, current);
- var absoluteName = ts.combinePaths(absolutePath, current);
- if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
- return "continue";
- if (excludeRegex && excludeRegex.test(absoluteName))
- return "continue";
- if (!includeFileRegexes) {
- results[0].push(name);
- }
- else {
- var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
- if (includeIndex !== -1) {
- results[includeIndex].push(name);
- }
- }
- };
- for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
- var current = _b[_i];
- _loop_1(current);
- }
- if (depth !== undefined) {
- depth--;
- if (depth === 0) {
- return;
- }
- }
- for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
- var current = _d[_c];
- var name = ts.combinePaths(path, current);
- var absoluteName = ts.combinePaths(absolutePath, current);
- if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
- (!excludeRegex || !excludeRegex.test(absoluteName))) {
- visitDirectory(name, absoluteName, depth);
- }
- }
- }
- }
- 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(ts.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 !ts.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);
- }
- }
- return basePaths;
- }
- function getIncludeBasePath(absolute) {
- var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
- if (wildcardOffset < 0) {
- // No "*" or "?" in the path
- return !ts.hasExtension(absolute)
- ? absolute
- : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
- }
- return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
- }
- function ensureScriptKind(fileName, scriptKind) {
- // 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" /* 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 /* Unknown */;
- }
- }
- ts.getScriptKindFromFileName = getScriptKindFromFileName;
- /**
- * List of supported extensions in order of file resolution precedence.
- */
- ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
- ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
- /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
- ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
- ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
- ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
- var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
- var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
- function getSupportedExtensions(options, extraFileExtensions) {
- var needJsExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0) {
- return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
- }
- var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
- return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- }
- ts.getSupportedExtensions = getSupportedExtensions;
- function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
- if (!options || !options.resolveJsonModule) {
- return supportedExtensions;
- }
- if (supportedExtensions === allSupportedExtensions) {
- return allSupportedExtensionsWithJson;
- }
- if (supportedExtensions === ts.supportedTSExtensions) {
- return ts.supportedTSExtensionsWithJson;
- }
- return __spreadArrays(supportedExtensions, [".json" /* Json */]);
- }
- ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
- function isJSLike(scriptKind) {
- return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
- }
- function hasJSFileExtension(fileName) {
- return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
- }
- ts.hasJSFileExtension = hasJSFileExtension;
- function hasTSFileExtension(fileName) {
- return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
- }
- ts.hasTSFileExtension = hasTSFileExtension;
- function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
- if (!fileName) {
- return false;
- }
- var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
- for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
- var extension = _a[_i];
- if (ts.fileExtensionIs(fileName, extension)) {
- return true;
- }
- }
- 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";
- ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
- ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
- ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
- })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
- function getExtensionPriority(path, supportedExtensions) {
- for (var i = supportedExtensions.length - 1; i >= 0; i--) {
- if (ts.fileExtensionIs(path, supportedExtensions[i])) {
- return adjustExtensionPriority(i, supportedExtensions);
- }
- }
- // 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 /* DeclarationAndJavaScriptFiles */) {
- return 0 /* TypeScriptFiles */;
- }
- else if (extensionPriority < supportedExtensions.length) {
- 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 /* DeclarationAndJavaScriptFiles */) {
- return 2 /* DeclarationAndJavaScriptFiles */;
- }
- else {
- return supportedExtensions.length;
- }
- }
- ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- 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];
- var extensionless = tryRemoveExtension(path, ext);
- if (extensionless !== undefined) {
- return extensionless;
- }
- }
- return path;
- }
- ts.removeFileExtension = removeFileExtension;
- function tryRemoveExtension(path, extension) {
- return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
- }
- ts.tryRemoveExtension = tryRemoveExtension;
- function removeExtension(path, extension) {
- return path.substring(0, path.length - extension.length);
- }
- ts.removeExtension = removeExtension;
- function changeExtension(path, newExtension) {
- return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
- }
- ts.changeExtension = changeExtension;
- function tryParsePattern(pattern) {
- // This should be verified outside of here and a proper error thrown.
- ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
- var indexOfStar = pattern.indexOf("*");
- return indexOfStar === -1 ? undefined : {
- prefix: pattern.substr(0, indexOfStar),
- suffix: pattern.substr(indexOfStar + 1)
- };
- }
- 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 extensionIsTS(ext) {
- return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
- }
- ts.extensionIsTS = extensionIsTS;
- function resolutionExtensionIsTSOrJson(ext) {
- return extensionIsTS(ext) || ext === ".json" /* Json */;
- }
- ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
- /**
- * Gets the extension from a path.
- * Path must have a valid extension.
- */
- function extensionFromPath(path) {
- var ext = tryGetExtensionFromPath(path);
- return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
- }
- ts.extensionFromPath = extensionFromPath;
- function isAnySupportedFileExtension(path) {
- return tryGetExtensionFromPath(path) !== undefined;
- }
- ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
- function tryGetExtensionFromPath(path) {
- return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
- }
- ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
- return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
- }
- ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
- ts.emptyFileSystemEntries = {
- 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++) {
- var patternString = patternStrings_1[_i];
- if (!hasZeroOrOneAsteriskCharacter(patternString))
- continue;
- var pattern = tryParsePattern(patternString);
- if (pattern) {
- patterns.push(pattern);
- }
- else if (patternString === candidate) {
- // pattern was matched as is - no need to search further
- return patternString;
- }
- }
- return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
- }
- ts.matchPatternOrExact = matchPatternOrExact;
- function sliceAfter(arr, value) {
- var index = arr.indexOf(value);
- ts.Debug.assert(index !== -1);
- return arr.slice(index);
- }
- ts.sliceAfter = sliceAfter;
- function addRelatedInfo(diagnostic) {
- var _a;
- var relatedInformation = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- relatedInformation[_i - 1] = arguments[_i];
- }
- if (!relatedInformation.length) {
- return diagnostic;
- }
- if (!diagnostic.relatedInformation) {
- diagnostic.relatedInformation = [];
- }
- (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
- return diagnostic;
- }
- ts.addRelatedInfo = addRelatedInfo;
- function minAndMax(arr, getValue) {
- ts.Debug.assert(arr.length !== 0);
- var min = getValue(arr[0]);
- var max = min;
- for (var i = 1; i < arr.length; i++) {
- var value = getValue(arr[i]);
- if (value < min) {
- min = value;
- }
- else if (value > max) {
- max = value;
- }
- }
- return { min: min, max: max };
- }
- ts.minAndMax = minAndMax;
- var NodeSet = /** @class */ (function () {
- function NodeSet() {
- this.map = ts.createMap();
- }
- NodeSet.prototype.add = function (node) {
- this.map.set(String(ts.getNodeId(node)), node);
- };
- NodeSet.prototype.tryAdd = function (node) {
- if (this.has(node))
- return false;
- this.add(node);
- return true;
- };
- NodeSet.prototype.has = function (node) {
- return this.map.has(String(ts.getNodeId(node)));
- };
- NodeSet.prototype.forEach = function (cb) {
- this.map.forEach(cb);
- };
- NodeSet.prototype.some = function (pred) {
- return forEachEntry(this.map, pred) || false;
- };
- return NodeSet;
- }());
- ts.NodeSet = NodeSet;
- var NodeMap = /** @class */ (function () {
- function NodeMap() {
- this.map = ts.createMap();
- }
- NodeMap.prototype.get = function (node) {
- var res = this.map.get(String(ts.getNodeId(node)));
- return res && res.value;
- };
- NodeMap.prototype.getOrUpdate = function (node, setValue) {
- var res = this.get(node);
- if (res)
- return res;
- var value = setValue();
- this.set(node, value);
- return value;
- };
- NodeMap.prototype.set = function (node, value) {
- this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
- };
- NodeMap.prototype.has = function (node) {
- return this.map.has(String(ts.getNodeId(node)));
- };
- NodeMap.prototype.forEach = function (cb) {
- this.map.forEach(function (_a) {
- var node = _a.node, value = _a.value;
- return cb(value, node);
- });
- };
- return NodeMap;
- }());
- ts.NodeMap = NodeMap;
- function rangeOfNode(node) {
- return { pos: getTokenPosOfNode(node), end: node.end };
- }
- ts.rangeOfNode = rangeOfNode;
- function rangeOfTypeParameters(typeParameters) {
- // Include the `<>`
- return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
- }
- ts.rangeOfTypeParameters = rangeOfTypeParameters;
- function skipTypeChecking(sourceFile, options, host) {
- // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
- // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
- // '/// ' directive.
- return (options.skipLibCheck && sourceFile.isDeclarationFile ||
- options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
- host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
- }
- ts.skipTypeChecking = skipTypeChecking;
- function isJsonEqual(a, b) {
- // eslint-disable-next-line no-null/no-null
- return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
- }
- ts.isJsonEqual = isJsonEqual;
- function getOrUpdate(map, key, getDefault) {
- var got = map.get(key);
- if (got === undefined) {
- var value = getDefault();
- map.set(key, value);
- return value;
- }
- else {
- return got;
- }
- }
- ts.getOrUpdate = getOrUpdate;
- /**
- * Converts a bigint literal string, e.g. `0x1234n`,
- * to its decimal string representation, e.g. `4660`.
- */
- function parsePseudoBigInt(stringValue) {
- var log2Base;
- switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
- case 98 /* b */:
- case 66 /* B */: // 0b or 0B
- log2Base = 1;
- break;
- case 111 /* o */:
- case 79 /* O */: // 0o or 0O
- log2Base = 3;
- break;
- case 120 /* x */:
- case 88 /* X */: // 0x or 0X
- log2Base = 4;
- break;
- default: // already in decimal; omit trailing "n"
- var nIndex = stringValue.length - 1;
- // Skip leading 0s
- var nonZeroStart = 0;
- while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
- nonZeroStart++;
- }
- return stringValue.slice(nonZeroStart, nIndex) || "0";
- }
- // Omit leading "0b", "0o", or "0x", and trailing "n"
- var startIndex = 2, endIndex = stringValue.length - 1;
- var bitsNeeded = (endIndex - startIndex) * log2Base;
- // Stores the value specified by the string as a LE array of 16-bit integers
- // using Uint16 instead of Uint32 so combining steps can use bitwise operators
- var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
- // Add the digits, one at a time
- for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
- var segment = bitOffset >>> 4;
- var digitChar = stringValue.charCodeAt(i);
- // Find character range: 0-9 < A-F < a-f
- var digit = digitChar <= 57 /* _9 */
- ? digitChar - 48 /* _0 */
- : 10 + digitChar -
- (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
- var shiftedDigit = digit << (bitOffset & 15);
- segments[segment] |= shiftedDigit;
- var residual = shiftedDigit >>> 16;
- if (residual)
- segments[segment + 1] |= residual; // overflows segment
- }
- // Repeatedly divide segments by 10 and add remainder to base10Value
- var base10Value = "";
- var firstNonzeroSegment = segments.length - 1;
- var segmentsRemaining = true;
- while (segmentsRemaining) {
- var mod10 = 0;
- segmentsRemaining = false;
- for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
- var newSegment = mod10 << 16 | segments[segment];
- var segmentValue = (newSegment / 10) | 0;
- segments[segment] = segmentValue;
- mod10 = newSegment - segmentValue * 10;
- if (segmentValue && !segmentsRemaining) {
- firstNonzeroSegment = segment;
- segmentsRemaining = true;
- }
- }
- base10Value = mod10 + base10Value;
- }
- return base10Value;
- }
- ts.parsePseudoBigInt = parsePseudoBigInt;
- function pseudoBigIntToString(_a) {
- var negative = _a.negative, base10Value = _a.base10Value;
- return (negative && base10Value !== "0" ? "-" : "") + base10Value;
- }
- ts.pseudoBigIntToString = pseudoBigIntToString;
- function isValidTypeOnlyAliasUseSite(useSite) {
- return !!(useSite.flags & 8388608 /* Ambient */)
- || isPartOfTypeQuery(useSite)
- || isIdentifierInNonEmittingHeritageClause(useSite)
- || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
- || !isExpressionNode(useSite);
- }
- ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
- function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
- return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
- }
- ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
- function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
- while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
- node = node.parent;
- }
- if (node.kind !== 154 /* ComputedPropertyName */) {
- return false;
- }
- if (hasModifier(node.parent, 128 /* Abstract */)) {
- return true;
- }
- var containerKind = node.parent.parent.kind;
- return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
- }
- /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
- function isIdentifierInNonEmittingHeritageClause(node) {
- if (node.kind !== 75 /* Identifier */)
- return false;
- var heritageClause = findAncestor(node.parent, function (parent) {
- switch (parent.kind) {
- case 279 /* HeritageClause */:
- return true;
- case 194 /* PropertyAccessExpression */:
- case 216 /* ExpressionWithTypeArguments */:
- return false;
- default:
- return "quit";
- }
- });
- return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
- }
- function isIdentifierTypeReference(node) {
- return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
- }
- ts.isIdentifierTypeReference = isIdentifierTypeReference;
- function arrayIsHomogeneous(array, comparer) {
- if (comparer === void 0) { comparer = ts.equateValues; }
- if (array.length < 2)
- return true;
- var first = array[0];
- for (var i = 1, length_1 = array.length; i < length_1; i++) {
- var target = array[i];
- if (!comparer(first, target))
- return false;
- }
- return true;
- }
- ts.arrayIsHomogeneous = arrayIsHomogeneous;
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var SignatureFlags;
- (function (SignatureFlags) {
- SignatureFlags[SignatureFlags["None"] = 0] = "None";
- SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
- SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
- SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
- SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
- SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
- })(SignatureFlags || (SignatureFlags = {}));
- var NodeConstructor;
- var TokenConstructor;
- var IdentifierConstructor;
- var PrivateIdentifierConstructor;
- var SourceFileConstructor;
- function createNode(kind, pos, end) {
- if (kind === 290 /* SourceFile */) {
- return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
- }
- else if (kind === 75 /* Identifier */) {
- return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
- }
- else if (kind === 76 /* PrivateIdentifier */) {
- return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
- }
- else if (!ts.isNodeKind(kind)) {
- return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
- }
- else {
- return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
- }
- }
- ts.createNode = createNode;
- function visitNode(cbNode, node) {
- return node && cbNode(node);
- }
- function visitNodes(cbNode, cbNodes, nodes) {
- if (nodes) {
- if (cbNodes) {
- return cbNodes(nodes);
- }
- for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
- var node = nodes_1[_i];
- var result = cbNode(node);
- if (result) {
- return result;
- }
- }
- }
- }
- /*@internal*/
- function isJSDocLikeText(text, start) {
- 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 <= 152 /* LastToken */) {
- return;
- }
- switch (node.kind) {
- case 153 /* QualifiedName */:
- return visitNode(cbNode, node.left) ||
- visitNode(cbNode, node.right);
- case 155 /* TypeParameter */:
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.constraint) ||
- visitNode(cbNode, node.default) ||
- visitNode(cbNode, node.expression);
- case 282 /* ShorthandPropertyAssignment */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.questionToken) ||
- visitNode(cbNode, node.exclamationToken) ||
- visitNode(cbNode, node.equalsToken) ||
- visitNode(cbNode, node.objectAssignmentInitializer);
- case 283 /* SpreadAssignment */:
- return visitNode(cbNode, node.expression);
- case 156 /* Parameter */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.dotDotDotToken) ||
- visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.questionToken) ||
- visitNode(cbNode, node.type) ||
- visitNode(cbNode, node.initializer);
- case 159 /* PropertyDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.questionToken) ||
- visitNode(cbNode, node.exclamationToken) ||
- visitNode(cbNode, node.type) ||
- visitNode(cbNode, node.initializer);
- case 158 /* 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 281 /* 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 242 /* 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 191 /* 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 170 /* FunctionType */:
- case 171 /* ConstructorType */:
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* 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 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 201 /* FunctionExpression */:
- case 244 /* FunctionDeclaration */:
- case 202 /* ArrowFunction */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.asteriskToken) ||
- visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.questionToken) ||
- visitNode(cbNode, node.exclamationToken) ||
- visitNodes(cbNode, cbNodes, node.typeParameters) ||
- visitNodes(cbNode, cbNodes, node.parameters) ||
- visitNode(cbNode, node.type) ||
- visitNode(cbNode, node.equalsGreaterThanToken) ||
- visitNode(cbNode, node.body);
- case 169 /* TypeReference */:
- return visitNode(cbNode, node.typeName) ||
- visitNodes(cbNode, cbNodes, node.typeArguments);
- case 168 /* TypePredicate */:
- return visitNode(cbNode, node.assertsModifier) ||
- visitNode(cbNode, node.parameterName) ||
- visitNode(cbNode, node.type);
- case 172 /* TypeQuery */:
- return visitNode(cbNode, node.exprName);
- case 173 /* TypeLiteral */:
- return visitNodes(cbNode, cbNodes, node.members);
- case 174 /* ArrayType */:
- return visitNode(cbNode, node.elementType);
- case 175 /* TupleType */:
- return visitNodes(cbNode, cbNodes, node.elementTypes);
- case 178 /* UnionType */:
- case 179 /* IntersectionType */:
- return visitNodes(cbNode, cbNodes, node.types);
- case 180 /* ConditionalType */:
- return visitNode(cbNode, node.checkType) ||
- visitNode(cbNode, node.extendsType) ||
- visitNode(cbNode, node.trueType) ||
- visitNode(cbNode, node.falseType);
- case 181 /* InferType */:
- return visitNode(cbNode, node.typeParameter);
- case 188 /* ImportType */:
- return visitNode(cbNode, node.argument) ||
- visitNode(cbNode, node.qualifier) ||
- visitNodes(cbNode, cbNodes, node.typeArguments);
- case 182 /* ParenthesizedType */:
- case 184 /* TypeOperator */:
- return visitNode(cbNode, node.type);
- case 185 /* IndexedAccessType */:
- return visitNode(cbNode, node.objectType) ||
- visitNode(cbNode, node.indexType);
- case 186 /* MappedType */:
- return visitNode(cbNode, node.readonlyToken) ||
- visitNode(cbNode, node.typeParameter) ||
- visitNode(cbNode, node.questionToken) ||
- visitNode(cbNode, node.type);
- case 187 /* LiteralType */:
- return visitNode(cbNode, node.literal);
- case 189 /* ObjectBindingPattern */:
- case 190 /* ArrayBindingPattern */:
- return visitNodes(cbNode, cbNodes, node.elements);
- case 192 /* ArrayLiteralExpression */:
- return visitNodes(cbNode, cbNodes, node.elements);
- case 193 /* ObjectLiteralExpression */:
- return visitNodes(cbNode, cbNodes, node.properties);
- case 194 /* PropertyAccessExpression */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.questionDotToken) ||
- visitNode(cbNode, node.name);
- case 195 /* ElementAccessExpression */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.questionDotToken) ||
- visitNode(cbNode, node.argumentExpression);
- case 196 /* CallExpression */:
- case 197 /* NewExpression */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.questionDotToken) ||
- visitNodes(cbNode, cbNodes, node.typeArguments) ||
- visitNodes(cbNode, cbNodes, node.arguments);
- case 198 /* TaggedTemplateExpression */:
- return visitNode(cbNode, node.tag) ||
- visitNode(cbNode, node.questionDotToken) ||
- visitNodes(cbNode, cbNodes, node.typeArguments) ||
- visitNode(cbNode, node.template);
- case 199 /* TypeAssertionExpression */:
- return visitNode(cbNode, node.type) ||
- visitNode(cbNode, node.expression);
- case 200 /* ParenthesizedExpression */:
- return visitNode(cbNode, node.expression);
- case 203 /* DeleteExpression */:
- return visitNode(cbNode, node.expression);
- case 204 /* TypeOfExpression */:
- return visitNode(cbNode, node.expression);
- case 205 /* VoidExpression */:
- return visitNode(cbNode, node.expression);
- case 207 /* PrefixUnaryExpression */:
- return visitNode(cbNode, node.operand);
- case 212 /* YieldExpression */:
- return visitNode(cbNode, node.asteriskToken) ||
- visitNode(cbNode, node.expression);
- case 206 /* AwaitExpression */:
- return visitNode(cbNode, node.expression);
- case 208 /* PostfixUnaryExpression */:
- return visitNode(cbNode, node.operand);
- case 209 /* BinaryExpression */:
- return visitNode(cbNode, node.left) ||
- visitNode(cbNode, node.operatorToken) ||
- visitNode(cbNode, node.right);
- case 217 /* AsExpression */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.type);
- case 218 /* NonNullExpression */:
- return visitNode(cbNode, node.expression);
- case 219 /* MetaProperty */:
- return visitNode(cbNode, node.name);
- case 210 /* ConditionalExpression */:
- return visitNode(cbNode, node.condition) ||
- visitNode(cbNode, node.questionToken) ||
- visitNode(cbNode, node.whenTrue) ||
- visitNode(cbNode, node.colonToken) ||
- visitNode(cbNode, node.whenFalse);
- case 213 /* SpreadElement */:
- return visitNode(cbNode, node.expression);
- case 223 /* Block */:
- case 250 /* ModuleBlock */:
- return visitNodes(cbNode, cbNodes, node.statements);
- case 290 /* SourceFile */:
- return visitNodes(cbNode, cbNodes, node.statements) ||
- visitNode(cbNode, node.endOfFileToken);
- case 225 /* VariableStatement */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.declarationList);
- case 243 /* VariableDeclarationList */:
- return visitNodes(cbNode, cbNodes, node.declarations);
- case 226 /* ExpressionStatement */:
- return visitNode(cbNode, node.expression);
- case 227 /* IfStatement */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.thenStatement) ||
- visitNode(cbNode, node.elseStatement);
- case 228 /* DoStatement */:
- return visitNode(cbNode, node.statement) ||
- visitNode(cbNode, node.expression);
- case 229 /* WhileStatement */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.statement);
- case 230 /* ForStatement */:
- return visitNode(cbNode, node.initializer) ||
- visitNode(cbNode, node.condition) ||
- visitNode(cbNode, node.incrementor) ||
- visitNode(cbNode, node.statement);
- case 231 /* ForInStatement */:
- return visitNode(cbNode, node.initializer) ||
- visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.statement);
- case 232 /* ForOfStatement */:
- return visitNode(cbNode, node.awaitModifier) ||
- visitNode(cbNode, node.initializer) ||
- visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.statement);
- case 233 /* ContinueStatement */:
- case 234 /* BreakStatement */:
- return visitNode(cbNode, node.label);
- case 235 /* ReturnStatement */:
- return visitNode(cbNode, node.expression);
- case 236 /* WithStatement */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.statement);
- case 237 /* SwitchStatement */:
- return visitNode(cbNode, node.expression) ||
- visitNode(cbNode, node.caseBlock);
- case 251 /* CaseBlock */:
- return visitNodes(cbNode, cbNodes, node.clauses);
- case 277 /* CaseClause */:
- return visitNode(cbNode, node.expression) ||
- visitNodes(cbNode, cbNodes, node.statements);
- case 278 /* DefaultClause */:
- return visitNodes(cbNode, cbNodes, node.statements);
- case 238 /* LabeledStatement */:
- return visitNode(cbNode, node.label) ||
- visitNode(cbNode, node.statement);
- case 239 /* ThrowStatement */:
- return visitNode(cbNode, node.expression);
- case 240 /* TryStatement */:
- return visitNode(cbNode, node.tryBlock) ||
- visitNode(cbNode, node.catchClause) ||
- visitNode(cbNode, node.finallyBlock);
- case 280 /* CatchClause */:
- return visitNode(cbNode, node.variableDeclaration) ||
- visitNode(cbNode, node.block);
- case 157 /* Decorator */:
- return visitNode(cbNode, node.expression);
- case 245 /* ClassDeclaration */:
- case 214 /* 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 246 /* 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 247 /* 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 248 /* EnumDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.name) ||
- visitNodes(cbNode, cbNodes, node.members);
- case 284 /* EnumMember */:
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.initializer);
- case 249 /* ModuleDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.body);
- case 253 /* ImportEqualsDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.moduleReference);
- case 254 /* ImportDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.importClause) ||
- visitNode(cbNode, node.moduleSpecifier);
- case 255 /* ImportClause */:
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.namedBindings);
- case 252 /* NamespaceExportDeclaration */:
- return visitNode(cbNode, node.name);
- case 256 /* NamespaceImport */:
- return visitNode(cbNode, node.name);
- case 262 /* NamespaceExport */:
- return visitNode(cbNode, node.name);
- case 257 /* NamedImports */:
- case 261 /* NamedExports */:
- return visitNodes(cbNode, cbNodes, node.elements);
- case 260 /* ExportDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.exportClause) ||
- visitNode(cbNode, node.moduleSpecifier);
- case 258 /* ImportSpecifier */:
- case 263 /* ExportSpecifier */:
- return visitNode(cbNode, node.propertyName) ||
- visitNode(cbNode, node.name);
- case 259 /* ExportAssignment */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- visitNode(cbNode, node.expression);
- case 211 /* TemplateExpression */:
- return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
- case 221 /* TemplateSpan */:
- return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
- case 154 /* ComputedPropertyName */:
- return visitNode(cbNode, node.expression);
- case 279 /* HeritageClause */:
- return visitNodes(cbNode, cbNodes, node.types);
- case 216 /* ExpressionWithTypeArguments */:
- return visitNode(cbNode, node.expression) ||
- visitNodes(cbNode, cbNodes, node.typeArguments);
- case 265 /* ExternalModuleReference */:
- return visitNode(cbNode, node.expression);
- case 264 /* MissingDeclaration */:
- return visitNodes(cbNode, cbNodes, node.decorators);
- case 327 /* CommaListExpression */:
- return visitNodes(cbNode, cbNodes, node.elements);
- case 266 /* JsxElement */:
- return visitNode(cbNode, node.openingElement) ||
- visitNodes(cbNode, cbNodes, node.children) ||
- visitNode(cbNode, node.closingElement);
- case 270 /* JsxFragment */:
- return visitNode(cbNode, node.openingFragment) ||
- visitNodes(cbNode, cbNodes, node.children) ||
- visitNode(cbNode, node.closingFragment);
- case 267 /* JsxSelfClosingElement */:
- case 268 /* JsxOpeningElement */:
- return visitNode(cbNode, node.tagName) ||
- visitNodes(cbNode, cbNodes, node.typeArguments) ||
- visitNode(cbNode, node.attributes);
- case 274 /* JsxAttributes */:
- return visitNodes(cbNode, cbNodes, node.properties);
- case 273 /* JsxAttribute */:
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.initializer);
- case 275 /* JsxSpreadAttribute */:
- return visitNode(cbNode, node.expression);
- case 276 /* JsxExpression */:
- return visitNode(cbNode, node.dotDotDotToken) ||
- visitNode(cbNode, node.expression);
- case 269 /* JsxClosingElement */:
- return visitNode(cbNode, node.tagName);
- case 176 /* OptionalType */:
- case 177 /* RestType */:
- case 294 /* JSDocTypeExpression */:
- case 298 /* JSDocNonNullableType */:
- case 297 /* JSDocNullableType */:
- case 299 /* JSDocOptionalType */:
- case 301 /* JSDocVariadicType */:
- return visitNode(cbNode, node.type);
- case 300 /* JSDocFunctionType */:
- return visitNodes(cbNode, cbNodes, node.parameters) ||
- visitNode(cbNode, node.type);
- case 303 /* JSDocComment */:
- return visitNodes(cbNode, cbNodes, node.tags);
- case 317 /* JSDocParameterTag */:
- case 323 /* JSDocPropertyTag */:
- return visitNode(cbNode, node.tagName) ||
- (node.isNameFirst
- ? visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression)
- : visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name));
- case 309 /* JSDocAuthorTag */:
- return visitNode(cbNode, node.tagName);
- case 308 /* JSDocImplementsTag */:
- return visitNode(cbNode, node.tagName) ||
- visitNode(cbNode, node.class);
- case 307 /* JSDocAugmentsTag */:
- return visitNode(cbNode, node.tagName) ||
- visitNode(cbNode, node.class);
- case 321 /* JSDocTemplateTag */:
- return visitNode(cbNode, node.tagName) ||
- visitNode(cbNode, node.constraint) ||
- visitNodes(cbNode, cbNodes, node.typeParameters);
- case 322 /* JSDocTypedefTag */:
- return visitNode(cbNode, node.tagName) ||
- (node.typeExpression &&
- node.typeExpression.kind === 294 /* JSDocTypeExpression */
- ? visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName)
- : visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression));
- case 315 /* JSDocCallbackTag */:
- return visitNode(cbNode, node.tagName) ||
- visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- case 318 /* JSDocReturnTag */:
- case 320 /* JSDocTypeTag */:
- case 319 /* JSDocThisTag */:
- case 316 /* JSDocEnumTag */:
- return visitNode(cbNode, node.tagName) ||
- visitNode(cbNode, node.typeExpression);
- case 305 /* JSDocSignature */:
- return ts.forEach(node.typeParameters, cbNode) ||
- ts.forEach(node.parameters, cbNode) ||
- visitNode(cbNode, node.type);
- case 304 /* JSDocTypeLiteral */:
- return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 306 /* JSDocTag */:
- case 310 /* JSDocClassTag */:
- case 311 /* JSDocPublicTag */:
- case 312 /* JSDocPrivateTag */:
- case 313 /* JSDocProtectedTag */:
- case 314 /* JSDocReadonlyTag */:
- return visitNode(cbNode, node.tagName);
- case 326 /* PartiallyEmittedExpression */:
- return visitNode(cbNode, node.expression);
- }
- }
- ts.forEachChild = forEachChild;
- /** @internal */
- /**
- * 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; additionally,
- * unlike `forEachChild`, 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 Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
- * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
- */
- function forEachChildRecursively(rootNode, cbNode, cbNodes) {
- var stack = [rootNode];
- while (stack.length) {
- var parent = stack.pop();
- var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
- if (res) {
- return res;
- }
- }
- return;
- function gatherPossibleChildren(node) {
- var children = [];
- forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
- return children;
- function addWorkItem(n) {
- children.unshift(n);
- }
- }
- function visitAllPossibleChildren(parent, children) {
- for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
- var child = children_1[_i];
- if (ts.isArray(child)) {
- if (cbNodes) {
- var res = cbNodes(child, parent);
- if (res) {
- if (res === "skip")
- continue;
- return res;
- }
- }
- for (var i = child.length - 1; i >= 0; i--) {
- var realChild = child[i];
- var res = cbNode(realChild, parent);
- if (res) {
- if (res === "skip")
- continue;
- return res;
- }
- stack.push(realChild);
- }
- }
- else {
- stack.push(child);
- var res = cbNode(child, parent);
- if (res) {
- if (res === "skip")
- continue;
- return res;
- }
- }
- }
- }
- }
- ts.forEachChildRecursively = forEachChildRecursively;
- function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
- if (setParentNodes === void 0) { setParentNodes = false; }
- ts.performance.mark("beforeParse");
- var result;
- ts.perfLogger.logStartParseSourceFile(fileName);
- if (languageVersion === 100 /* JSON */) {
- result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
- }
- else {
- result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
- }
- ts.perfLogger.logStopParseSourceFile();
- ts.performance.mark("afterParse");
- ts.performance.measure("Parse", "beforeParse", "afterParse");
- return result;
- }
- ts.createSourceFile = createSourceFile;
- function parseIsolatedEntityName(text, languageVersion) {
- 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);
- // 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 & 3145728 /* 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) {
- // 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(99 /* Latest */, /*skipTrivia*/ true);
- var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
- // capture constructors in 'initializeState' to avoid null checks
- var NodeConstructor;
- var TokenConstructor;
- var IdentifierConstructor;
- var PrivateIdentifierConstructor;
- var SourceFileConstructor;
- var sourceFile;
- var parseDiagnostics;
- var syntaxCursor;
- var currentToken;
- var sourceText;
- var nodeCount;
- var identifiers;
- var privateIdentifiers;
- var identifierCount;
- var parsingContext;
- var notParenthesizedArrow;
- // 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 /* JSON */) {
- var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
- ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
- result_2.referencedFiles = ts.emptyArray;
- result_2.typeReferenceDirectives = ts.emptyArray;
- result_2.libReferenceDirectives = ts.emptyArray;
- result_2.amdDependencies = ts.emptyArray;
- result_2.hasNoDefaultLib = false;
- result_2.pragmas = ts.emptyMap;
- return result_2;
- }
- initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
- var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
- clearState();
- return result;
- }
- Parser.parseSourceFile = parseSourceFile;
- function parseIsolatedEntityName(content, languageVersion) {
- // Choice of `isDeclarationFile` should be arbitrary
- initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
- // Prime the scanner.
- nextToken();
- 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 /* 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 /* EndOfFileToken */) {
- sourceFile.statements = createNodeArray([], pos, pos);
- sourceFile.endOfFileToken = parseTokenNode();
- }
- else {
- var statement = createNode(226 /* ExpressionStatement */);
- switch (token()) {
- case 22 /* OpenBracketToken */:
- statement.expression = parseArrayLiteralExpression();
- break;
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- case 100 /* NullKeyword */:
- statement.expression = parseTokenNode();
- break;
- case 40 /* MinusToken */:
- if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
- statement.expression = parsePrefixUnaryExpression();
- }
- else {
- statement.expression = parseObjectLiteralExpression();
- }
- break;
- case 8 /* NumericLiteral */:
- case 10 /* StringLiteral */:
- if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
- statement.expression = parseLiteralNode();
- break;
- }
- // falls through
- default:
- statement.expression = parseObjectLiteralExpression();
- break;
- }
- finishNode(statement);
- sourceFile.statements = createNodeArray([statement], pos);
- sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
- }
- if (setParentNodes) {
- fixupParentReferences(sourceFile);
- }
- sourceFile.nodeCount = nodeCount;
- sourceFile.identifierCount = identifierCount;
- sourceFile.identifiers = identifiers;
- sourceFile.parseDiagnostics = parseDiagnostics;
- var result = sourceFile;
- clearState();
- return result;
- }
- Parser.parseJsonText = parseJsonText;
- function getLanguageVariant(scriptKind) {
- // .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();
- TokenConstructor = ts.objectAllocator.getTokenConstructor();
- IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
- PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
- SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
- sourceText = _sourceText;
- syntaxCursor = _syntaxCursor;
- parseDiagnostics = [];
- parsingContext = 0;
- identifiers = ts.createMap();
- privateIdentifiers = ts.createMap();
- identifierCount = 0;
- nodeCount = 0;
- switch (scriptKind) {
- case 1 /* JS */:
- case 2 /* JSX */:
- contextFlags = 131072 /* JavaScriptFile */;
- break;
- case 6 /* JSON */:
- contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
- break;
- default:
- 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.clearCommentDirectives();
- 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;
- syntaxCursor = undefined;
- sourceText = undefined;
- notParenthesizedArrow = undefined;
- }
- function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
- var isDeclarationFile = isDeclarationFileName(fileName);
- if (isDeclarationFile) {
- contextFlags |= 8388608 /* 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 /* SourceElements */, parseStatement);
- ts.Debug.assert(token() === 1 /* EndOfFileToken */);
- sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
- setExternalModuleIndicator(sourceFile);
- sourceFile.commentDirectives = scanner.getCommentDirectives();
- sourceFile.nodeCount = nodeCount;
- sourceFile.identifierCount = identifierCount;
- sourceFile.identifiers = identifiers;
- sourceFile.parseDiagnostics = parseDiagnostics;
- if (setParentNodes) {
- fixupParentReferences(sourceFile);
- }
- return sourceFile;
- function reportPragmaDiagnostic(pos, end, diagnostic) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
- }
- }
- function addJSDocComment(node) {
- ts.Debug.assert(!node.jsDoc); // Should only be called once per node
- var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
- if (jsDoc.length)
- node.jsDoc = jsDoc;
- 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.
- forEachChildRecursively(rootNode, bindParentToChild);
- function bindParentToChild(child, parent) {
- child.parent = parent;
- if (ts.hasJSDocNodes(child)) {
- for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
- var doc = _a[_i];
- bindParentToChild(doc, child);
- forEachChildRecursively(doc, bindParentToChild);
- }
- }
- }
- }
- Parser.fixupParentReferences = fixupParentReferences;
- function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
- // 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(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
- nodeCount++;
- sourceFile.text = sourceText;
- sourceFile.bindDiagnostics = [];
- sourceFile.bindSuggestionDiagnostics = undefined;
- sourceFile.languageVersion = languageVersion;
- sourceFile.fileName = ts.normalizePath(fileName);
- sourceFile.languageVariant = getLanguageVariant(scriptKind);
- sourceFile.isDeclarationFile = isDeclarationFile;
- sourceFile.scriptKind = scriptKind;
- return sourceFile;
- }
- function setContextFlag(val, flag) {
- if (val) {
- contextFlags |= flag;
- }
- else {
- contextFlags &= ~flag;
- }
- }
- function setDisallowInContext(val) {
- setContextFlag(val, 4096 /* DisallowInContext */);
- }
- function setYieldContext(val) {
- setContextFlag(val, 8192 /* YieldContext */);
- }
- function setDecoratorContext(val) {
- setContextFlag(val, 16384 /* DecoratorContext */);
- }
- function setAwaitContext(val) {
- setContextFlag(val, 32768 /* 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) {
- // clear the requested context flags
- setContextFlag(/*val*/ false, contextFlagsToClear);
- var result = func();
- // 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) {
- // set the requested context flags
- setContextFlag(/*val*/ true, contextFlagsToSet);
- var result = func();
- // 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(4096 /* DisallowInContext */, func);
- }
- function disallowInAnd(func) {
- return doInsideOfContext(4096 /* DisallowInContext */, func);
- }
- function doInYieldContext(func) {
- return doInsideOfContext(8192 /* YieldContext */, func);
- }
- function doInDecoratorContext(func) {
- return doInsideOfContext(16384 /* DecoratorContext */, func);
- }
- function doInAwaitContext(func) {
- return doInsideOfContext(32768 /* AwaitContext */, func);
- }
- function doOutsideOfAwaitContext(func) {
- return doOutsideOfContext(32768 /* AwaitContext */, func);
- }
- function doInYieldAndAwaitContext(func) {
- return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
- }
- function doOutsideOfYieldAndAwaitContext(func) {
- return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
- }
- function inContext(flags) {
- return (contextFlags & flags) !== 0;
- }
- function inYieldContext() {
- return inContext(8192 /* YieldContext */);
- }
- function inDisallowInContext() {
- return inContext(4096 /* DisallowInContext */);
- }
- function inDecoratorContext() {
- return inContext(16384 /* DecoratorContext */);
- }
- function inAwaitContext() {
- return inContext(32768 /* 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) {
- parseErrorAtPosition(start, end - start, message, arg0);
- }
- function parseErrorAtRange(range, message, arg0) {
- parseErrorAt(range.pos, range.end, message, arg0);
- }
- function scanError(message, length) {
- parseErrorAtPosition(scanner.getTextPos(), length, message);
- }
- 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;
- }
- function nextTokenWithoutCheck() {
- return currentToken = scanner.scan();
- }
- function nextToken() {
- // if the keyword had an escape
- if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
- // issue a parse error for the escape
- parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
- }
- return nextTokenWithoutCheck();
- }
- function nextTokenJSDoc() {
- return currentToken = scanner.scanJsDocToken();
- }
- function reScanGreaterToken() {
- return currentToken = scanner.reScanGreaterToken();
- }
- function reScanSlashToken() {
- return currentToken = scanner.reScanSlashToken();
- }
- function reScanTemplateToken(isTaggedTemplate) {
- return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
- }
- function reScanTemplateHeadOrNoSubstitutionTemplate() {
- return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
- }
- function reScanLessThanToken() {
- return currentToken = scanner.reScanLessThanToken();
- }
- function scanJsxIdentifier() {
- return currentToken = scanner.scanJsxIdentifier();
- }
- function scanJsxText() {
- return currentToken = scanner.scanJsxToken();
- }
- function scanJsxAttributeValue() {
- 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;
- parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
- }
- 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, /*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, /*isLookAhead*/ false);
- }
- // Ignore strict mode flag because we will report an error in type checker instead.
- function isIdentifier() {
- if (token() === 75 /* Identifier */) {
- return true;
- }
- // 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() === 121 /* YieldKeyword */ && inYieldContext()) {
- return false;
- }
- // 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() === 127 /* AwaitKeyword */ && inAwaitContext()) {
- return false;
- }
- return token() > 112 /* LastReservedWord */;
- }
- function parseExpected(kind, diagnosticMessage, shouldAdvance) {
- if (shouldAdvance === void 0) { shouldAdvance = true; }
- if (token() === kind) {
- if (shouldAdvance) {
- nextToken();
- }
- return true;
- }
- // Report specific message if provided with one. Otherwise, report generic fallback message.
- if (diagnosticMessage) {
- parseErrorAtCurrentToken(diagnosticMessage);
- }
- else {
- parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
- }
- return false;
- }
- function parseExpectedJSDoc(kind) {
- if (token() === kind) {
- nextTokenJSDoc();
- return true;
- }
- parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
- return false;
- }
- function parseOptional(t) {
- if (token() === t) {
- nextToken();
- return true;
- }
- return false;
- }
- function parseOptionalToken(t) {
- if (token() === t) {
- return parseTokenNode();
- }
- return undefined;
- }
- function parseOptionalTokenJSDoc(t) {
- if (token() === t) {
- return parseTokenNodeJSDoc();
- }
- return undefined;
- }
- function parseExpectedToken(t, diagnosticMessage, arg0) {
- return parseOptionalToken(t) ||
- createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
- }
- function parseExpectedTokenJSDoc(t) {
- return parseOptionalTokenJSDoc(t) ||
- createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
- }
- function parseTokenNode() {
- var node = createNode(token());
- nextToken();
- return finishNode(node);
- }
- function parseTokenNodeJSDoc() {
- var node = createNode(token());
- nextTokenJSDoc();
- return finishNode(node);
- }
- function canParseSemicolon() {
- // If there's a real semicolon, then we can always parse it out.
- if (token() === 26 /* SemicolonToken */) {
- return true;
- }
- // We can parse out an optional semicolon in ASI cases in the following cases.
- return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
- }
- function parseSemicolon() {
- if (canParseSemicolon()) {
- if (token() === 26 /* SemicolonToken */) {
- // consume the semicolon if it was explicitly provided.
- nextToken();
- }
- return true;
- }
- else {
- return parseExpected(26 /* SemicolonToken */);
- }
- }
- function createNode(kind, pos) {
- nodeCount++;
- var p = pos >= 0 ? pos : scanner.getStartPos();
- return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
- kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
- kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
- new TokenConstructor(kind, p, p);
- }
- function createNodeWithJSDoc(kind, pos) {
- var node = createNode(kind, pos);
- if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
- 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;
- array.end = end === undefined ? scanner.getStartPos() : end;
- return array;
- }
- function finishNode(node, end) {
- node.end = end === undefined ? scanner.getStartPos() : end;
- 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 |= 65536 /* ThisNodeHasError */;
- }
- return node;
- }
- function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
- if (reportAtCurrentPosition) {
- parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
- }
- else if (diagnosticMessage) {
- parseErrorAtCurrentToken(diagnosticMessage, arg0);
- }
- var result = createNode(kind);
- if (kind === 75 /* Identifier */) {
- result.escapedText = "";
- }
- else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
- result.text = "";
- }
- return finishNode(result);
- }
- function internIdentifier(text) {
- var identifier = identifiers.get(text);
- if (identifier === undefined) {
- identifiers.set(text, identifier = text);
- }
- 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, privateIdentifierDiagnosticMessage) {
- identifierCount++;
- if (isIdentifier) {
- var node = createNode(75 /* Identifier */);
- // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
- if (token() !== 75 /* Identifier */) {
- node.originalKeywordKind = token();
- }
- node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
- nextTokenWithoutCheck();
- return finishNode(node);
- }
- if (token() === 76 /* PrivateIdentifier */) {
- parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
- return createIdentifier(/*isIdentifier*/ true);
- }
- // Only for end of file because the error gets reported incorrectly on embedded script tags.
- var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
- var isReservedWord = scanner.isReservedWord();
- var msgArg = scanner.getTokenText();
- var defaultMessage = isReservedWord ?
- ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
- ts.Diagnostics.Identifier_expected;
- return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
- }
- function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
- return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
- }
- function parseIdentifierName(diagnosticMessage) {
- return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
- }
- function isLiteralPropertyName() {
- return ts.tokenIsIdentifierOrKeyword(token()) ||
- token() === 10 /* StringLiteral */ ||
- token() === 8 /* NumericLiteral */;
- }
- function parsePropertyNameWorker(allowComputedPropertyNames) {
- if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
- var node = parseLiteralNode();
- node.text = internIdentifier(node.text);
- return node;
- }
- if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
- return parseComputedPropertyName();
- }
- if (token() === 76 /* PrivateIdentifier */) {
- return parsePrivateIdentifier();
- }
- return parseIdentifierName();
- }
- function parsePropertyName() {
- return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
- }
- function parseComputedPropertyName() {
- // PropertyName [Yield]:
- // LiteralPropertyName
- // ComputedPropertyName[?Yield]
- var node = createNode(154 /* ComputedPropertyName */);
- parseExpected(22 /* 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(23 /* CloseBracketToken */);
- return finishNode(node);
- }
- function internPrivateIdentifier(text) {
- var privateIdentifier = privateIdentifiers.get(text);
- if (privateIdentifier === undefined) {
- privateIdentifiers.set(text, privateIdentifier = text);
- }
- return privateIdentifier;
- }
- function parsePrivateIdentifier() {
- var node = createNode(76 /* PrivateIdentifier */);
- node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
- nextToken();
- return finishNode(node);
- }
- function parseContextualModifier(t) {
- return token() === t && tryParse(nextTokenCanFollowModifier);
- }
- function nextTokenIsOnSameLineAndCanFollowModifier() {
- nextToken();
- if (scanner.hasPrecedingLineBreak()) {
- return false;
- }
- return canFollowModifier();
- }
- function nextTokenCanFollowModifier() {
- switch (token()) {
- case 81 /* ConstKeyword */:
- // 'const' is only a modifier if followed by 'enum'.
- return nextToken() === 88 /* EnumKeyword */;
- case 89 /* ExportKeyword */:
- nextToken();
- if (token() === 84 /* DefaultKeyword */) {
- return lookAhead(nextTokenCanFollowDefaultKeyword);
- }
- if (token() === 145 /* TypeKeyword */) {
- return lookAhead(nextTokenCanFollowExportModifier);
- }
- return canFollowExportModifier();
- case 84 /* DefaultKeyword */:
- return nextTokenCanFollowDefaultKeyword();
- case 120 /* StaticKeyword */:
- case 131 /* GetKeyword */:
- case 142 /* SetKeyword */:
- nextToken();
- return canFollowModifier();
- default:
- return nextTokenIsOnSameLineAndCanFollowModifier();
- }
- }
- function canFollowExportModifier() {
- return token() !== 41 /* AsteriskToken */
- && token() !== 123 /* AsKeyword */
- && token() !== 18 /* OpenBraceToken */
- && canFollowModifier();
- }
- function nextTokenCanFollowExportModifier() {
- nextToken();
- return canFollowExportModifier();
- }
- function parseAnyContextualModifier() {
- return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
- }
- function canFollowModifier() {
- return token() === 22 /* OpenBracketToken */
- || token() === 18 /* OpenBraceToken */
- || token() === 41 /* AsteriskToken */
- || token() === 25 /* DotDotDotToken */
- || isLiteralPropertyName();
- }
- function nextTokenCanFollowDefaultKeyword() {
- nextToken();
- return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
- token() === 114 /* InterfaceKeyword */ ||
- (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
- (token() === 126 /* 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 /* 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() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
- case 2 /* SwitchClauses */:
- return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
- case 4 /* TypeMembers */:
- return lookAhead(isTypeMemberStart);
- 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() === 26 /* 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() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
- case 12 /* ObjectLiteralMembers */:
- switch (token()) {
- case 22 /* OpenBracketToken */:
- case 41 /* AsteriskToken */:
- case 25 /* DotDotDotToken */:
- case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
- return true;
- default:
- return isLiteralPropertyName();
- }
- case 18 /* RestProperties */:
- return isLiteralPropertyName();
- case 9 /* ObjectBindingElements */:
- return token() === 22 /* OpenBracketToken */ || token() === 25 /* 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() === 18 /* 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 /* VariableDeclarations */:
- return isIdentifierOrPrivateIdentifierOrPattern();
- case 10 /* ArrayBindingElements */:
- return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
- case 19 /* TypeParameters */:
- return isIdentifier();
- case 15 /* ArrayLiteralMembers */:
- switch (token()) {
- case 27 /* CommaToken */:
- case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
- return true;
- }
- // falls through
- case 11 /* ArgumentExpressions */:
- return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
- case 16 /* Parameters */:
- return isStartOfParameter(/*isJSDocParameter*/ false);
- case 17 /* JSDocParameters */:
- return isStartOfParameter(/*isJSDocParameter*/ true);
- case 20 /* TypeArguments */:
- case 21 /* TupleElementTypes */:
- return token() === 27 /* CommaToken */ || isStartOfType();
- case 22 /* HeritageClauses */:
- return isHeritageClause();
- case 23 /* ImportOrExportSpecifiers */:
- return ts.tokenIsIdentifierOrKeyword(token());
- case 13 /* JsxAttributes */:
- return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
- case 14 /* JsxChildren */:
- return true;
- }
- return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
- }
- function isValidHeritageClauseObjectLiteral() {
- ts.Debug.assert(token() === 18 /* OpenBraceToken */);
- if (nextToken() === 19 /* 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 === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
- }
- return true;
- }
- function nextTokenIsIdentifier() {
- nextToken();
- return isIdentifier();
- }
- function nextTokenIsIdentifierOrKeyword() {
- nextToken();
- return ts.tokenIsIdentifierOrKeyword(token());
- }
- function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
- nextToken();
- return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
- }
- function isHeritageClauseExtendsOrImplementsKeyword() {
- if (token() === 113 /* ImplementsKeyword */ ||
- token() === 90 /* ExtendsKeyword */) {
- return lookAhead(nextTokenIsStartOfExpression);
- }
- return false;
- }
- function nextTokenIsStartOfExpression() {
- nextToken();
- return isStartOfExpression();
- }
- function nextTokenIsStartOfType() {
- nextToken();
- return isStartOfType();
- }
- // True if positioned at a list terminator
- function isListTerminator(kind) {
- if (token() === 1 /* EndOfFileToken */) {
- // Being at the end of the file ends all lists.
- return true;
- }
- switch (kind) {
- case 1 /* BlockStatements */:
- case 2 /* SwitchClauses */:
- case 4 /* TypeMembers */:
- case 5 /* ClassMembers */:
- case 6 /* EnumMembers */:
- case 12 /* ObjectLiteralMembers */:
- case 9 /* ObjectBindingElements */:
- case 23 /* ImportOrExportSpecifiers */:
- return token() === 19 /* CloseBraceToken */;
- case 3 /* SwitchClauseStatements */:
- return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
- case 7 /* HeritageClauseElement */:
- return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
- case 8 /* VariableDeclarations */:
- return isVariableDeclaratorListTerminator();
- case 19 /* TypeParameters */:
- // Tokens other than '>' are here for better error recovery
- return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
- case 11 /* ArgumentExpressions */:
- // Tokens other than ')' are here for better error recovery
- return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
- case 15 /* ArrayLiteralMembers */:
- case 21 /* TupleElementTypes */:
- case 10 /* ArrayBindingElements */:
- return token() === 23 /* CloseBracketToken */;
- case 17 /* JSDocParameters */:
- case 16 /* Parameters */:
- case 18 /* RestProperties */:
- // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
- return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
- case 20 /* TypeArguments */:
- // All other tokens should cause the type-argument to terminate except comma token
- return token() !== 27 /* CommaToken */;
- case 22 /* HeritageClauses */:
- return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
- case 13 /* JsxAttributes */:
- return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
- case 14 /* JsxChildren */:
- return token() === 29 /* 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;
- }
- // 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() === 38 /* 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 < 24 /* Count */; kind++) {
- if (parsingContext & (1 << 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, /*inErrorRecovery*/ false)) {
- var element = parseListElement(kind, parseElement);
- list.push(element);
- continue;
- }
- if (abortParsingListOrMoveToNextToken(kind)) {
- break;
- }
- }
- parsingContext = saveParsingContext;
- return createNodeArray(list, listPos);
- }
- function parseListElement(parsingContext, parseElement) {
- var node = currentNode(parsingContext);
- if (node) {
- return consumeNode(node);
- }
- return parseElement();
- }
- function currentNode(parsingContext) {
- // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
- //
- // 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 (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
- return undefined;
- }
- var node = syntaxCursor.currentNode(scanner.getStartPos());
- // Can't reuse a missing node.
- // Can't reuse a node that intersected the change range.
- // 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.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
- return undefined;
- }
- // 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 & 25358336 /* 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 isReusableParsingContext(parsingContext) {
- switch (parsingContext) {
- case 5 /* ClassMembers */:
- case 2 /* SwitchClauses */:
- case 0 /* SourceElements */:
- case 1 /* BlockStatements */:
- case 3 /* SwitchClauseStatements */:
- case 6 /* EnumMembers */:
- case 4 /* TypeMembers */:
- case 8 /* VariableDeclarations */:
- case 17 /* JSDocParameters */:
- case 16 /* Parameters */:
- return true;
- }
- return false;
- }
- function canReuseNode(node, parsingContext) {
- switch (parsingContext) {
- case 5 /* ClassMembers */:
- return isReusableClassMember(node);
- case 2 /* SwitchClauses */:
- return isReusableSwitchClause(node);
- case 0 /* SourceElements */:
- case 1 /* BlockStatements */:
- case 3 /* SwitchClauseStatements */:
- return isReusableStatement(node);
- case 6 /* EnumMembers */:
- return isReusableEnumMember(node);
- case 4 /* TypeMembers */:
- return isReusableTypeMember(node);
- case 8 /* VariableDeclarations */:
- return isReusableVariableDeclaration(node);
- case 17 /* JSDocParameters */:
- case 16 /* Parameters */:
- return isReusableParameter(node);
- // 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 ParsingContext.HeritageClauses:
- // This would probably be safe to reuse. There is no speculative parsing with
- // heritage clauses.
- // case ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.JsxAttributes:
- // case ParsingContext.JsxChildren:
- }
- return false;
- }
- function isReusableClassMember(node) {
- if (node) {
- switch (node.kind) {
- case 162 /* Constructor */:
- case 167 /* IndexSignature */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 159 /* PropertyDeclaration */:
- case 222 /* SemicolonClassElement */:
- return true;
- case 161 /* 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 === 75 /* Identifier */ &&
- methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
- return !nameIsConstructor;
- }
- }
- return false;
- }
- function isReusableSwitchClause(node) {
- if (node) {
- switch (node.kind) {
- case 277 /* CaseClause */:
- case 278 /* DefaultClause */:
- return true;
- }
- }
- return false;
- }
- function isReusableStatement(node) {
- if (node) {
- switch (node.kind) {
- case 244 /* FunctionDeclaration */:
- case 225 /* VariableStatement */:
- case 223 /* Block */:
- case 227 /* IfStatement */:
- case 226 /* ExpressionStatement */:
- case 239 /* ThrowStatement */:
- case 235 /* ReturnStatement */:
- case 237 /* SwitchStatement */:
- case 234 /* BreakStatement */:
- case 233 /* ContinueStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- case 230 /* ForStatement */:
- case 229 /* WhileStatement */:
- case 236 /* WithStatement */:
- case 224 /* EmptyStatement */:
- case 240 /* TryStatement */:
- case 238 /* LabeledStatement */:
- case 228 /* DoStatement */:
- case 241 /* DebuggerStatement */:
- case 254 /* ImportDeclaration */:
- case 253 /* ImportEqualsDeclaration */:
- case 260 /* ExportDeclaration */:
- case 259 /* ExportAssignment */:
- case 249 /* ModuleDeclaration */:
- case 245 /* ClassDeclaration */:
- case 246 /* InterfaceDeclaration */:
- case 248 /* EnumDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- return true;
- }
- }
- return false;
- }
- function isReusableEnumMember(node) {
- return node.kind === 284 /* EnumMember */;
- }
- function isReusableTypeMember(node) {
- if (node) {
- switch (node.kind) {
- case 166 /* ConstructSignature */:
- case 160 /* MethodSignature */:
- case 167 /* IndexSignature */:
- case 158 /* PropertySignature */:
- case 165 /* CallSignature */:
- return true;
- }
- }
- return false;
- }
- function isReusableVariableDeclaration(node) {
- if (node.kind !== 242 /* 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;
- }
- function getExpectedCommaDiagnostic(kind) {
- return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
- }
- function createMissingList() {
- var list = createNodeArray([], getNodePos());
- list.isMissingList = true;
- return list;
- }
- function isMissingList(arr) {
- return !!arr.isMissingList;
- }
- function parseBracketedList(kind, parseElement, open, close) {
- if (parseExpected(open)) {
- var result = parseDelimitedList(kind, parseElement);
- parseExpected(close);
- return result;
- }
- return createMissingList();
- }
- function parseEntityName(allowReservedWords, diagnosticMessage) {
- var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
- var dotPos = scanner.getStartPos();
- while (parseOptional(24 /* DotToken */)) {
- if (token() === 29 /* LessThanToken */) {
- // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
- entity.jsdocDotPos = dotPos;
- break;
- }
- dotPos = scanner.getStartPos();
- entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
- }
- return entity;
- }
- function createQualifiedName(entity, name) {
- var node = createNode(153 /* QualifiedName */, entity.pos);
- node.left = entity;
- node.right = name;
- return finishNode(node);
- }
- function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
- // 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) {
- // 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(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
- }
- }
- if (token() === 76 /* PrivateIdentifier */) {
- var node = parsePrivateIdentifier();
- return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
- }
- return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
- }
- function parseTemplateExpression(isTaggedTemplate) {
- var template = createNode(211 /* TemplateExpression */);
- template.head = parseTemplateHead(isTaggedTemplate);
- ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
- var list = [];
- var listPos = getNodePos();
- do {
- list.push(parseTemplateSpan(isTaggedTemplate));
- } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
- template.templateSpans = createNodeArray(list, listPos);
- return finishNode(template);
- }
- function parseTemplateSpan(isTaggedTemplate) {
- var span = createNode(221 /* TemplateSpan */);
- span.expression = allowInAnd(parseExpression);
- var literal;
- if (token() === 19 /* CloseBraceToken */) {
- reScanTemplateToken(isTaggedTemplate);
- literal = parseTemplateMiddleOrTemplateTail();
- }
- else {
- literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
- }
- span.literal = literal;
- return finishNode(span);
- }
- function parseLiteralNode() {
- return parseLiteralLikeNode(token());
- }
- function parseTemplateHead(isTaggedTemplate) {
- if (isTaggedTemplate) {
- reScanTemplateHeadOrNoSubstitutionTemplate();
- }
- var fragment = parseLiteralLikeNode(token());
- ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
- return fragment;
- }
- function parseTemplateMiddleOrTemplateTail() {
- var fragment = parseLiteralLikeNode(token());
- ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
- return fragment;
- }
- function parseLiteralLikeNode(kind) {
- var node = createNode(kind);
- node.text = scanner.getTokenValue();
- switch (kind) {
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 15 /* TemplateHead */:
- case 16 /* TemplateMiddle */:
- case 17 /* TemplateTail */:
- var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
- var tokenText = scanner.getTokenText();
- node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
- break;
- }
- if (scanner.hasExtendedUnicodeEscape()) {
- node.hasExtendedUnicodeEscape = true;
- }
- if (scanner.isUnterminated()) {
- node.isUnterminated = true;
- }
- // 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 */;
- }
- if (ts.isTemplateLiteralKind(node.kind)) {
- node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
- }
- nextToken();
- finishNode(node);
- return node;
- }
- // TYPES
- function parseTypeReference() {
- var node = createNode(169 /* TypeReference */);
- node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
- if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
- node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
- }
- return finishNode(node);
- }
- // If true, we should abort parsing an error function.
- function typeHasArrowFunctionBlockingParseError(node) {
- switch (node.kind) {
- case 169 /* TypeReference */:
- return ts.nodeIsMissing(node.typeName);
- case 170 /* FunctionType */:
- case 171 /* ConstructorType */: {
- var _a = node, parameters = _a.parameters, type = _a.type;
- return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
- }
- case 182 /* ParenthesizedType */:
- return typeHasArrowFunctionBlockingParseError(node.type);
- default:
- return false;
- }
- }
- function parseThisTypePredicate(lhs) {
- nextToken();
- var node = createNode(168 /* TypePredicate */, lhs.pos);
- node.parameterName = lhs;
- node.type = parseType();
- return finishNode(node);
- }
- function parseThisTypeNode() {
- var node = createNode(183 /* ThisType */);
- nextToken();
- return finishNode(node);
- }
- function parseJSDocAllType(postFixEquals) {
- var result = createNode(295 /* JSDocAllType */);
- if (postFixEquals) {
- return createPostfixType(299 /* JSDocOptionalType */, result);
- }
- else {
- nextToken();
- }
- return finishNode(result);
- }
- function parseJSDocNonNullableType() {
- var result = createNode(298 /* JSDocNonNullableType */);
- nextToken();
- result.type = parseNonArrayType();
- return finishNode(result);
- }
- function parseJSDocUnknownOrNullableType() {
- var pos = scanner.getStartPos();
- // skip the ?
- nextToken();
- // 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() === 27 /* CommaToken */ ||
- token() === 19 /* CloseBraceToken */ ||
- token() === 21 /* CloseParenToken */ ||
- token() === 31 /* GreaterThanToken */ ||
- token() === 62 /* EqualsToken */ ||
- token() === 51 /* BarToken */) {
- var result = createNode(296 /* JSDocUnknownType */, pos);
- return finishNode(result);
- }
- else {
- var result = createNode(297 /* JSDocNullableType */, pos);
- result.type = parseType();
- return finishNode(result);
- }
- }
- function parseJSDocFunctionType() {
- if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
- nextToken();
- fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
- return finishNode(result);
- }
- var node = createNode(169 /* TypeReference */);
- node.typeName = parseIdentifierName();
- return finishNode(node);
- }
- function parseJSDocParameter() {
- var parameter = createNode(156 /* Parameter */);
- if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
- parameter.name = parseIdentifierName();
- parseExpected(58 /* ColonToken */);
- }
- parameter.type = parseJSDocType();
- return finishNode(parameter);
- }
- function parseJSDocType() {
- scanner.setInJSDocType(true);
- var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
- if (moduleSpecifier) {
- var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
- terminate: while (true) {
- switch (token()) {
- case 19 /* CloseBraceToken */:
- case 1 /* EndOfFileToken */:
- case 27 /* CommaToken */:
- case 5 /* WhitespaceTrivia */:
- break terminate;
- default:
- nextTokenJSDoc();
- }
- }
- scanner.setInJSDocType(false);
- return finishNode(moduleTag);
- }
- var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
- var type = parseTypeOrTypePredicate();
- scanner.setInJSDocType(false);
- if (dotdotdot) {
- var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
- variadic.type = type;
- type = finishNode(variadic);
- }
- if (token() === 62 /* EqualsToken */) {
- return createPostfixType(299 /* JSDocOptionalType */, type);
- }
- return type;
- }
- function parseTypeQuery() {
- var node = createNode(172 /* TypeQuery */);
- parseExpected(108 /* TypeOfKeyword */);
- node.exprName = parseEntityName(/*allowReservedWords*/ true);
- return finishNode(node);
- }
- function parseTypeParameter() {
- var node = createNode(155 /* TypeParameter */);
- node.name = parseIdentifier();
- if (parseOptional(90 /* 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(62 /* EqualsToken */)) {
- node.default = parseType();
- }
- return finishNode(node);
- }
- function parseTypeParameters() {
- if (token() === 29 /* LessThanToken */) {
- return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
- }
- }
- function parseParameterType() {
- if (parseOptional(58 /* ColonToken */)) {
- return parseType();
- }
- return undefined;
- }
- function isStartOfParameter(isJSDocParameter) {
- return token() === 25 /* DotDotDotToken */ ||
- isIdentifierOrPrivateIdentifierOrPattern() ||
- ts.isModifierKind(token()) ||
- token() === 59 /* AtToken */ ||
- isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
- }
- function parseParameter() {
- var node = createNodeWithJSDoc(156 /* Parameter */);
- if (token() === 104 /* ThisKeyword */) {
- node.name = createIdentifier(/*isIdentifier*/ true);
- node.type = parseParameterType();
- return finishNode(node);
- }
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers();
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- // FormalParameter [Yield,Await]:
- // BindingElement[?Yield,?Await]
- node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
- if (ts.getFullWidth(node.name) === 0 && !node.modifiers && 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(57 /* 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 /* JSDoc */)) {
- signature.typeParameters = parseTypeParameters();
- }
- var parametersParsedSuccessfully = parseParameterList(signature, flags);
- if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
- signature.type = parseTypeOrTypePredicate();
- if (typeHasArrowFunctionBlockingParseError(signature.type))
- return false;
- }
- return parametersParsedSuccessfully;
- }
- function shouldParseReturnType(returnToken, isType) {
- if (returnToken === 38 /* EqualsGreaterThanToken */) {
- parseExpected(returnToken);
- return true;
- }
- else if (parseOptional(58 /* ColonToken */)) {
- return true;
- }
- else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
- // This is easy to get backward, especially in type contexts, so parse the type anyway
- parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
- nextToken();
- return true;
- }
- return false;
- }
- // Returns true on success.
- function parseParameterList(signature, flags) {
- // 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(20 /* OpenParenToken */)) {
- signature.parameters = createMissingList();
- return false;
- }
- var savedYieldContext = inYieldContext();
- var savedAwaitContext = inAwaitContext();
- setYieldContext(!!(flags & 1 /* Yield */));
- setAwaitContext(!!(flags & 2 /* Await */));
- signature.parameters = flags & 32 /* JSDoc */ ?
- parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
- parseDelimitedList(16 /* Parameters */, parseParameter);
- setYieldContext(savedYieldContext);
- setAwaitContext(savedAwaitContext);
- return parseExpected(21 /* CloseParenToken */);
- }
- function parseTypeMemberSemicolon() {
- // 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(27 /* CommaToken */)) {
- return;
- }
- // Didn't have a comma. We must have a (possible ASI) semicolon.
- parseSemicolon();
- }
- function parseSignatureMember(kind) {
- var node = createNodeWithJSDoc(kind);
- if (kind === 166 /* ConstructSignature */) {
- parseExpected(99 /* NewKeyword */);
- }
- fillSignature(58 /* ColonToken */, 4 /* Type */, node);
- parseTypeMemberSemicolon();
- return finishNode(node);
- }
- function isIndexSignature() {
- return token() === 22 /* 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() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
- return true;
- }
- if (ts.isModifierKind(token())) {
- nextToken();
- if (isIdentifier()) {
- return true;
- }
- }
- else if (!isIdentifier()) {
- return false;
- }
- else {
- // Skip the identifier
- nextToken();
- }
- // 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() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
- return true;
- }
- // Question mark could be an indexer with an optional property,
- // or it could be a conditional expression in a computed property.
- if (token() !== 57 /* 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() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
- }
- function parseIndexSignatureDeclaration(node) {
- node.kind = 167 /* IndexSignature */;
- node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
- node.type = parseTypeAnnotation();
- parseTypeMemberSemicolon();
- return finishNode(node);
- }
- function parsePropertyOrMethodSignature(node) {
- node.name = parsePropertyName();
- node.questionToken = parseOptionalToken(57 /* QuestionToken */);
- if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
- node.kind = 160 /* MethodSignature */;
- // Method signatures don't exist in expression contexts. So they have neither
- // [Yield] nor [Await]
- fillSignature(58 /* ColonToken */, 4 /* Type */, node);
- }
- else {
- node.kind = 158 /* PropertySignature */;
- node.type = parseTypeAnnotation();
- if (token() === 62 /* 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();
- }
- }
- parseTypeMemberSemicolon();
- return finishNode(node);
- }
- function isTypeMemberStart() {
- // Return true if we have the start of a signature member
- if (token() === 20 /* OpenParenToken */ || token() === 29 /* 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();
- }
- // Index signatures and computed property names are type members
- if (token() === 22 /* 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() === 20 /* OpenParenToken */ ||
- token() === 29 /* LessThanToken */ ||
- token() === 57 /* QuestionToken */ ||
- token() === 58 /* ColonToken */ ||
- token() === 27 /* CommaToken */ ||
- canParseSemicolon();
- }
- return false;
- }
- function parseTypeMember() {
- if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
- return parseSignatureMember(165 /* CallSignature */);
- }
- if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
- return parseSignatureMember(166 /* ConstructSignature */);
- }
- var node = createNodeWithJSDoc(0 /* Unknown */);
- node.modifiers = parseModifiers();
- if (isIndexSignature()) {
- return parseIndexSignatureDeclaration(node);
- }
- return parsePropertyOrMethodSignature(node);
- }
- function nextTokenIsOpenParenOrLessThan() {
- nextToken();
- return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
- }
- function nextTokenIsDot() {
- return nextToken() === 24 /* DotToken */;
- }
- function nextTokenIsOpenParenOrLessThanOrDot() {
- switch (nextToken()) {
- case 20 /* OpenParenToken */:
- case 29 /* LessThanToken */:
- case 24 /* DotToken */:
- return true;
- }
- return false;
- }
- function parseTypeLiteral() {
- var node = createNode(173 /* TypeLiteral */);
- node.members = parseObjectTypeMembers();
- return finishNode(node);
- }
- function parseObjectTypeMembers() {
- var members;
- if (parseExpected(18 /* OpenBraceToken */)) {
- members = parseList(4 /* TypeMembers */, parseTypeMember);
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- members = createMissingList();
- }
- return members;
- }
- function isStartOfMappedType() {
- nextToken();
- if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
- return nextToken() === 138 /* ReadonlyKeyword */;
- }
- if (token() === 138 /* ReadonlyKeyword */) {
- nextToken();
- }
- return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
- }
- function parseMappedTypeParameter() {
- var node = createNode(155 /* TypeParameter */);
- node.name = parseIdentifier();
- parseExpected(97 /* InKeyword */);
- node.constraint = parseType();
- return finishNode(node);
- }
- function parseMappedType() {
- var node = createNode(186 /* MappedType */);
- parseExpected(18 /* OpenBraceToken */);
- if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
- node.readonlyToken = parseTokenNode();
- if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
- parseExpectedToken(138 /* ReadonlyKeyword */);
- }
- }
- parseExpected(22 /* OpenBracketToken */);
- node.typeParameter = parseMappedTypeParameter();
- parseExpected(23 /* CloseBracketToken */);
- if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
- node.questionToken = parseTokenNode();
- if (node.questionToken.kind !== 57 /* QuestionToken */) {
- parseExpectedToken(57 /* QuestionToken */);
- }
- }
- node.type = parseTypeAnnotation();
- parseSemicolon();
- parseExpected(19 /* CloseBraceToken */);
- return finishNode(node);
- }
- function parseTupleElementType() {
- var pos = getNodePos();
- if (parseOptional(25 /* DotDotDotToken */)) {
- var node = createNode(177 /* RestType */, pos);
- node.type = parseType();
- return finishNode(node);
- }
- var type = parseType();
- if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
- type.kind = 176 /* OptionalType */;
- }
- return type;
- }
- function parseTupleType() {
- var node = createNode(175 /* TupleType */);
- node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
- return finishNode(node);
- }
- function parseParenthesizedType() {
- var node = createNode(182 /* ParenthesizedType */);
- parseExpected(20 /* OpenParenToken */);
- node.type = parseType();
- parseExpected(21 /* CloseParenToken */);
- return finishNode(node);
- }
- function parseFunctionOrConstructorType() {
- var pos = getNodePos();
- var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
- var node = createNodeWithJSDoc(kind, pos);
- fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
- return finishNode(node);
- }
- function parseKeywordAndNoDot() {
- var node = parseTokenNode();
- return token() === 24 /* DotToken */ ? undefined : node;
- }
- function parseLiteralTypeNode(negative) {
- var node = createNode(187 /* LiteralType */);
- var unaryMinusExpression;
- if (negative) {
- unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
- unaryMinusExpression.operator = 40 /* MinusToken */;
- nextToken();
- }
- var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
- ? parseTokenNode()
- : parseLiteralLikeNode(token());
- if (negative) {
- unaryMinusExpression.operand = expression;
- finishNode(unaryMinusExpression);
- expression = unaryMinusExpression;
- }
- node.literal = expression;
- return finishNode(node);
- }
- function isStartOfTypeOfImportType() {
- nextToken();
- return token() === 96 /* ImportKeyword */;
- }
- function parseImportType() {
- sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
- var node = createNode(188 /* ImportType */);
- if (parseOptional(108 /* TypeOfKeyword */)) {
- node.isTypeOf = true;
- }
- parseExpected(96 /* ImportKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.argument = parseType();
- parseExpected(21 /* CloseParenToken */);
- if (parseOptional(24 /* DotToken */)) {
- node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
- }
- if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
- node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
- }
- return finishNode(node);
- }
- function nextTokenIsNumericOrBigIntLiteral() {
- nextToken();
- return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
- }
- function parseNonArrayType() {
- switch (token()) {
- case 125 /* AnyKeyword */:
- case 148 /* UnknownKeyword */:
- case 143 /* StringKeyword */:
- case 140 /* NumberKeyword */:
- case 151 /* BigIntKeyword */:
- case 144 /* SymbolKeyword */:
- case 128 /* BooleanKeyword */:
- case 146 /* UndefinedKeyword */:
- case 137 /* NeverKeyword */:
- case 141 /* ObjectKeyword */:
- // If these are followed by a dot, then parse these out as a dotted type reference instead.
- return tryParse(parseKeywordAndNoDot) || parseTypeReference();
- case 41 /* AsteriskToken */:
- return parseJSDocAllType(/*postfixEquals*/ false);
- case 65 /* AsteriskEqualsToken */:
- return parseJSDocAllType(/*postfixEquals*/ true);
- case 60 /* QuestionQuestionToken */:
- // If there is '??', consider that is prefix '?' in JSDoc type.
- scanner.reScanQuestionToken();
- // falls through
- case 57 /* QuestionToken */:
- return parseJSDocUnknownOrNullableType();
- case 94 /* FunctionKeyword */:
- return parseJSDocFunctionType();
- case 53 /* ExclamationToken */:
- return parseJSDocNonNullableType();
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 10 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- return parseLiteralTypeNode();
- case 40 /* MinusToken */:
- return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
- case 110 /* VoidKeyword */:
- case 100 /* NullKeyword */:
- return parseTokenNode();
- case 104 /* ThisKeyword */: {
- var thisKeyword = parseThisTypeNode();
- if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
- return parseThisTypePredicate(thisKeyword);
- }
- else {
- return thisKeyword;
- }
- }
- case 108 /* TypeOfKeyword */:
- return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
- case 18 /* OpenBraceToken */:
- return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
- case 22 /* OpenBracketToken */:
- return parseTupleType();
- case 20 /* OpenParenToken */:
- return parseParenthesizedType();
- case 96 /* ImportKeyword */:
- return parseImportType();
- case 124 /* AssertsKeyword */:
- return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
- default:
- return parseTypeReference();
- }
- }
- function isStartOfType(inStartOfParameter) {
- switch (token()) {
- case 125 /* AnyKeyword */:
- case 148 /* UnknownKeyword */:
- case 143 /* StringKeyword */:
- case 140 /* NumberKeyword */:
- case 151 /* BigIntKeyword */:
- case 128 /* BooleanKeyword */:
- case 138 /* ReadonlyKeyword */:
- case 144 /* SymbolKeyword */:
- case 147 /* UniqueKeyword */:
- case 110 /* VoidKeyword */:
- case 146 /* UndefinedKeyword */:
- case 100 /* NullKeyword */:
- case 104 /* ThisKeyword */:
- case 108 /* TypeOfKeyword */:
- case 137 /* NeverKeyword */:
- case 18 /* OpenBraceToken */:
- case 22 /* OpenBracketToken */:
- case 29 /* LessThanToken */:
- case 51 /* BarToken */:
- case 50 /* AmpersandToken */:
- case 99 /* NewKeyword */:
- case 10 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- case 141 /* ObjectKeyword */:
- case 41 /* AsteriskToken */:
- case 57 /* QuestionToken */:
- case 53 /* ExclamationToken */:
- case 25 /* DotDotDotToken */:
- case 132 /* InferKeyword */:
- case 96 /* ImportKeyword */:
- case 124 /* AssertsKeyword */:
- return true;
- case 94 /* FunctionKeyword */:
- return !inStartOfParameter;
- case 40 /* MinusToken */:
- return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
- case 20 /* 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();
- }
- }
- function isStartOfParenthesizedOrFunctionType() {
- nextToken();
- return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
- }
- function parsePostfixTypeOrHigher() {
- var type = parseNonArrayType();
- while (!scanner.hasPrecedingLineBreak()) {
- switch (token()) {
- case 53 /* ExclamationToken */:
- type = createPostfixType(298 /* JSDocNonNullableType */, type);
- break;
- case 57 /* QuestionToken */:
- // If not in JSDoc and next token is start of a type we have a conditional type
- if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
- return type;
- }
- type = createPostfixType(297 /* JSDocNullableType */, type);
- break;
- case 22 /* OpenBracketToken */:
- parseExpected(22 /* OpenBracketToken */);
- if (isStartOfType()) {
- var node = createNode(185 /* IndexedAccessType */, type.pos);
- node.objectType = type;
- node.indexType = parseType();
- parseExpected(23 /* CloseBracketToken */);
- type = finishNode(node);
- }
- else {
- var node = createNode(174 /* ArrayType */, type.pos);
- node.elementType = type;
- parseExpected(23 /* CloseBracketToken */);
- type = finishNode(node);
- }
- break;
- default:
- return type;
- }
- }
- return type;
- }
- function createPostfixType(kind, type) {
- nextToken();
- var postfix = createNode(kind, type.pos);
- postfix.type = type;
- return finishNode(postfix);
- }
- function parseTypeOperator(operator) {
- var node = createNode(184 /* TypeOperator */);
- parseExpected(operator);
- node.operator = operator;
- node.type = parseTypeOperatorOrHigher();
- return finishNode(node);
- }
- function parseInferType() {
- var node = createNode(181 /* InferType */);
- parseExpected(132 /* InferKeyword */);
- var typeParameter = createNode(155 /* TypeParameter */);
- typeParameter.name = parseIdentifier();
- node.typeParameter = finishNode(typeParameter);
- return finishNode(node);
- }
- function parseTypeOperatorOrHigher() {
- var operator = token();
- switch (operator) {
- case 134 /* KeyOfKeyword */:
- case 147 /* UniqueKeyword */:
- case 138 /* ReadonlyKeyword */:
- return parseTypeOperator(operator);
- case 132 /* InferKeyword */:
- return parseInferType();
- }
- return parsePostfixTypeOrHigher();
- }
- function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
- var start = scanner.getStartPos();
- var hasLeadingOperator = parseOptional(operator);
- var type = parseConstituentType();
- if (token() === operator || hasLeadingOperator) {
- var types = [type];
- while (parseOptional(operator)) {
- types.push(parseConstituentType());
- }
- var node = createNode(kind, start);
- node.types = createNodeArray(types, start);
- type = finishNode(node);
- }
- return type;
- }
- function parseIntersectionTypeOrHigher() {
- return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
- }
- function parseUnionTypeOrHigher() {
- return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
- }
- function isStartOfFunctionType() {
- if (token() === 29 /* LessThanToken */) {
- return true;
- }
- return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
- }
- function skipParameterStart() {
- if (ts.isModifierKind(token())) {
- // Skip modifiers
- parseModifiers();
- }
- if (isIdentifier() || token() === 104 /* ThisKeyword */) {
- nextToken();
- return true;
- }
- if (token() === 22 /* OpenBracketToken */ || token() === 18 /* 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;
- }
- return false;
- }
- function isUnambiguouslyStartOfFunctionType() {
- nextToken();
- if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
- // ( )
- // ( ...
- return true;
- }
- if (skipParameterStart()) {
- // 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() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
- token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
- // ( xxx :
- // ( xxx ,
- // ( xxx ?
- // ( xxx =
- return true;
- }
- if (token() === 21 /* CloseParenToken */) {
- nextToken();
- if (token() === 38 /* EqualsGreaterThanToken */) {
- // ( xxx ) =>
- return true;
- }
- }
- }
- return false;
- }
- function parseTypeOrTypePredicate() {
- var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
- var type = parseType();
- if (typePredicateVariable) {
- var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
- node.assertsModifier = undefined;
- node.parameterName = typePredicateVariable;
- node.type = type;
- return finishNode(node);
- }
- else {
- return type;
- }
- }
- function parseTypePredicatePrefix() {
- var id = parseIdentifier();
- if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
- nextToken();
- return id;
- }
- }
- function parseAssertsTypePredicate() {
- var node = createNode(168 /* TypePredicate */);
- node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
- node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
- node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
- return finishNode(node);
- }
- function parseType() {
- // 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(40960 /* TypeExcludesFlags */, parseTypeWorker);
- }
- function parseTypeWorker(noConditionalTypes) {
- if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
- return parseFunctionOrConstructorType();
- }
- var type = parseUnionTypeOrHigher();
- if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
- var node = createNode(180 /* ConditionalType */, type.pos);
- node.checkType = type;
- // The type following 'extends' is not permitted to be another conditional type
- node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
- parseExpected(57 /* QuestionToken */);
- node.trueType = parseTypeWorker();
- parseExpected(58 /* ColonToken */);
- node.falseType = parseTypeWorker();
- return finishNode(node);
- }
- return type;
- }
- function parseTypeAnnotation() {
- return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
- }
- // EXPRESSIONS
- function isStartOfLeftHandSideExpression() {
- switch (token()) {
- case 104 /* ThisKeyword */:
- case 102 /* SuperKeyword */:
- case 100 /* NullKeyword */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 15 /* TemplateHead */:
- case 20 /* OpenParenToken */:
- case 22 /* OpenBracketToken */:
- case 18 /* OpenBraceToken */:
- case 94 /* FunctionKeyword */:
- case 80 /* ClassKeyword */:
- case 99 /* NewKeyword */:
- case 43 /* SlashToken */:
- case 67 /* SlashEqualsToken */:
- case 75 /* Identifier */:
- return true;
- case 96 /* ImportKeyword */:
- return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
- default:
- return isIdentifier();
- }
- }
- function isStartOfExpression() {
- if (isStartOfLeftHandSideExpression()) {
- return true;
- }
- switch (token()) {
- case 39 /* PlusToken */:
- case 40 /* MinusToken */:
- case 54 /* TildeToken */:
- case 53 /* ExclamationToken */:
- case 85 /* DeleteKeyword */:
- case 108 /* TypeOfKeyword */:
- case 110 /* VoidKeyword */:
- case 45 /* PlusPlusToken */:
- case 46 /* MinusMinusToken */:
- case 29 /* LessThanToken */:
- case 127 /* AwaitKeyword */:
- case 121 /* YieldKeyword */:
- case 76 /* PrivateIdentifier */:
- // 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;
- }
- return isIdentifier();
- }
- }
- function isStartOfExpressionStatement() {
- // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
- return token() !== 18 /* OpenBraceToken */ &&
- token() !== 94 /* FunctionKeyword */ &&
- token() !== 80 /* ClassKeyword */ &&
- token() !== 59 /* 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(/*val*/ false);
- }
- var expr = parseAssignmentExpressionOrHigher();
- var operatorToken;
- while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
- expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
- }
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ true);
- }
- return expr;
- }
- function parseInitializer() {
- return parseOptional(62 /* 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;
- }
- // 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 === 75 /* Identifier */ && token() === 38 /* 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() === 121 /* 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;
- }
- function nextTokenIsIdentifierOnSameLine() {
- nextToken();
- return !scanner.hasPrecedingLineBreak() && isIdentifier();
- }
- function parseYieldExpression() {
- var node = createNode(212 /* 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() === 41 /* AsteriskToken */ || isStartOfExpression())) {
- node.asteriskToken = parseOptionalToken(41 /* 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() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
- var node;
- if (asyncModifier) {
- node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
- node.modifiers = asyncModifier;
- }
- else {
- node = createNode(202 /* ArrowFunction */, identifier.pos);
- }
- var parameter = createNode(156 /* Parameter */, identifier.pos);
- parameter.name = identifier;
- finishNode(parameter);
- node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
- node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
- node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
- return addJSDocComment(finishNode(node));
- }
- function tryParseParenthesizedArrowFunctionExpression() {
- var triState = isParenthesizedArrowFunctionExpression();
- if (triState === 0 /* False */) {
- // It's definitely not a parenthesized arrow function expression.
- return undefined;
- }
- // 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 = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
- // 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(38 /* EqualsGreaterThanToken */);
- arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* 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() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
- return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
- }
- if (token() === 38 /* 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 */;
- }
- // Definitely not a parenthesized arrow function.
- return 0 /* False */;
- }
- function isParenthesizedArrowFunctionExpressionWorker() {
- if (token() === 126 /* AsyncKeyword */) {
- nextToken();
- if (scanner.hasPrecedingLineBreak()) {
- return 0 /* False */;
- }
- if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
- return 0 /* False */;
- }
- }
- var first = token();
- var second = nextToken();
- if (first === 20 /* OpenParenToken */) {
- if (second === 21 /* 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 38 /* EqualsGreaterThanToken */:
- case 58 /* ColonToken */:
- case 18 /* OpenBraceToken */:
- return 1 /* True */;
- default:
- return 0 /* False */;
- }
- }
- // If encounter "([" or "({", this could be the start of a binding pattern.
- // Examples:
- // ([ x ]) => { }
- // ({ x }) => { }
- // ([ x ])
- // ({ x })
- if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
- return 2 /* Unknown */;
- }
- // Simple case: "(..."
- // This is an arrow function with a rest parameter.
- if (second === 25 /* DotDotDotToken */) {
- return 1 /* True */;
- }
- // 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 !== 126 /* 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. "this" is not
- // valid, but we want to parse it and then give a semantic error.
- if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
- return 0 /* False */;
- }
- switch (nextToken()) {
- case 58 /* ColonToken */:
- // If we have something like "(a:", then we must have a
- // type-annotated parameter in an arrow function expression.
- return 1 /* True */;
- case 57 /* QuestionToken */:
- nextToken();
- // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
- if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
- return 1 /* True */;
- }
- // Otherwise it is definitely not a lambda.
- return 0 /* False */;
- case 27 /* CommaToken */:
- case 62 /* EqualsToken */:
- case 21 /* CloseParenToken */:
- // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
- return 2 /* Unknown */;
- }
- // It is definitely not an arrow function
- return 0 /* False */;
- }
- else {
- ts.Debug.assert(first === 29 /* LessThanToken */);
- // If we have "<" not followed by an identifier,
- // then this definitely is not an arrow function.
- if (!isIdentifier()) {
- return 0 /* False */;
- }
- // JSX overrides
- if (sourceFile.languageVariant === 1 /* JSX */) {
- var isArrowFunctionInJsx = lookAhead(function () {
- var third = nextToken();
- if (third === 90 /* ExtendsKeyword */) {
- var fourth = nextToken();
- switch (fourth) {
- case 62 /* EqualsToken */:
- case 31 /* GreaterThanToken */:
- return false;
- default:
- return true;
- }
- }
- else if (third === 27 /* CommaToken */) {
- return true;
- }
- return false;
- });
- if (isArrowFunctionInJsx) {
- return 1 /* True */;
- }
- return 0 /* False */;
- }
- // This *could* be a parenthesized arrow function.
- return 2 /* Unknown */;
- }
- }
- function parsePossibleParenthesizedArrowFunctionExpressionHead() {
- var tokenPos = scanner.getTokenPos();
- if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
- return undefined;
- }
- var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
- if (!result) {
- (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
- }
- return result;
- }
- function tryParseAsyncSimpleArrowFunctionExpression() {
- // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
- if (token() === 126 /* AsyncKeyword */) {
- if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
- var asyncModifier = parseModifiersForArrowFunction();
- var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
- return parseSimpleArrowFunctionExpression(expr, asyncModifier);
- }
- }
- return undefined;
- }
- function isUnParenthesizedAsyncArrowFunctionWorker() {
- // AsyncArrowFunctionExpression:
- // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
- // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
- if (token() === 126 /* AsyncKeyword */) {
- nextToken();
- // 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() === 38 /* EqualsGreaterThanToken */) {
- return 0 /* False */;
- }
- // Check for un-parenthesized AsyncArrowFunction
- var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
- if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
- return 1 /* True */;
- }
- }
- return 0 /* False */;
- }
- function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
- var node = createNodeWithJSDoc(202 /* ArrowFunction */);
- node.modifiers = parseModifiersForArrowFunction();
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 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(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
- return undefined;
- }
- // 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.
- // - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
- //
- // So we need just a bit of lookahead to ensure that it can only be a signature.
- var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
- if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
- // Returning undefined here will cause our caller to rewind to where we started from.
- return undefined;
- }
- return node;
- }
- function parseArrowFunctionExpressionBody(isAsync) {
- if (token() === 18 /* OpenBraceToken */) {
- return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
- }
- if (token() !== 26 /* SemicolonToken */ &&
- token() !== 94 /* FunctionKeyword */ &&
- token() !== 80 /* ClassKeyword */ &&
- isStartOfStatement() &&
- !isStartOfExpressionStatement()) {
- // 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) {
- // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
- var questionToken = parseOptionalToken(57 /* QuestionToken */);
- if (!questionToken) {
- return leftOperand;
- }
- // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
- // we do not that for the 'whenFalse' part.
- var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
- node.condition = leftOperand;
- node.questionToken = questionToken;
- node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
- node.colonToken = parseExpectedToken(58 /* ColonToken */);
- node.whenFalse = ts.nodeIsPresent(node.colonToken)
- ? parseAssignmentExpressionOrHigher()
- : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
- return finishNode(node);
- }
- function parseBinaryExpressionOrHigher(precedence) {
- var leftOperand = parseUnaryExpressionOrHigher();
- return parseBinaryExpressionRest(precedence, leftOperand);
- }
- function isInOrOfKeyword(t) {
- return t === 97 /* InKeyword */ || t === 152 /* 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());
- // 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() === 42 /* AsteriskAsteriskToken */ ?
- newPrecedence >= precedence :
- newPrecedence > precedence;
- if (!consumeCurrentOperator) {
- break;
- }
- if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
- break;
- }
- if (token() === 123 /* 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;
- }
- else {
- nextToken();
- leftOperand = makeAsExpression(leftOperand, parseType());
- }
- }
- else {
- leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
- }
- }
- return leftOperand;
- }
- function isBinaryOperator() {
- if (inDisallowInContext() && token() === 97 /* InKeyword */) {
- return false;
- }
- return ts.getBinaryOperatorPrecedence(token()) > 0;
- }
- function makeBinaryExpression(left, operatorToken, right) {
- var node = createNode(209 /* BinaryExpression */, left.pos);
- node.left = left;
- node.operatorToken = operatorToken;
- node.right = right;
- return finishNode(node);
- }
- function makeAsExpression(left, right) {
- var node = createNode(217 /* AsExpression */, left.pos);
- node.expression = left;
- node.type = right;
- return finishNode(node);
- }
- function parsePrefixUnaryExpression() {
- var node = createNode(207 /* PrefixUnaryExpression */);
- node.operator = token();
- nextToken();
- node.operand = parseSimpleUnaryExpression();
- return finishNode(node);
- }
- function parseDeleteExpression() {
- var node = createNode(203 /* DeleteExpression */);
- nextToken();
- node.expression = parseSimpleUnaryExpression();
- return finishNode(node);
- }
- function parseTypeOfExpression() {
- var node = createNode(204 /* TypeOfExpression */);
- nextToken();
- node.expression = parseSimpleUnaryExpression();
- return finishNode(node);
- }
- function parseVoidExpression() {
- var node = createNode(205 /* VoidExpression */);
- nextToken();
- node.expression = parseSimpleUnaryExpression();
- return finishNode(node);
- }
- function isAwaitExpression() {
- if (token() === 127 /* AwaitKeyword */) {
- if (inAwaitContext()) {
- return true;
- }
- // here we are using similar heuristics as 'isYieldExpression'
- return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
- }
- return false;
- }
- function parseAwaitExpression() {
- var node = createNode(206 /* 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() === 42 /* AsteriskAsteriskToken */ ?
- parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
- updateExpression;
+ var activeSession;
+ var profilePath = "./profile.cpuprofile";
+ var hitSystemWatcherLimit = false;
+ var Buffer = require("buffer").Buffer;
+ var nodeVersion = getNodeMajorVersion();
+ var isNode4OrLater = nodeVersion >= 4;
+ var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
+ var platform = _os.platform();
+ var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
+ var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync;
+ var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
+ var getCurrentDirectory = ts.memoize(function () { return process.cwd(); });
+ var _c = createSystemWatchFunctions({
+ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
+ getModifiedTime: getModifiedTime,
+ setTimeout: setTimeout,
+ clearTimeout: clearTimeout,
+ fsWatch: fsWatch,
+ useCaseSensitiveFileNames: useCaseSensitiveFileNames,
+ getCurrentDirectory: getCurrentDirectory,
+ fileExists: fileExists,
+ // 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)
+ fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
+ directoryExists: directoryExists,
+ getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
+ realpath: realpath,
+ tscWatchFile: process.env.TSC_WATCHFILE,
+ useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
+ tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
+ defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); },
+ }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory;
+ var nodeSystem = {
+ args: process.argv.slice(2),
+ newLine: _os.EOL,
+ useCaseSensitiveFileNames: useCaseSensitiveFileNames,
+ write: function (s) {
+ process.stdout.write(s);
+ },
+ getWidthOfTerminal: function () {
+ return process.stdout.columns;
+ },
+ writeOutputIsTTY: function () {
+ return process.stdout.isTTY;
+ },
+ readFile: readFile,
+ writeFile: writeFile,
+ watchFile: watchFile,
+ watchDirectory: watchDirectory,
+ resolvePath: function (path) { return _path.resolve(path); },
+ fileExists: fileExists,
+ directoryExists: directoryExists,
+ createDirectory: function (directoryName) {
+ if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
+ _fs.mkdirSync(directoryName);
+ }
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
+ },
+ getExecutingFilePath: function () {
+ return __filename;
+ },
+ getCurrentDirectory: getCurrentDirectory,
+ getDirectories: getDirectories,
+ getEnvironmentVariable: function (name) {
+ return process.env[name] || "";
+ },
+ readDirectory: readDirectory,
+ getModifiedTime: getModifiedTime,
+ setModifiedTime: setModifiedTime,
+ deleteFile: deleteFile,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
+ createSHA256Hash: _crypto ? createSHA256Hash : undefined,
+ getMemoryUsage: function () {
+ if (global.gc) {
+ global.gc();
+ }
+ return process.memoryUsage().heapUsed;
+ },
+ getFileSize: function (path) {
+ try {
+ var stat = statSync(path);
+ if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
+ return stat.size;
+ }
+ }
+ catch ( /*ignore*/_a) { /*ignore*/ }
+ return 0;
+ },
+ exit: function (exitCode) {
+ disableCPUProfiler(function () { return process.exit(exitCode); });
+ },
+ enableCPUProfiler: enableCPUProfiler,
+ disableCPUProfiler: disableCPUProfiler,
+ cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); },
+ realpath: realpath,
+ debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
+ tryEnableSourceMapsForHost: function () {
+ try {
+ require("source-map-support").install();
+ }
+ catch (_a) {
+ // Could not enable source maps.
+ }
+ },
+ setTimeout: setTimeout,
+ clearTimeout: clearTimeout,
+ clearScreen: function () {
+ process.stdout.write("\x1Bc");
+ },
+ setBlocking: function () {
+ if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
+ process.stdout._handle.setBlocking(true);
+ }
+ },
+ bufferFrom: bufferFrom,
+ base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
+ base64encode: function (input) { return bufferFrom(input).toString("base64"); },
+ require: function (baseDir, moduleName) {
+ try {
+ var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
+ return { module: require(modulePath), modulePath: modulePath, error: undefined };
+ }
+ catch (error) {
+ return { module: undefined, modulePath: undefined, error: error };
+ }
+ }
+ };
+ return nodeSystem;
+ /**
+ * `throwIfNoEntry` was added so recently that it's not in the node types.
+ * This helper encapsulates the mitigating usage of `any`.
+ * See https://github.com/nodejs/node/pull/33716
+ */
+ function statSync(path) {
+ // throwIfNoEntry will be ignored by older versions of node
+ return _fs.statSync(path, { throwIfNoEntry: false });
}
/**
- * 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]
+ * Uses the builtin inspector APIs to capture a CPU profile
+ * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
*/
- var unaryOperator = token();
- var simpleUnaryExpression = parseSimpleUnaryExpression();
- if (token() === 42 /* AsteriskAsteriskToken */) {
- var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
- var end = simpleUnaryExpression.end;
- if (simpleUnaryExpression.kind === 199 /* 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 {
- parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator));
- }
- }
- 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 39 /* PlusToken */:
- case 40 /* MinusToken */:
- case 54 /* TildeToken */:
- case 53 /* ExclamationToken */:
- return parsePrefixUnaryExpression();
- case 85 /* DeleteKeyword */:
- return parseDeleteExpression();
- case 108 /* TypeOfKeyword */:
- return parseTypeOfExpression();
- case 110 /* VoidKeyword */:
- return parseVoidExpression();
- case 29 /* LessThanToken */:
- // This is modified UnaryExpression grammar in TypeScript
- // UnaryExpression (modified):
- // < type > UnaryExpression
- return parseTypeAssertion();
- case 127 /* 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 39 /* PlusToken */:
- case 40 /* MinusToken */:
- case 54 /* TildeToken */:
- case 53 /* ExclamationToken */:
- case 85 /* DeleteKeyword */:
- case 108 /* TypeOfKeyword */:
- case 110 /* VoidKeyword */:
- case 127 /* AwaitKeyword */:
+ function enableCPUProfiler(path, cb) {
+ if (activeSession) {
+ cb();
return false;
- case 29 /* 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() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
- var node = createNode(207 /* PrefixUnaryExpression */);
- node.operator = token();
- nextToken();
- node.operand = parseLeftHandSideExpressionOrHigher();
- return finishNode(node);
- }
- else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
- // JSXElement is part of primaryExpression
- return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
- }
- var expression = parseLeftHandSideExpressionOrHigher();
- ts.Debug.assert(ts.isLeftHandSideExpression(expression));
- if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
- var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
- node.operand = expression;
- node.operator = token();
- nextToken();
- return finishNode(node);
- }
- 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() === 96 /* ImportKeyword */) {
- if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
- // 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 |= 1048576 /* PossiblyContainsDynamicImport */;
- expression = parseTokenNode();
- }
- else if (lookAhead(nextTokenIsDot)) {
- // This is an 'import.*' metaproperty (i.e. 'import.meta')
- var fullStart = scanner.getStartPos();
- nextToken(); // advance past the 'import'
- nextToken(); // advance past the dot
- var node = createNode(219 /* MetaProperty */, fullStart);
- node.keywordToken = 96 /* ImportKeyword */;
- node.name = parseIdentifierName();
- expression = finishNode(node);
- sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
- }
- else {
- expression = parseMemberExpressionOrHigher();
- }
- }
- else {
- expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
- }
- // Now, we *may* be complete. However, we might have consumed the start of a
- // CallExpression or OptionalExpression. 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, /*allowOptionalChain*/ true);
- }
- function parseSuperExpression() {
- var expression = parseTokenNode();
- if (token() === 29 /* LessThanToken */) {
- var startPos = getNodePos();
- var typeArguments = tryParse(parseTypeArgumentsInExpression);
- if (typeArguments !== undefined) {
- parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
- }
- }
- if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
- return expression;
- }
- // 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(194 /* PropertyAccessExpression */, expression.pos);
- node.expression = expression;
- parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
- // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
- node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
- return finishNode(node);
- }
- function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
- var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
- var result;
- if (opening.kind === 268 /* JsxOpeningElement */) {
- var node = createNode(266 /* JsxElement */, opening.pos);
- node.openingElement = opening;
- node.children = parseJsxChildren(node.openingElement);
- node.closingElement = parseJsxClosingElement(inExpressionContext);
- if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
- parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
- }
- result = finishNode(node);
- }
- else if (opening.kind === 271 /* JsxOpeningFragment */) {
- var node = createNode(270 /* JsxFragment */, opening.pos);
- node.openingFragment = opening;
- node.children = parseJsxChildren(node.openingFragment);
- node.closingFragment = parseJsxClosingFragment(inExpressionContext);
- result = finishNode(node);
- }
- else {
- ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
- // Nothing else to do for self-closing elements
- result = opening;
- }
- // 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() === 29 /* LessThanToken */) {
- var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
- if (invalidElement) {
- parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
- var badNode = createNode(209 /* BinaryExpression */, result.pos);
- badNode.end = invalidElement.end;
- badNode.left = result;
- badNode.right = invalidElement;
- badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
- badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
- return badNode;
- }
- }
- return result;
- }
- function parseJsxText() {
- var node = createNode(11 /* JsxText */);
- node.text = scanner.getTokenValue();
- node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
- currentToken = scanner.scanJsxToken();
- return finishNode(node);
- }
- function parseJsxChild(openingTag, token) {
- switch (token) {
- 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);
- }
- else {
- // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
- // or to cover only 'Foo' in < Foo >
- var tag = openingTag.tagName;
- var start = ts.skipTrivia(sourceText, tag.pos);
- parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
- }
- return undefined;
- case 30 /* LessThanSlashToken */:
- case 7 /* ConflictMarkerTrivia */:
- return undefined;
- case 11 /* JsxText */:
- case 12 /* JsxTextAllWhiteSpaces */:
- return parseJsxText();
- case 18 /* OpenBraceToken */:
- return parseJsxExpression(/*inExpressionContext*/ false);
- case 29 /* LessThanToken */:
- return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
- default:
- return ts.Debug.assertNever(token);
- }
- }
- function parseJsxChildren(openingTag) {
- var list = [];
- var listPos = getNodePos();
- var saveParsingContext = parsingContext;
- parsingContext |= 1 << 14 /* JsxChildren */;
- while (true) {
- var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
- if (!child)
- break;
- list.push(child);
- }
- parsingContext = saveParsingContext;
- return createNodeArray(list, listPos);
- }
- function parseJsxAttributes() {
- var jsxAttributes = createNode(274 /* JsxAttributes */);
- jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
- return finishNode(jsxAttributes);
- }
- function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
- var fullStart = scanner.getStartPos();
- parseExpected(29 /* LessThanToken */);
- if (token() === 31 /* GreaterThanToken */) {
- // See below for explanation of scanJsxText
- var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
- scanJsxText();
- return finishNode(node_1);
- }
- var tagName = parseJsxElementName();
- var typeArguments = tryParseTypeArguments();
- var attributes = parseJsxAttributes();
- var node;
- if (token() === 31 /* 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(268 /* JsxOpeningElement */, fullStart);
- scanJsxText();
- }
- else {
- parseExpected(43 /* SlashToken */);
- if (inExpressionContext) {
- parseExpected(31 /* GreaterThanToken */);
- }
- else {
- parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
- scanJsxText();
- }
- node = createNode(267 /* JsxSelfClosingElement */, fullStart);
- }
- node.tagName = tagName;
- node.typeArguments = typeArguments;
- node.attributes = attributes;
- return finishNode(node);
- }
- function parseJsxElementName() {
- scanJsxIdentifier();
- // 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() === 104 /* ThisKeyword */ ?
- parseTokenNode() : parseIdentifierName();
- while (parseOptional(24 /* DotToken */)) {
- var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
- propertyAccess.expression = expression;
- propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
- expression = finishNode(propertyAccess);
- }
- return expression;
- }
- function parseJsxExpression(inExpressionContext) {
- var node = createNode(276 /* JsxExpression */);
- if (!parseExpected(18 /* OpenBraceToken */)) {
- return undefined;
- }
- if (token() !== 19 /* CloseBraceToken */) {
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- // Only an AssignmentExpression is valid here per the JSX spec,
- // but we can unambiguously parse a comma sequence and provide
- // a better error message in grammar checking.
- node.expression = parseExpression();
- }
- if (inExpressionContext) {
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
- scanJsxText();
- }
- }
- return finishNode(node);
- }
- function parseJsxAttribute() {
- if (token() === 18 /* OpenBraceToken */) {
- return parseJsxSpreadAttribute();
- }
- scanJsxIdentifier();
- var node = createNode(273 /* JsxAttribute */);
- node.name = parseIdentifierName();
- if (token() === 62 /* EqualsToken */) {
- switch (scanJsxAttributeValue()) {
- case 10 /* StringLiteral */:
- node.initializer = parseLiteralNode();
- break;
- default:
- node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
- break;
}
- }
- return finishNode(node);
- }
- function parseJsxSpreadAttribute() {
- var node = createNode(275 /* JsxSpreadAttribute */);
- parseExpected(18 /* OpenBraceToken */);
- parseExpected(25 /* DotDotDotToken */);
- node.expression = parseExpression();
- parseExpected(19 /* CloseBraceToken */);
- return finishNode(node);
- }
- function parseJsxClosingElement(inExpressionContext) {
- var node = createNode(269 /* JsxClosingElement */);
- parseExpected(30 /* LessThanSlashToken */);
- node.tagName = parseJsxElementName();
- if (inExpressionContext) {
- parseExpected(31 /* GreaterThanToken */);
- }
- else {
- parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
- scanJsxText();
- }
- return finishNode(node);
- }
- function parseJsxClosingFragment(inExpressionContext) {
- var node = createNode(272 /* JsxClosingFragment */);
- parseExpected(30 /* LessThanSlashToken */);
- if (ts.tokenIsIdentifierOrKeyword(token())) {
- parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
- }
- if (inExpressionContext) {
- parseExpected(31 /* GreaterThanToken */);
- }
- else {
- parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
- scanJsxText();
- }
- return finishNode(node);
- }
- function parseTypeAssertion() {
- var node = createNode(199 /* TypeAssertionExpression */);
- parseExpected(29 /* LessThanToken */);
- node.type = parseType();
- parseExpected(31 /* GreaterThanToken */);
- node.expression = parseSimpleUnaryExpression();
- return finishNode(node);
- }
- function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
- nextToken();
- return ts.tokenIsIdentifierOrKeyword(token())
- || token() === 22 /* OpenBracketToken */
- || isTemplateStartOfTaggedTemplate();
- }
- function isStartOfOptionalPropertyOrElementAccessChain() {
- return token() === 28 /* QuestionDotToken */
- && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
- }
- function tryReparseOptionalChain(node) {
- if (node.flags & 32 /* OptionalChain */) {
+ var inspector = require("inspector");
+ if (!inspector || !inspector.Session) {
+ cb();
+ return false;
+ }
+ var session = new inspector.Session();
+ session.connect();
+ session.post("Profiler.enable", function () {
+ session.post("Profiler.start", function () {
+ activeSession = session;
+ profilePath = path;
+ cb();
+ });
+ });
return true;
}
- // check for an optional chain in a non-null expression
- if (ts.isNonNullExpression(node)) {
- var expr = node.expression;
- while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
- expr = expr.expression;
- }
- if (expr.flags & 32 /* OptionalChain */) {
- // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
- while (ts.isNonNullExpression(node)) {
- node.flags |= 32 /* OptionalChain */;
- node = node.expression;
+ /**
+ * Strips non-TS paths from the profile, so users with private projects shouldn't
+ * need to worry about leaking paths by submitting a cpu profile to us
+ */
+ function cleanupPaths(profile) {
+ var externalFileCounter = 0;
+ var remappedPaths = new ts.Map();
+ var normalizedDir = ts.normalizeSlashes(__dirname);
+ // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
+ var fileUrlRoot = "file://".concat(ts.getRootLength(normalizedDir) === 1 ? "" : "/").concat(normalizedDir);
+ for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
+ var node = _a[_i];
+ if (node.callFrame.url) {
+ var url = ts.normalizeSlashes(node.callFrame.url);
+ if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
+ node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
+ }
+ else if (!nativePattern.test(url)) {
+ node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external".concat(externalFileCounter, ".js"))).get(url);
+ externalFileCounter++;
+ }
}
- return true;
}
+ return profile;
}
- return false;
- }
- function parsePropertyAccessExpressionRest(expression, questionDotToken) {
- var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
- propertyAccess.expression = expression;
- propertyAccess.questionDotToken = questionDotToken;
- propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- propertyAccess.flags |= 32 /* OptionalChain */;
- if (ts.isPrivateIdentifier(propertyAccess.name)) {
- parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
+ function disableCPUProfiler(cb) {
+ if (activeSession && activeSession !== "stopping") {
+ var s_1 = activeSession;
+ activeSession.post("Profiler.stop", function (err, _a) {
+ var _b;
+ var profile = _a.profile;
+ if (!err) {
+ try {
+ if ((_b = statSync(profilePath)) === null || _b === void 0 ? void 0 : _b.isDirectory()) {
+ profilePath = _path.join(profilePath, "".concat((new Date()).toISOString().replace(/:/g, "-"), "+P").concat(process.pid, ".cpuprofile"));
+ }
+ }
+ catch (_c) {
+ // do nothing and ignore fallible fs operation
+ }
+ try {
+ _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
+ }
+ catch (_d) {
+ // do nothing and ignore fallible fs operation
+ }
+ _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
+ }
+ activeSession = undefined;
+ s_1.disconnect();
+ cb();
+ });
+ activeSession = "stopping";
+ return true;
+ }
+ else {
+ cb();
+ return false;
}
}
- return finishNode(propertyAccess);
- }
- function parseElementAccessExpressionRest(expression, questionDotToken) {
- var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
- indexedAccess.expression = expression;
- indexedAccess.questionDotToken = questionDotToken;
- if (token() === 23 /* CloseBracketToken */) {
- indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
+ function bufferFrom(input, encoding) {
+ // See https://github.com/Microsoft/TypeScript/issues/25652
+ return Buffer.from && Buffer.from !== Int8Array.from
+ ? Buffer.from(input, encoding)
+ : new Buffer(input, encoding);
}
- else {
- var argument = allowInAnd(parseExpression);
- if (ts.isStringOrNumericLiteralLike(argument)) {
- argument.text = internIdentifier(argument.text);
+ function isFileSystemCaseSensitive() {
+ // win32\win64 are case insensitive platforms
+ if (platform === "win32" || platform === "win64") {
+ return false;
}
- indexedAccess.argumentExpression = argument;
+ // If this file exists under a different case, we must be case-insensitve.
+ return !fileExists(swapCase(__filename));
}
- parseExpected(23 /* CloseBracketToken */);
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- indexedAccess.flags |= 32 /* OptionalChain */;
+ /** Convert all lowercase chars to uppercase, and vice-versa */
+ function swapCase(s) {
+ return s.replace(/\w/g, function (ch) {
+ var up = ch.toUpperCase();
+ return ch === up ? ch.toLowerCase() : up;
+ });
}
- return finishNode(indexedAccess);
- }
- function parseMemberExpressionRest(expression, allowOptionalChain) {
- while (true) {
- var questionDotToken = void 0;
- var isPropertyAccess = false;
- if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
- questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
- isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
- }
- else {
- isPropertyAccess = parseOptional(24 /* DotToken */);
- }
- if (isPropertyAccess) {
- expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
- continue;
- }
- if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
- nextToken();
- var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
- nonNullExpression.expression = expression;
- expression = finishNode(nonNullExpression);
- continue;
+ function fsWatchFileWorker(fileName, callback, pollingInterval) {
+ _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
+ var eventKind;
+ return {
+ 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;
+ }
+ 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);
}
- // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
- if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
- expression = parseElementAccessExpressionRest(expression, questionDotToken);
- continue;
+ }
+ function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
+ var options;
+ var lastDirectoryPartWithDirectorySeparator;
+ var lastDirectoryPart;
+ if (isLinuxOrMacOs) {
+ lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
+ lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
}
- if (isTemplateStartOfTaggedTemplate()) {
- expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
- continue;
+ /** 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) {
+ ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher"));
+ // Call the callback for current directory
+ callback("rename", "");
+ // If watcher is not closed, update it
+ if (watcher) {
+ watcher.close();
+ watcher = createWatcher();
+ }
}
- return expression;
- }
- }
- function isTemplateStartOfTaggedTemplate() {
- return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
- }
- function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
- var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
- tagExpression.tag = tag;
- tagExpression.questionDotToken = questionDotToken;
- tagExpression.typeArguments = typeArguments;
- tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
- ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
- : parseTemplateExpression(/*isTaggedTemplate*/ true);
- if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
- tagExpression.flags |= 32 /* OptionalChain */;
- }
- return finishNode(tagExpression);
- }
- function parseCallExpressionRest(expression) {
- while (true) {
- expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
- var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
- // handle 'foo<()'
- if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
- // 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) {
- if (isTemplateStartOfTaggedTemplate()) {
- expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
- continue;
+ /**
+ * 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 (fsSupportsRecursiveFsWatch) {
+ options = { persistent: true, recursive: !!recursive };
}
- var callExpr = createNode(196 /* CallExpression */, expression.pos);
- callExpr.expression = expression;
- callExpr.questionDotToken = questionDotToken;
- callExpr.typeArguments = typeArguments;
- callExpr.arguments = parseArgumentList();
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- callExpr.flags |= 32 /* OptionalChain */;
+ else {
+ options = { persistent: true };
}
- expression = finishNode(callExpr);
- continue;
+ }
+ if (hitSystemWatcherLimit) {
+ ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile"));
+ return watchPresentFileSystemEntryWithFsWatchFile();
+ }
+ try {
+ var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
+ callbackChangingToMissingFileSystemEntry :
+ 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
+ hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC");
+ ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile"));
+ return watchPresentFileSystemEntryWithFsWatchFile();
}
}
- else if (token() === 20 /* OpenParenToken */) {
- var callExpr = createNode(196 /* CallExpression */, expression.pos);
- callExpr.expression = expression;
- callExpr.questionDotToken = questionDotToken;
- callExpr.arguments = parseArgumentList();
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- callExpr.flags |= 32 /* OptionalChain */;
- }
- expression = finishNode(callExpr);
- continue;
+ function callbackChangingToMissingFileSystemEntry(event, relativeName) {
+ // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
+ // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
+ return event === "rename" &&
+ (!relativeName ||
+ relativeName === lastDirectoryPart ||
+ (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) &&
+ !fileSystemEntryExists(fileOrDirectory, entryKind) ?
+ invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
+ callback(event, relativeName);
}
- if (questionDotToken) {
- // We failed to parse anything, so report a missing identifier here.
- var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
- propertyAccess.expression = expression;
- propertyAccess.questionDotToken = questionDotToken;
- propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
- propertyAccess.flags |= 32 /* OptionalChain */;
- expression = finishNode(propertyAccess);
+ /**
+ * 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 watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
+ }
+ /**
+ * 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 watchFile(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);
+ }
+ }, fallbackPollingInterval, fallbackOptions);
}
- break;
- }
- return expression;
- }
- function parseArgumentList() {
- parseExpected(20 /* OpenParenToken */);
- var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
- parseExpected(21 /* CloseParenToken */);
- return result;
- }
- function parseTypeArgumentsInExpression() {
- if (reScanLessThanToken() !== 29 /* LessThanToken */) {
- return undefined;
- }
- nextToken();
- var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
- if (!parseExpected(31 /* 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 20 /* OpenParenToken */: // foo(
- case 14 /* NoSubstitutionTemplateLiteral */: // foo `...`
- case 15 /* 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.
- // falls through
- case 24 /* DotToken */: // foo.
- case 21 /* CloseParenToken */: // foo)
- case 23 /* CloseBracketToken */: // foo]
- case 58 /* ColonToken */: // foo:
- case 26 /* SemicolonToken */: // foo;
- case 57 /* QuestionToken */: // foo?
- case 34 /* EqualsEqualsToken */: // foo ==
- case 36 /* EqualsEqualsEqualsToken */: // foo ===
- case 35 /* ExclamationEqualsToken */: // foo !=
- case 37 /* ExclamationEqualsEqualsToken */: // foo !==
- case 55 /* AmpersandAmpersandToken */: // foo &&
- case 56 /* BarBarToken */: // foo ||
- case 60 /* QuestionQuestionToken */: // foo ??
- case 52 /* CaretToken */: // foo ^
- case 50 /* AmpersandToken */: // foo &
- case 51 /* BarToken */: // foo |
- case 19 /* 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 27 /* CommaToken */: // foo,
- case 18 /* 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.
- // falls through
- default:
- // Anything else treat as an expression.
- return false;
}
- }
- function parsePrimaryExpression() {
- switch (token()) {
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- return parseLiteralNode();
- case 104 /* ThisKeyword */:
- case 102 /* SuperKeyword */:
- case 100 /* NullKeyword */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- return parseTokenNode();
- case 20 /* OpenParenToken */:
- return parseParenthesizedExpression();
- case 22 /* OpenBracketToken */:
- return parseArrayLiteralExpression();
- case 18 /* OpenBraceToken */:
- return parseObjectLiteralExpression();
- case 126 /* 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 80 /* ClassKeyword */:
- return parseClassExpression();
- case 94 /* FunctionKeyword */:
- return parseFunctionExpression();
- case 99 /* NewKeyword */:
- return parseNewExpressionOrNewDotTarget();
- case 43 /* SlashToken */:
- case 67 /* SlashEqualsToken */:
- if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
- return parseLiteralNode();
+ function readFileWorker(fileName, _encoding) {
+ var buffer;
+ try {
+ buffer = _fs.readFileSync(fileName);
+ }
+ catch (e) {
+ return undefined;
+ }
+ var len = buffer.length;
+ if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
+ // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
+ // flip all byte pairs and treat as little endian.
+ len &= ~1; // Round down to a multiple of 2
+ for (var i = 0; i < len; i += 2) {
+ var temp = buffer[i];
+ buffer[i] = buffer[i + 1];
+ buffer[i + 1] = temp;
}
- break;
- case 15 /* TemplateHead */:
- return parseTemplateExpression(/* isTaggedTemplate */ false);
- }
- return parseIdentifier(ts.Diagnostics.Expression_expected);
- }
- function parseParenthesizedExpression() {
- var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- return finishNode(node);
- }
- function parseSpreadElement() {
- var node = createNode(213 /* SpreadElement */);
- parseExpected(25 /* DotDotDotToken */);
- node.expression = parseAssignmentExpressionOrHigher();
- return finishNode(node);
- }
- function parseArgumentOrArrayLiteralElement() {
- return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
- token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
- parseAssignmentExpressionOrHigher();
- }
- function parseArgumentExpression() {
- return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
- }
- function parseArrayLiteralExpression() {
- var node = createNode(192 /* ArrayLiteralExpression */);
- parseExpected(22 /* OpenBracketToken */);
- if (scanner.hasPrecedingLineBreak()) {
- node.multiLine = true;
- }
- node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
- parseExpected(23 /* CloseBracketToken */);
- return finishNode(node);
- }
- function parseObjectLiteralElement() {
- var node = createNodeWithJSDoc(0 /* Unknown */);
- if (parseOptionalToken(25 /* DotDotDotToken */)) {
- node.kind = 283 /* SpreadAssignment */;
- node.expression = parseAssignmentExpressionOrHigher();
- return finishNode(node);
- }
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers();
- if (parseContextualModifier(131 /* GetKeyword */)) {
- return parseAccessorDeclaration(node, 163 /* GetAccessor */);
- }
- if (parseContextualModifier(142 /* SetKeyword */)) {
- return parseAccessorDeclaration(node, 164 /* SetAccessor */);
- }
- var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- var tokenIsIdentifier = isIdentifier();
- node.name = parsePropertyName();
- // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
- node.questionToken = parseOptionalToken(57 /* QuestionToken */);
- node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
- if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
- return parseMethodDeclaration(node, asteriskToken);
- }
- // 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() !== 58 /* ColonToken */);
- if (isShorthandPropertyAssignment) {
- node.kind = 282 /* ShorthandPropertyAssignment */;
- var equalsToken = parseOptionalToken(62 /* EqualsToken */);
- if (equalsToken) {
- node.equalsToken = equalsToken;
- node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
+ return buffer.toString("utf16le", 2);
}
- }
- else {
- node.kind = 281 /* PropertyAssignment */;
- parseExpected(58 /* ColonToken */);
- node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
- }
- return finishNode(node);
- }
- function parseObjectLiteralExpression() {
- var node = createNode(193 /* ObjectLiteralExpression */);
- var openBracePosition = scanner.getTokenPos();
- parseExpected(18 /* OpenBraceToken */);
- if (scanner.hasPrecedingLineBreak()) {
- node.multiLine = true;
- }
- node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
- if (!parseExpected(19 /* CloseBraceToken */)) {
- var lastError = ts.lastOrUndefined(parseDiagnostics);
- if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
- ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
+ 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");
}
- 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(/*val*/ false);
- }
- var node = createNodeWithJSDoc(201 /* FunctionExpression */);
- node.modifiers = parseModifiers();
- parseExpected(94 /* FunctionKeyword */);
- node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
- node.name =
- isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
- isGenerator ? doInYieldContext(parseOptionalIdentifier) :
- isAsync ? doInAwaitContext(parseOptionalIdentifier) :
- parseOptionalIdentifier();
- fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
- node.body = parseFunctionBlock(isGenerator | isAsync);
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ true);
+ function readFile(fileName, _encoding) {
+ ts.perfLogger.logStartReadFile(fileName);
+ var file = readFileWorker(fileName, _encoding);
+ ts.perfLogger.logStopReadFile();
+ return file;
}
- return finishNode(node);
- }
- function parseOptionalIdentifier() {
- return isIdentifier() ? parseIdentifier() : undefined;
- }
- function parseNewExpressionOrNewDotTarget() {
- var fullStart = scanner.getStartPos();
- parseExpected(99 /* NewKeyword */);
- if (parseOptional(24 /* DotToken */)) {
- var node_2 = createNode(219 /* MetaProperty */, fullStart);
- node_2.keywordToken = 99 /* NewKeyword */;
- node_2.name = parseIdentifierName();
- return finishNode(node_2);
+ function writeFile(fileName, data, writeByteOrderMark) {
+ ts.perfLogger.logEvent("WriteFile: " + fileName);
+ // If a BOM is required, emit one
+ if (writeByteOrderMark) {
+ data = byteOrderMarkIndicator + data;
+ }
+ var fd;
+ try {
+ fd = _fs.openSync(fileName, "w");
+ _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
+ }
+ finally {
+ if (fd !== undefined) {
+ _fs.closeSync(fd);
+ }
+ }
}
- var expression = parsePrimaryExpression();
- var typeArguments;
- while (true) {
- expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
- typeArguments = tryParse(parseTypeArgumentsInExpression);
- if (isTemplateStartOfTaggedTemplate()) {
- ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
- expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
- typeArguments = undefined;
+ function getAccessibleFileSystemEntries(path) {
+ ts.perfLogger.logEvent("ReadDir: " + (path || "."));
+ try {
+ var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
+ var files = [];
+ var directories = [];
+ for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
+ var dirent = entries_1[_i];
+ // withFileTypes is not supported before Node 10.10.
+ var entry = typeof dirent === "string" ? dirent : dirent.name;
+ // 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;
+ }
+ var stat = void 0;
+ if (typeof dirent === "string" || dirent.isSymbolicLink()) {
+ var name = ts.combinePaths(path, entry);
+ try {
+ stat = statSync(name);
+ if (!stat) {
+ continue;
+ }
+ }
+ catch (e) {
+ continue;
+ }
+ }
+ else {
+ stat = dirent;
+ }
+ if (stat.isFile()) {
+ files.push(entry);
+ }
+ else if (stat.isDirectory()) {
+ directories.push(entry);
+ }
+ }
+ files.sort();
+ directories.sort();
+ return { files: files, directories: directories };
+ }
+ catch (e) {
+ return ts.emptyFileSystemEntries;
}
- break;
- }
- var node = createNode(197 /* NewExpression */, fullStart);
- node.expression = expression;
- node.typeArguments = typeArguments;
- if (token() === 20 /* OpenParenToken */) {
- node.arguments = parseArgumentList();
}
- else if (node.typeArguments) {
- parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
+ function readDirectory(path, extensions, excludes, includes, depth) {
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
- return finishNode(node);
- }
- // STATEMENTS
- function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
- var node = createNode(223 /* Block */);
- var openBracePosition = scanner.getTokenPos();
- if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
- if (scanner.hasPrecedingLineBreak()) {
- node.multiLine = true;
- }
- node.statements = parseList(1 /* BlockStatements */, parseStatement);
- if (!parseExpected(19 /* CloseBraceToken */)) {
- var lastError = ts.lastOrUndefined(parseDiagnostics);
- if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
- ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
+ function fileSystemEntryExists(path, entryKind) {
+ // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve
+ // the CPU time performance.
+ var originalStackTraceLimit = Error.stackTraceLimit;
+ Error.stackTraceLimit = 0;
+ try {
+ var stat = statSync(path);
+ if (!stat) {
+ return false;
+ }
+ switch (entryKind) {
+ case 0 /* File */: return stat.isFile();
+ case 1 /* Directory */: return stat.isDirectory();
+ default: return false;
}
}
+ catch (e) {
+ return false;
+ }
+ finally {
+ Error.stackTraceLimit = originalStackTraceLimit;
+ }
}
- else {
- node.statements = createMissingList();
+ function fileExists(path) {
+ return fileSystemEntryExists(path, 0 /* File */);
}
- return finishNode(node);
- }
- function parseFunctionBlock(flags, diagnosticMessage) {
- var savedYieldContext = inYieldContext();
- setYieldContext(!!(flags & 1 /* Yield */));
- var savedAwaitContext = inAwaitContext();
- 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(/*val*/ false);
+ function directoryExists(path) {
+ return fileSystemEntryExists(path, 1 /* Directory */);
}
- var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ true);
+ function getDirectories(path) {
+ return getAccessibleFileSystemEntries(path).directories.slice();
}
- setYieldContext(savedYieldContext);
- setAwaitContext(savedAwaitContext);
- return block;
- }
- function parseEmptyStatement() {
- var node = createNode(224 /* EmptyStatement */);
- parseExpected(26 /* SemicolonToken */);
- return finishNode(node);
- }
- function parseIfStatement() {
- var node = createNode(227 /* IfStatement */);
- parseExpected(95 /* IfKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- node.thenStatement = parseStatement();
- node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
- return finishNode(node);
- }
- function parseDoStatement() {
- var node = createNode(228 /* DoStatement */);
- parseExpected(86 /* DoKeyword */);
- node.statement = parseStatement();
- parseExpected(111 /* WhileKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* 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(26 /* SemicolonToken */);
- return finishNode(node);
- }
- function parseWhileStatement() {
- var node = createNode(229 /* WhileStatement */);
- parseExpected(111 /* WhileKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- node.statement = parseStatement();
- return finishNode(node);
- }
- function parseForOrForInOrForOfStatement() {
- var pos = getNodePos();
- parseExpected(93 /* ForKeyword */);
- var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
- parseExpected(20 /* OpenParenToken */);
- var initializer;
- if (token() !== 26 /* SemicolonToken */) {
- if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
- initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
+ function realpath(path) {
+ try {
+ return realpathSync(path);
}
- else {
- initializer = disallowInAnd(parseExpression);
+ catch (_a) {
+ return path;
}
}
- var forOrForInOrForOfStatement;
- if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
- var forOfStatement = createNode(232 /* ForOfStatement */, pos);
- forOfStatement.awaitModifier = awaitToken;
- forOfStatement.initializer = initializer;
- forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
- parseExpected(21 /* CloseParenToken */);
- forOrForInOrForOfStatement = forOfStatement;
- }
- else if (parseOptional(97 /* InKeyword */)) {
- var forInStatement = createNode(231 /* ForInStatement */, pos);
- forInStatement.initializer = initializer;
- forInStatement.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- forOrForInOrForOfStatement = forInStatement;
+ function getModifiedTime(path) {
+ var _a;
+ try {
+ return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime;
+ }
+ catch (e) {
+ return undefined;
+ }
}
- else {
- var forStatement = createNode(230 /* ForStatement */, pos);
- forStatement.initializer = initializer;
- parseExpected(26 /* SemicolonToken */);
- if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
- forStatement.condition = allowInAnd(parseExpression);
+ function setModifiedTime(path, time) {
+ try {
+ _fs.utimesSync(path, time, time);
}
- parseExpected(26 /* SemicolonToken */);
- if (token() !== 21 /* CloseParenToken */) {
- forStatement.incrementor = allowInAnd(parseExpression);
+ catch (e) {
+ return;
}
- parseExpected(21 /* CloseParenToken */);
- forOrForInOrForOfStatement = forStatement;
}
- forOrForInOrForOfStatement.statement = parseStatement();
- return finishNode(forOrForInOrForOfStatement);
- }
- function parseBreakOrContinueStatement(kind) {
- var node = createNode(kind);
- parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
- if (!canParseSemicolon()) {
- node.label = parseIdentifier();
+ function deleteFile(path) {
+ try {
+ return _fs.unlinkSync(path);
+ }
+ catch (e) {
+ return;
+ }
}
- parseSemicolon();
- return finishNode(node);
- }
- function parseReturnStatement() {
- var node = createNode(235 /* ReturnStatement */);
- parseExpected(101 /* ReturnKeyword */);
- if (!canParseSemicolon()) {
- node.expression = allowInAnd(parseExpression);
+ function createSHA256Hash(data) {
+ var hash = _crypto.createHash("sha256");
+ hash.update(data);
+ return hash.digest("hex");
}
- parseSemicolon();
- return finishNode(node);
- }
- function parseWithStatement() {
- var node = createNode(236 /* WithStatement */);
- parseExpected(112 /* WithKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
- return finishNode(node);
- }
- function parseCaseClause() {
- var node = createNode(277 /* CaseClause */);
- parseExpected(78 /* CaseKeyword */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(58 /* ColonToken */);
- node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
- return finishNode(node);
- }
- function parseDefaultClause() {
- var node = createNode(278 /* DefaultClause */);
- parseExpected(84 /* DefaultKeyword */);
- parseExpected(58 /* ColonToken */);
- node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
- return finishNode(node);
- }
- function parseCaseOrDefaultClause() {
- return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
}
- function parseSwitchStatement() {
- var node = createNode(237 /* SwitchStatement */);
- parseExpected(103 /* SwitchKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- var caseBlock = createNode(251 /* CaseBlock */);
- parseExpected(18 /* OpenBraceToken */);
- caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
- parseExpected(19 /* CloseBraceToken */);
- node.caseBlock = finishNode(caseBlock);
- return finishNode(node);
+ var sys;
+ 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();
}
- function parseThrowStatement() {
- // 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(239 /* ThrowStatement */);
- parseExpected(105 /* ThrowKeyword */);
- node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
- parseSemicolon();
- return finishNode(node);
+ if (sys) {
+ // patch writefile to create folder before writing the file
+ patchWriteFileEnsuringDirectory(sys);
}
- // TODO: Review for error recovery
- function parseTryStatement() {
- var node = createNode(240 /* TryStatement */);
- parseExpected(107 /* TryKeyword */);
- node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
- node.catchClause = token() === 79 /* 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() === 92 /* FinallyKeyword */) {
- parseExpected(92 /* FinallyKeyword */);
- node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
- }
- return finishNode(node);
+ return sys;
+ })();
+ /*@internal*/
+ function setSys(s) {
+ ts.sys = s;
+ }
+ ts.setSys = setSys;
+ if (ts.sys && ts.sys.getEnvironmentVariable) {
+ setCustomPollingValues(ts.sys);
+ ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
+ ? 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, elidedInCompatabilityPyramid, reportsDeprecated) {
+ return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid, reportsDeprecated: reportsDeprecated };
+ }
+ 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."),
+ _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
+ A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."),
+ The_parser_expected_to_find_a_to_match_the_token_here: diag(1007, ts.DiagnosticCategory.Error, "The_parser_expected_to_find_a_to_match_the_token_here_1007", "The parser expected to find a '}' to match the '{' token here."),
+ Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
+ Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
+ An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."),
+ Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
+ A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."),
+ A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."),
+ Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."),
+ A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."),
+ An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."),
+ An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."),
+ An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."),
+ An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."),
+ An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."),
+ An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."),
+ readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."),
+ An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."),
+ Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
+ _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
+ _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
+ _0_modifier_cannot_appear_on_class_elements_of_this_kind: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031", "'{0}' modifier cannot appear on class elements of this kind."),
+ super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."),
+ Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."),
+ Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."),
+ A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."),
+ Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."),
+ _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."),
+ _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
+ _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."),
+ Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier: diag(1046, ts.DiagnosticCategory.Error, "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046", "Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier."),
+ A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
+ A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."),
+ A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."),
+ A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."),
+ A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."),
+ A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."),
+ A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
+ Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."),
+ Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."),
+ The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."),
+ A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."),
+ The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."),
+ Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
+ Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."),
+ An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."),
+ The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"),
+ In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."),
+ Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."),
+ Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."),
+ _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."),
+ _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."),
+ A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."),
+ Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
+ Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."),
+ _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."),
+ _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."),
+ Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."),
+ Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."),
+ Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."),
+ An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
+ A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."),
+ An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."),
+ _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
+ Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
+ Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
+ Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."),
+ with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."),
+ delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."),
+ for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."),
+ A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."),
+ A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."),
+ The_left_hand_side_of_a_for_of_statement_may_not_be_async: diag(1106, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106", "The left-hand side of a 'for...of' statement may not be 'async'."),
+ Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
+ A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."),
+ Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
+ Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
+ A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."),
+ Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
+ A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."),
+ A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."),
+ An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."),
+ An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."),
+ An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."),
+ An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
+ Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."),
+ Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
+ Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
+ Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
+ Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
+ Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
+ Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
+ Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
+ case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
+ Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
+ Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
+ Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
+ Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
+ Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
+ Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
+ Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
+ Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
+ Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
+ String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
+ Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
+ or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
+ Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
+ Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."),
+ Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."),
+ File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."),
+ const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
+ const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."),
+ let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."),
+ Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
+ Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
+ An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."),
+ A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."),
+ Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."),
+ A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."),
+ A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."),
+ A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."),
+ A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."),
+ A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."),
+ A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."),
+ extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
+ extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
+ Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."),
+ implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
+ Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
+ Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
+ Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
+ Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
+ Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
+ Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
+ A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."),
+ An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."),
+ Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
+ Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
+ A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."),
+ A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."),
+ Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."),
+ The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."),
+ The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."),
+ An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
+ Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
+ An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
+ Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."),
+ export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."),
+ Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196", "Catch clause variable type annotation must be 'any' or 'unknown' if specified."),
+ Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."),
+ An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."),
+ Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
+ Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
+ Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."),
+ Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."),
+ Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type: diag(1205, ts.DiagnosticCategory.Error, "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205", "Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'."),
+ Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
+ Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
+ _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."),
+ Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."),
+ A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
+ Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
+ Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."),
+ Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."),
+ Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."),
+ Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."),
+ Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."),
+ Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning."),
+ Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."),
+ An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."),
+ _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
+ Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."),
+ Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
+ Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."),
+ Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."),
+ A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."),
+ A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."),
+ A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."),
+ An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."),
+ An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."),
+ An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."),
+ An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."),
+ A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."),
+ The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."),
+ The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."),
+ Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."),
+ Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."),
+ Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."),
+ Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."),
+ abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."),
+ _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."),
+ Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."),
+ Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."),
+ An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."),
+ A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."),
+ A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."),
+ A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."),
+ Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."),
+ Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),
+ Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),
+ A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),
+ A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."),
+ A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."),
+ A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."),
+ Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"),
+ Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
+ Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."),
+ Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module: diag(1262, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262", "Identifier expected. '{0}' is a reserved word at the top-level of a module."),
+ Declarations_with_initializers_cannot_also_have_definite_assignment_assertions: diag(1263, ts.DiagnosticCategory.Error, "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263", "Declarations with initializers cannot also have definite assignment assertions."),
+ Declarations_with_definite_assignment_assertions_must_also_have_type_annotations: diag(1264, ts.DiagnosticCategory.Error, "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264", "Declarations with definite assignment assertions must also have type annotations."),
+ A_rest_element_cannot_follow_another_rest_element: diag(1265, ts.DiagnosticCategory.Error, "A_rest_element_cannot_follow_another_rest_element_1265", "A rest element cannot follow another rest element."),
+ An_optional_element_cannot_follow_a_rest_element: diag(1266, ts.DiagnosticCategory.Error, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."),
+ Property_0_cannot_have_an_initializer_because_it_is_marked_abstract: diag(1267, ts.DiagnosticCategory.Error, "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267", "Property '{0}' cannot have an initializer because it is marked abstract."),
+ An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type: diag(1268, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268", "An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type."),
+ with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."),
+ await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."),
+ Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."),
+ The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."),
+ Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."),
+ Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."),
+ Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."),
+ A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."),
+ An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."),
+ A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."),
+ Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
+ Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
+ Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
+ Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node12_or_nodenext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12', or 'nodenext'."),
+ Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext'."),
+ Argument_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Argument_of_dynamic_import_cannot_be_spread_element_1325", "Argument of dynamic import cannot be spread element."),
+ Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."),
+ String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
+ Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."),
+ _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"),
+ A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."),
+ A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."),
+ A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."),
+ unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."),
+ unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."),
+ unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."),
+ An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337", "An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead."),
+ infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."),
+ Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."),
+ Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"),
+ Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
+ The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node12_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'."),
+ A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
+ An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness."),
+ This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."),
+ use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."),
+ Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
+ use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
+ Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."),
+ An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
+ A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
+ A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355", "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."),
+ Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"),
+ An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."),
+ Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."),
+ Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."),
+ _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."),
+ _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."),
+ A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."),
+ Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
+ Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"),
+ Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
+ Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
+ Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
+ This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371", "This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'."),
+ Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
+ Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"),
+ await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."),
+ _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
+ _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
+ Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher."),
+ An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."),
+ An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."),
+ Unexpected_token_Did_you_mean_or_rbrace: diag(1381, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_rbrace_1381", "Unexpected token. Did you mean `{'}'}` or `}`?"),
+ Unexpected_token_Did_you_mean_or_gt: diag(1382, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_gt_1382", "Unexpected token. Did you mean `{'>'}` or `>`?"),
+ Only_named_exports_may_use_export_type: diag(1383, ts.DiagnosticCategory.Error, "Only_named_exports_may_use_export_type_1383", "Only named exports may use 'export type'."),
+ A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list: diag(1384, ts.DiagnosticCategory.Error, "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384", "A 'new' expression with type arguments must always be followed by a parenthesized argument list."),
+ Function_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1385, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385", "Function type notation must be parenthesized when used in a union type."),
+ Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1386, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386", "Constructor type notation must be parenthesized when used in a union type."),
+ Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."),
+ Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."),
+ _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."),
+ _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."),
+ An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"),
+ Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"),
+ Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"),
+ Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions: diag(1395, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395", "Imported via {0} from file '{1}' to import 'importHelpers' as specified in compilerOptions"),
+ Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions: diag(1396, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396", "Imported via {0} from file '{1}' with packageId '{2}' to import 'importHelpers' as specified in compilerOptions"),
+ Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions: diag(1397, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397", "Imported via {0} from file '{1}' to import 'jsx' and 'jsxs' factory functions"),
+ Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions: diag(1398, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398", "Imported via {0} from file '{1}' with packageId '{2}' to import 'jsx' and 'jsxs' factory functions"),
+ File_is_included_via_import_here: diag(1399, ts.DiagnosticCategory.Message, "File_is_included_via_import_here_1399", "File is included via import here."),
+ Referenced_via_0_from_file_1: diag(1400, ts.DiagnosticCategory.Message, "Referenced_via_0_from_file_1_1400", "Referenced via '{0}' from file '{1}'"),
+ File_is_included_via_reference_here: diag(1401, ts.DiagnosticCategory.Message, "File_is_included_via_reference_here_1401", "File is included via reference here."),
+ Type_library_referenced_via_0_from_file_1: diag(1402, ts.DiagnosticCategory.Message, "Type_library_referenced_via_0_from_file_1_1402", "Type library referenced via '{0}' from file '{1}'"),
+ Type_library_referenced_via_0_from_file_1_with_packageId_2: diag(1403, ts.DiagnosticCategory.Message, "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403", "Type library referenced via '{0}' from file '{1}' with packageId '{2}'"),
+ File_is_included_via_type_library_reference_here: diag(1404, ts.DiagnosticCategory.Message, "File_is_included_via_type_library_reference_here_1404", "File is included via type library reference here."),
+ Library_referenced_via_0_from_file_1: diag(1405, ts.DiagnosticCategory.Message, "Library_referenced_via_0_from_file_1_1405", "Library referenced via '{0}' from file '{1}'"),
+ File_is_included_via_library_reference_here: diag(1406, ts.DiagnosticCategory.Message, "File_is_included_via_library_reference_here_1406", "File is included via library reference here."),
+ Matched_by_include_pattern_0_in_1: diag(1407, ts.DiagnosticCategory.Message, "Matched_by_include_pattern_0_in_1_1407", "Matched by include pattern '{0}' in '{1}'"),
+ File_is_matched_by_include_pattern_specified_here: diag(1408, ts.DiagnosticCategory.Message, "File_is_matched_by_include_pattern_specified_here_1408", "File is matched by include pattern specified here."),
+ Part_of_files_list_in_tsconfig_json: diag(1409, ts.DiagnosticCategory.Message, "Part_of_files_list_in_tsconfig_json_1409", "Part of 'files' list in tsconfig.json"),
+ File_is_matched_by_files_list_specified_here: diag(1410, ts.DiagnosticCategory.Message, "File_is_matched_by_files_list_specified_here_1410", "File is matched by 'files' list specified here."),
+ Output_from_referenced_project_0_included_because_1_specified: diag(1411, ts.DiagnosticCategory.Message, "Output_from_referenced_project_0_included_because_1_specified_1411", "Output from referenced project '{0}' included because '{1}' specified"),
+ Output_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1412, ts.DiagnosticCategory.Message, "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412", "Output from referenced project '{0}' included because '--module' is specified as 'none'"),
+ File_is_output_from_referenced_project_specified_here: diag(1413, ts.DiagnosticCategory.Message, "File_is_output_from_referenced_project_specified_here_1413", "File is output from referenced project specified here."),
+ Source_from_referenced_project_0_included_because_1_specified: diag(1414, ts.DiagnosticCategory.Message, "Source_from_referenced_project_0_included_because_1_specified_1414", "Source from referenced project '{0}' included because '{1}' specified"),
+ Source_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1415, ts.DiagnosticCategory.Message, "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415", "Source from referenced project '{0}' included because '--module' is specified as 'none'"),
+ File_is_source_from_referenced_project_specified_here: diag(1416, ts.DiagnosticCategory.Message, "File_is_source_from_referenced_project_specified_here_1416", "File is source from referenced project specified here."),
+ Entry_point_of_type_library_0_specified_in_compilerOptions: diag(1417, ts.DiagnosticCategory.Message, "Entry_point_of_type_library_0_specified_in_compilerOptions_1417", "Entry point of type library '{0}' specified in compilerOptions"),
+ Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1: diag(1418, ts.DiagnosticCategory.Message, "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418", "Entry point of type library '{0}' specified in compilerOptions with packageId '{1}'"),
+ File_is_entry_point_of_type_library_specified_here: diag(1419, ts.DiagnosticCategory.Message, "File_is_entry_point_of_type_library_specified_here_1419", "File is entry point of type library specified here."),
+ Entry_point_for_implicit_type_library_0: diag(1420, ts.DiagnosticCategory.Message, "Entry_point_for_implicit_type_library_0_1420", "Entry point for implicit type library '{0}'"),
+ Entry_point_for_implicit_type_library_0_with_packageId_1: diag(1421, ts.DiagnosticCategory.Message, "Entry_point_for_implicit_type_library_0_with_packageId_1_1421", "Entry point for implicit type library '{0}' with packageId '{1}'"),
+ Library_0_specified_in_compilerOptions: diag(1422, ts.DiagnosticCategory.Message, "Library_0_specified_in_compilerOptions_1422", "Library '{0}' specified in compilerOptions"),
+ File_is_library_specified_here: diag(1423, ts.DiagnosticCategory.Message, "File_is_library_specified_here_1423", "File is library specified here."),
+ Default_library: diag(1424, ts.DiagnosticCategory.Message, "Default_library_1424", "Default library"),
+ Default_library_for_target_0: diag(1425, ts.DiagnosticCategory.Message, "Default_library_for_target_0_1425", "Default library for target '{0}'"),
+ File_is_default_library_for_target_specified_here: diag(1426, ts.DiagnosticCategory.Message, "File_is_default_library_for_target_specified_here_1426", "File is default library for target specified here."),
+ Root_file_specified_for_compilation: diag(1427, ts.DiagnosticCategory.Message, "Root_file_specified_for_compilation_1427", "Root file specified for compilation"),
+ File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"),
+ File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"),
+ The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"),
+ for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."),
+ Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher."),
+ Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."),
+ Unexpected_keyword_or_identifier: diag(1434, ts.DiagnosticCategory.Error, "Unexpected_keyword_or_identifier_1434", "Unexpected keyword or identifier."),
+ Unknown_keyword_or_identifier_Did_you_mean_0: diag(1435, ts.DiagnosticCategory.Error, "Unknown_keyword_or_identifier_Did_you_mean_0_1435", "Unknown keyword or identifier. Did you mean '{0}'?"),
+ Decorators_must_precede_the_name_and_all_keywords_of_property_declarations: diag(1436, ts.DiagnosticCategory.Error, "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436", "Decorators must precede the name and all keywords of property declarations."),
+ Namespace_must_be_given_a_name: diag(1437, ts.DiagnosticCategory.Error, "Namespace_must_be_given_a_name_1437", "Namespace must be given a name."),
+ Interface_must_be_given_a_name: diag(1438, ts.DiagnosticCategory.Error, "Interface_must_be_given_a_name_1438", "Interface must be given a name."),
+ Type_alias_must_be_given_a_name: diag(1439, ts.DiagnosticCategory.Error, "Type_alias_must_be_given_a_name_1439", "Type alias must be given a name."),
+ Variable_declaration_not_allowed_at_this_location: diag(1440, ts.DiagnosticCategory.Error, "Variable_declaration_not_allowed_at_this_location_1440", "Variable declaration not allowed at this location."),
+ Cannot_start_a_function_call_in_a_type_annotation: diag(1441, ts.DiagnosticCategory.Error, "Cannot_start_a_function_call_in_a_type_annotation_1441", "Cannot start a function call in a type annotation."),
+ Expected_for_property_initializer: diag(1442, ts.DiagnosticCategory.Error, "Expected_for_property_initializer_1442", "Expected '=' for property initializer."),
+ Module_declaration_names_may_only_use_or_quoted_strings: diag(1443, ts.DiagnosticCategory.Error, "Module_declaration_names_may_only_use_or_quoted_strings_1443", "Module declaration names may only use ' or \" quoted strings."),
+ _0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled: diag(1444, ts.DiagnosticCategory.Error, "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444", "'{0}' is a type and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled."),
+ _0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled: diag(1446, ts.DiagnosticCategory.Error, "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveVa_1446", "'{0}' resolves to a type-only declaration and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled."),
+ _0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_isolatedModules_is_enabled: diag(1448, ts.DiagnosticCategory.Error, "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_isol_1448", "'{0}' resolves to a type-only declaration and must be re-exported using a type-only re-export when 'isolatedModules' is enabled."),
+ Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."),
+ Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"),
+ Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"),
+ The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."),
+ Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."),
+ The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."),
+ The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."),
+ Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
+ Construct_signature_return_types_0_and_1_are_incompatible: diag(2203, ts.DiagnosticCategory.Error, "Construct_signature_return_types_0_and_1_are_incompatible_2203", "Construct signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
+ Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2204, ts.DiagnosticCategory.Error, "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
+ Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
+ The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."),
+ The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."),
+ Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
+ Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),
+ Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."),
+ Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
+ Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
+ Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."),
+ File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
+ Cannot_find_module_0_or_its_corresponding_type_declarations: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", "Cannot find module '{0}' or its corresponding type declarations."),
+ Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."),
+ An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
+ Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
+ Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
+ Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
+ Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
+ Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."),
+ Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."),
+ Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
+ Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."),
+ Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."),
+ Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."),
+ Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."),
+ Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
+ Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."),
+ Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."),
+ Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
+ Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."),
+ Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."),
+ Index_signature_for_type_0_is_missing_in_type_1: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_for_type_0_is_missing_in_type_1_2329", "Index signature for type '{0}' is missing in type '{1}'."),
+ _0_and_1_index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "_0_and_1_index_signatures_are_incompatible_2330", "'{0}' and '{1}' index signatures are incompatible."),
+ this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."),
+ this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."),
+ this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."),
+ this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."),
+ super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."),
+ super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."),
+ Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."),
+ super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."),
+ Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."),
+ Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."),
+ Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."),
+ This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."),
+ Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."),
+ Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."),
+ Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."),
+ Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."),
+ Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"),
+ This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
+ Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."),
+ This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
+ Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."),
+ Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."),
+ This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."),
+ A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."),
+ An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."),
+ The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."),
+ The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."),
+ The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."),
+ The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360", "The left-hand side of an 'in' expression must be a private identifier or of type 'any', 'string', 'number', or 'symbol'."),
+ The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."),
+ The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
+ The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
+ The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."),
+ Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."),
+ Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."),
+ This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."),
+ Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
+ A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."),
+ A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."),
+ A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."),
+ Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
+ Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."),
+ Duplicate_index_signature_for_type_0: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_index_signature_for_type_0_2374", "Duplicate index signature for type '{0}'."),
+ Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2375, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."),
+ A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."),
+ Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."),
+ A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."),
+ Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2379, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379", "Argument of type '{0}' is not assignable to parameter of type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."),
+ The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"),
+ Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."),
+ Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."),
+ Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."),
+ Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."),
+ Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
+ Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
+ Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
+ Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
+ Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
+ Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
+ Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
+ Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
+ Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
+ Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
+ constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."),
+ Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."),
+ Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."),
+ Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."),
+ Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."),
+ The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."),
+ The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."),
+ The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."),
+ The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."),
+ Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
+ Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."),
+ The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."),
+ Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target: diag(2412, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target."),
+ Property_0_of_type_1_is_not_assignable_to_2_index_type_3: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411", "Property '{0}' of type '{1}' is not assignable to '{2}' index type '{3}'."),
+ _0_index_type_1_is_not_assignable_to_2_index_type_3: diag(2413, ts.DiagnosticCategory.Error, "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413", "'{0}' index type '{1}' is not assignable to '{2}' index type '{3}'."),
+ Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
+ Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."),
+ Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."),
+ Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
+ Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
+ Types_of_construct_signatures_are_incompatible: diag(2419, ts.DiagnosticCategory.Error, "Types_of_construct_signatures_are_incompatible_2419", "Types of construct signatures are incompatible."),
+ Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
+ Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
+ Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
+ Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."),
+ Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
+ All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."),
+ Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
+ Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
+ In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."),
+ A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."),
+ A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."),
+ Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."),
+ Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."),
+ Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."),
+ Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
+ Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."),
+ Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."),
+ Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."),
+ Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."),
+ Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."),
+ Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."),
+ Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."),
+ Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."),
+ The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."),
+ Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."),
+ Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
+ Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
+ Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
+ An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."),
+ Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."),
+ Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
+ Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
+ An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."),
+ Module_0_declares_1_locally_but_it_is_not_exported: diag(2459, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_not_exported_2459", "Module '{0}' declares '{1}' locally, but it is not exported."),
+ Module_0_declares_1_locally_but_it_is_exported_as_2: diag(2460, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_exported_as_2_2460", "Module '{0}' declares '{1}' locally, but it is exported as '{2}'."),
+ Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."),
+ A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."),
+ A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."),
+ A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."),
+ this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."),
+ super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."),
+ A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."),
+ Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
+ The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."),
+ Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."),
+ Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."),
+ const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."),
+ const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."),
+ A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."),
+ const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."),
+ const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."),
+ let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."),
+ Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."),
+ The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."),
+ Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."),
+ The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."),
+ Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."),
+ An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."),
+ The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the '{0}()' method of an iterator must have a 'value' property."),
+ The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."),
+ Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."),
+ Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."),
+ Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."),
+ Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."),
+ The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."),
+ This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."),
+ Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."),
+ An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."),
+ A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."),
+ A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."),
+ _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."),
+ Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
+ Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."),
+ A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."),
+ _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
+ Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
+ No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
+ Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
+ Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
+ Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
+ Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."),
+ Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."),
+ All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."),
+ Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."),
+ A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."),
+ An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."),
+ Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."),
+ The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."),
+ yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."),
+ await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."),
+ Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."),
+ A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."),
+ The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."),
+ A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."),
+ Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."),
+ Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."),
+ Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
+ Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
+ Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
+ A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."),
+ Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."),
+ Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."),
+ Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
+ Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
+ Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
+ Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
+ Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
+ Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."),
+ A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."),
+ The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."),
+ Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
+ Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
+ Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."),
+ Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),
+ Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"),
+ Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."),
+ Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
+ Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."),
+ A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."),
+ Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."),
+ Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."),
+ Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"),
+ Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"),
+ Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."),
+ The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."),
+ Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."),
+ Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."),
+ A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."),
+ Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."),
+ Property_0_may_not_exist_on_type_1_Did_you_mean_2: diag(2568, ts.DiagnosticCategory.Error, "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568", "Property '{0}' may not exist on type '{1}'. Did you mean '{2}'?"),
+ Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),
+ Could_not_find_name_0_Did_you_mean_1: diag(2570, ts.DiagnosticCategory.Error, "Could_not_find_name_0_Did_you_mean_1_2570", "Could not find name '{0}'. Did you mean '{1}'?"),
+ Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
+ A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."),
+ No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),
+ Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead: diag(2576, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576", "Property '{0}' does not exist on type '{1}'. Did you mean to access the static member '{2}' instead?"),
+ Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
+ Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."),
+ Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."),
+ Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."),
+ _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."),
+ This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."),
+ _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."),
+ _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."),
+ _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."),
+ _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."),
+ JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
+ Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."),
+ JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."),
+ Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."),
+ JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."),
+ The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."),
+ JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."),
+ _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."),
+ _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."),
+ Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."),
+ Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"),
+ Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"),
+ Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."),
+ _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."),
+ _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."),
+ Source_has_0_element_s_but_target_requires_1: diag(2618, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_requires_1_2618", "Source has {0} element(s) but target requires {1}."),
+ Source_has_0_element_s_but_target_allows_only_1: diag(2619, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_allows_only_1_2619", "Source has {0} element(s) but target allows only {1}."),
+ Target_requires_0_element_s_but_source_may_have_fewer: diag(2620, ts.DiagnosticCategory.Error, "Target_requires_0_element_s_but_source_may_have_fewer_2620", "Target requires {0} element(s) but source may have fewer."),
+ Target_allows_only_0_element_s_but_source_may_have_more: diag(2621, ts.DiagnosticCategory.Error, "Target_allows_only_0_element_s_but_source_may_have_more_2621", "Target allows only {0} element(s) but source may have more."),
+ Source_provides_no_match_for_required_element_at_position_0_in_target: diag(2623, ts.DiagnosticCategory.Error, "Source_provides_no_match_for_required_element_at_position_0_in_target_2623", "Source provides no match for required element at position {0} in target."),
+ Source_provides_no_match_for_variadic_element_at_position_0_in_target: diag(2624, ts.DiagnosticCategory.Error, "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624", "Source provides no match for variadic element at position {0} in target."),
+ Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."),
+ Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."),
+ Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."),
+ Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."),
+ Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."),
+ Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."),
+ Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."),
+ Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."),
+ JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"),
+ _0_index_signatures_are_incompatible: diag(2634, ts.DiagnosticCategory.Error, "_0_index_signatures_are_incompatible_2634", "'{0}' index signatures are incompatible."),
+ Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."),
+ A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."),
+ Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."),
+ Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."),
+ JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."),
+ Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."),
+ super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."),
+ super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."),
+ Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."),
+ Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"),
+ Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"),
+ Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."),
+ Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."),
+ Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."),
+ Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."),
+ export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."),
+ Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."),
+ Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."),
+ Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."),
+ Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."),
+ Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."),
+ Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."),
+ Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."),
+ Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."),
+ A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."),
+ Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."),
+ A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."),
+ A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."),
+ A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."),
+ this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."),
+ The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."),
+ The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."),
+ _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."),
+ All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."),
+ Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."),
+ Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"),
+ _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0: diag(2690, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690", "'{0}' only refers to a type, but is being used as a value here. Did you mean to use '{1} in {0}'?"),
+ An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."),
+ _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.", /*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."),
+ Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."),
+ Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."),
+ The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."),
+ _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."),
+ The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."),
+ The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."),
+ An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."),
+ Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."),
+ Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."),
+ Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."),
+ Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."),
+ _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."),
+ A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."),
+ A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."),
+ Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"),
+ The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."),
+ Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."),
+ Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."),
+ Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."),
+ Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
+ Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."),
+ Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"),
+ Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
+ Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
+ Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ _0_has_no_exported_member_named_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "_0_has_no_exported_member_named_1_Did_you_mean_2_2724", "'{0}' has no exported member named '{1}'. Did you mean '{2}'?"),
+ Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."),
+ Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
+ Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"),
+ _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
+ Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."),
+ An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."),
+ Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),
+ Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension."),
+ Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
+ Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
+ Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"),
+ Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."),
+ BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."),
+ An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."),
+ Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
+ Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
+ Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
+ No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."),
+ Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."),
+ This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
+ This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
+ _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749", "'{0}' refers to a value, but is being used as a type here. Did you mean 'typeof {0}'?"),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
+ super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
+ No_constituent_of_type_0_is_callable: diag(2755, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_callable_2755", "No constituent of type '{0}' is callable."),
+ Not_all_constituents_of_type_0_are_callable: diag(2756, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_callable_2756", "Not all constituents of type '{0}' are callable."),
+ Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
+ Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2758, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758", "Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other."),
+ No_constituent_of_type_0_is_constructable: diag(2759, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_constructable_2759", "No constituent of type '{0}' is constructable."),
+ Not_all_constituents_of_type_0_are_constructable: diag(2760, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_constructable_2760", "Not all constituents of type '{0}' are constructable."),
+ Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
+ Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2762, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762", "Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other."),
+ Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0: diag(2763, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but for-of will always send '{0}'."),
+ Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0: diag(2764, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array spread will always send '{0}'."),
+ Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0: diag(2765, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array destructuring will always send '{0}'."),
+ Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0: diag(2766, ts.DiagnosticCategory.Error, "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766", "Cannot delegate iteration to value because the 'next' method of its iterator expects type '{1}', but the containing generator will always send '{0}'."),
+ The_0_property_of_an_iterator_must_be_a_method: diag(2767, ts.DiagnosticCategory.Error, "The_0_property_of_an_iterator_must_be_a_method_2767", "The '{0}' property of an iterator must be a method."),
+ The_0_property_of_an_async_iterator_must_be_a_method: diag(2768, ts.DiagnosticCategory.Error, "The_0_property_of_an_async_iterator_must_be_a_method_2768", "The '{0}' property of an async iterator must be a method."),
+ No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
+ The_last_overload_gave_the_following_error: diag(2770, ts.DiagnosticCategory.Error, "The_last_overload_gave_the_following_error_2770", "The last overload gave the following error."),
+ The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
+ Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."),
+ Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
+ This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"),
+ Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."),
+ Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."),
+ The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."),
+ The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access: diag(2778, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778", "The target of an object rest assignment may not be an optional property access."),
+ The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access: diag(2779, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779", "The left-hand side of an assignment expression may not be an optional property access."),
+ The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."),
+ The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."),
+ _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
+ _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."),
+ get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."),
+ This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
+ _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."),
+ Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."),
+ Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."),
+ Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."),
+ The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."),
+ Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."),
+ Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option: diag(2792, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_th_2792", "Cannot find module '{0}'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?"),
+ The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible: diag(2793, ts.DiagnosticCategory.Error, "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793", "The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible."),
+ Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise: diag(2794, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794", "Expected {0} arguments, but got {1}. Did you forget to include 'void' in your type argument to 'Promise'?"),
+ The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."),
+ It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."),
+ A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."),
+ The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."),
+ Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."),
+ Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."),
+ This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."),
+ Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."),
+ Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."),
+ Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."),
+ Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."),
+ Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."),
+ This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."),
+ A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"),
+ Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."),
+ Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."),
+ Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"),
+ Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."),
+ Class_declaration_cannot_implement_overload_list_for_0: diag(2813, ts.DiagnosticCategory.Error, "Class_declaration_cannot_implement_overload_list_for_0_2813", "Class declaration cannot implement overload list for '{0}'."),
+ Function_with_bodies_can_only_merge_with_classes_that_are_ambient: diag(2814, ts.DiagnosticCategory.Error, "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814", "Function with bodies can only merge with classes that are ambient."),
+ arguments_cannot_be_referenced_in_property_initializers: diag(2815, ts.DiagnosticCategory.Error, "arguments_cannot_be_referenced_in_property_initializers_2815", "'arguments' cannot be referenced in property initializers."),
+ Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class: diag(2816, ts.DiagnosticCategory.Error, "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816", "Cannot use 'this' in a static property initializer of a decorated class."),
+ Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block: diag(2817, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817", "Property '{0}' has no initializer and is not definitely assigned in a class static block."),
+ Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers: diag(2818, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818", "Duplicate identifier '{0}'. Compiler reserves name '{1}' when emitting 'super' references in static initializers."),
+ Namespace_name_cannot_be_0: diag(2819, ts.DiagnosticCategory.Error, "Namespace_name_cannot_be_0_2819", "Namespace name cannot be '{0}'."),
+ Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"),
+ Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."),
+ Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."),
+ Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"),
+ Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."),
+ Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"),
+ Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
+ Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
+ Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."),
+ Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."),
+ Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."),
+ extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."),
+ extends_clause_of_exported_class_has_or_is_using_private_name_0: diag(4021, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021", "'extends' clause of exported class has or is using private name '{0}'."),
+ extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."),
+ Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."),
+ Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."),
+ Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."),
+ Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
+ Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."),
+ Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
+ Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."),
+ Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
+ Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."),
+ Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
+ Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."),
+ Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
+ Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."),
+ Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
+ Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."),
+ Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
+ Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."),
+ Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."),
+ Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."),
+ Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."),
+ Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
+ Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."),
+ Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
+ Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."),
+ Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."),
+ Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."),
+ Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."),
+ Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."),
+ Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."),
+ Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
+ Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
+ Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
+ Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."),
+ Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."),
+ Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."),
+ Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."),
+ Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."),
+ Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."),
+ Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."),
+ Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."),
+ Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."),
+ Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."),
+ Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
+ Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
+ Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."),
+ Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
+ Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
+ Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
+ Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
+ Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
+ The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1: diag(4104, ts.DiagnosticCategory.Error, "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104", "The type '{0}' is 'readonly' and cannot be assigned to the mutable type '{1}'."),
+ Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter: diag(4105, ts.DiagnosticCategory.Error, "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105", "Private or protected member '{0}' cannot be accessed on a type parameter."),
+ Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."),
+ Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."),
+ Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."),
+ Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."),
+ Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
+ Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."),
+ This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."),
+ This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."),
+ This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."),
+ This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."),
+ This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."),
+ This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4117, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'. Did you mean '{1}'?"),
+ The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized: diag(4118, ts.DiagnosticCategory.Error, "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118", "The type of this node cannot be serialized because its property '{0}' cannot be serialized."),
+ This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0: diag(4119, ts.DiagnosticCategory.Error, "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119", "This member must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'."),
+ This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0: diag(4120, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120", "This parameter property must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'."),
+ This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."),
+ This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."),
+ This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"),
+ Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."),
+ The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
+ Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
+ File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
+ Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
+ Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."),
+ Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
+ Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."),
+ Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"),
+ Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."),
+ Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."),
+ Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."),
+ Option_0_cannot_be_specified_when_option_target_is_ES3: diag(5048, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_target_is_ES3_5048", "Option '{0}' cannot be specified when option 'target' is 'ES3'."),
+ Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."),
+ Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."),
+ Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."),
+ A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."),
+ Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."),
+ Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."),
+ Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."),
+ The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."),
+ Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."),
+ Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."),
+ Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' can have at most one '*' character."),
+ Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."),
+ Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."),
+ File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."),
+ Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."),
+ Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
+ Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
+ Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
+ Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),
+ Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
+ Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."),
+ Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."),
+ _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."),
+ _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."),
+ Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"),
+ Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
+ Unknown_watch_option_0_Did_you_mean_1: diag(5079, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"),
+ Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."),
+ Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."),
+ _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."),
+ Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
+ Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."),
+ A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."),
+ A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."),
+ A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."),
+ The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."),
+ Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."),
+ Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"),
+ Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."),
+ The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."),
+ Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."),
+ Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."),
+ Option_preserveValueImports_can_only_be_used_when_module_is_set_to_es2015_or_later: diag(5095, ts.DiagnosticCategory.Error, "Option_preserveValueImports_can_only_be_used_when_module_is_set_to_es2015_or_later_5095", "Option 'preserveValueImports' can only be used when 'module' is set to 'es2015' or later."),
+ Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
+ Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
+ Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
+ Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."),
+ Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
+ Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
+ Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."),
+ Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."),
+ Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
+ Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
+ Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."),
+ Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
+ Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
+ Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
+ Specify_ECMAScript_target_version: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_6015", "Specify ECMAScript target version."),
+ Specify_module_code_generation: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_6016", "Specify module code generation."),
+ Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
+ Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
+ Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."),
+ Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
+ options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
+ file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
+ Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
+ Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
+ Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
+ Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."),
+ Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
+ File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
+ KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
+ FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
+ VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
+ LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
+ DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
+ STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
+ FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
+ Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
+ Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
+ Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."),
+ Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."),
+ Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."),
+ Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
+ Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
+ Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."),
+ File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
+ File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."),
+ Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."),
+ Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."),
+ Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."),
+ File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."),
+ Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."),
+ NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
+ Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."),
+ Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
+ Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."),
+ Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."),
+ Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."),
+ Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
+ Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."),
+ Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."),
+ Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."),
+ Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."),
+ Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."),
+ Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."),
+ Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."),
+ Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."),
+ Specify_JSX_code_generation: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_6080", "Specify JSX code generation."),
+ File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."),
+ Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."),
+ Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."),
+ Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"),
+ Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."),
+ Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
+ Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."),
+ Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."),
+ Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"),
+ Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
+ paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."),
+ Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
+ Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."),
+ Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."),
+ Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."),
+ File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
+ File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."),
+ Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."),
+ Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
+ package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."),
+ package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."),
+ Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
+ Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),
+ Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),
+ baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),
+ rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."),
+ Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."),
+ Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."),
+ Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
+ Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
+ Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."),
+ Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
+ Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"),
+ Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."),
+ Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"),
+ Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"),
+ Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"),
+ Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
+ Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."),
+ Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"),
+ Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."),
+ Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."),
+ Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."),
+ Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"),
+ Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"),
+ 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.", /*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.", /*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."),
+ Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."),
+ Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
+ Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
+ Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
+ Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
+ Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
+ Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
+ Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."),
+ Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."),
+ Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."),
+ Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."),
+ Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."),
+ The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"),
+ Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."),
+ Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."),
+ Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."),
+ Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."),
+ List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."),
+ Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
+ The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."),
+ Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
+ Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
+ A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."),
+ List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."),
+ Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
+ Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"),
+ Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
+ Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."),
+ Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
+ List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
+ Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
+ Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183", "Reusing resolution of module '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."),
+ Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3: diag(6184, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184", "Reusing resolution of module '{0}' from '{1}' of old program, it was successfully resolved to '{2}' with Package ID '{3}'."),
+ Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
+ Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."),
+ Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
+ 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."),
+ 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.", /*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.", /*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.", /*reportsUnnecessary*/ true),
+ All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
+ Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"),
+ Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
+ 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}"),
+ _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
+ and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
+ All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused."),
+ package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."),
+ package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),
+ package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),
+ package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),
+ An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."),
+ An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."),
+ Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"),
+ Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"),
+ Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."),
+ Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."),
+ Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
+ Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
+ Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2: diag(6218, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218", "======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========"),
+ Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3: diag(6219, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219", "======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========"),
+ package_json_had_a_falsy_0_field: diag(6220, ts.DiagnosticCategory.Message, "package_json_had_a_falsy_0_field_6220", "'package.json' had a falsy '{0}' field."),
+ Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects: diag(6221, ts.DiagnosticCategory.Message, "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221", "Disable use of source files instead of declaration files from referenced projects."),
+ Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."),
+ Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
+ Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
+ Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
+ Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."),
+ Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."),
+ Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."),
+ Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."),
+ Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."),
+ Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."),
+ This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."),
+ This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without: diag(6234, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234", "This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'?"),
+ Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."),
+ Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."),
+ Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."),
+ Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"),
+ File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."),
+ File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."),
+ Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."),
+ Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"),
+ Interpret_optional_property_types_as_written_rather_than_adding_undefined: diag(6243, ts.DiagnosticCategory.Message, "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243", "Interpret optional property types as written, rather than adding 'undefined'."),
+ Modules: diag(6244, ts.DiagnosticCategory.Message, "Modules_6244", "Modules"),
+ File_Management: diag(6245, ts.DiagnosticCategory.Message, "File_Management_6245", "File Management"),
+ Emit: diag(6246, ts.DiagnosticCategory.Message, "Emit_6246", "Emit"),
+ JavaScript_Support: diag(6247, ts.DiagnosticCategory.Message, "JavaScript_Support_6247", "JavaScript Support"),
+ Type_Checking: diag(6248, ts.DiagnosticCategory.Message, "Type_Checking_6248", "Type Checking"),
+ Editor_Support: diag(6249, ts.DiagnosticCategory.Message, "Editor_Support_6249", "Editor Support"),
+ Watch_and_Build_Modes: diag(6250, ts.DiagnosticCategory.Message, "Watch_and_Build_Modes_6250", "Watch and Build Modes"),
+ Compiler_Diagnostics: diag(6251, ts.DiagnosticCategory.Message, "Compiler_Diagnostics_6251", "Compiler Diagnostics"),
+ Interop_Constraints: diag(6252, ts.DiagnosticCategory.Message, "Interop_Constraints_6252", "Interop Constraints"),
+ Backwards_Compatibility: diag(6253, ts.DiagnosticCategory.Message, "Backwards_Compatibility_6253", "Backwards Compatibility"),
+ Language_and_Environment: diag(6254, ts.DiagnosticCategory.Message, "Language_and_Environment_6254", "Language and Environment"),
+ Projects: diag(6255, ts.DiagnosticCategory.Message, "Projects_6255", "Projects"),
+ Output_Formatting: diag(6256, ts.DiagnosticCategory.Message, "Output_Formatting_6256", "Output Formatting"),
+ Completeness: diag(6257, ts.DiagnosticCategory.Message, "Completeness_6257", "Completeness"),
+ _0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file: diag(6258, ts.DiagnosticCategory.Error, "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258", "'{0}' should be set inside the 'compilerOptions' object of the config json file"),
+ Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve: diag(6270, ts.DiagnosticCategory.Message, "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270", "Directory '{0}' has no containing package.json scope. Imports will not resolve."),
+ Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6271, ts.DiagnosticCategory.Message, "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271", "Import specifier '{0}' does not exist in package.json scope at path '{1}'."),
+ Invalid_import_specifier_0_has_no_possible_resolutions: diag(6272, ts.DiagnosticCategory.Message, "Invalid_import_specifier_0_has_no_possible_resolutions_6272", "Invalid import specifier '{0}' has no possible resolutions."),
+ package_json_scope_0_has_no_imports_defined: diag(6273, ts.DiagnosticCategory.Message, "package_json_scope_0_has_no_imports_defined_6273", "package.json scope '{0}' has no imports defined."),
+ package_json_scope_0_explicitly_maps_specifier_1_to_null: diag(6274, ts.DiagnosticCategory.Message, "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274", "package.json scope '{0}' explicitly maps specifier '{1}' to null."),
+ package_json_scope_0_has_invalid_type_for_target_of_specifier_1: diag(6275, ts.DiagnosticCategory.Message, "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275", "package.json scope '{0}' has invalid type for target of specifier '{1}'"),
+ Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6276, ts.DiagnosticCategory.Message, "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276", "Export specifier '{0}' does not exist in package.json scope at path '{1}'."),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307", "File '{0}' is not listed within the file list of project '{1}'. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
+ Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."),
+ Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"),
+ Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"),
+ Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"),
+ Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"),
+ Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"),
+ Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
+ A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"),
+ A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"),
+ Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
+ Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
+ Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
+ Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"),
+ Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"),
+ Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"),
+ Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
+ Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"),
+ Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
+ Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
+ Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
+ Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"),
+ Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"),
+ Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."),
+ _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
+ Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."),
+ The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
+ Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"),
+ Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved: diag(6389, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389", "Reusing resolution of module '{0}' from '{1}' of old program, it was not resolved."),
+ Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6390, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."),
+ Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3: diag(6391, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}' with Package ID '{3}'."),
+ Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved: diag(6392, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was not resolved."),
+ Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6393, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."),
+ Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6394, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."),
+ Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6395, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was not resolved."),
+ Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."),
+ Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."),
+ Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."),
+ The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
+ The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
+ The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
+ Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."),
+ File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"),
+ Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."),
+ Consider_adding_a_declare_modifier_to_this_class: diag(6506, ts.DiagnosticCategory.Message, "Consider_adding_a_declare_modifier_to_this_class_6506", "Consider adding a 'declare' modifier to this class."),
+ Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files: diag(6600, ts.DiagnosticCategory.Message, "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600", "Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files."),
+ Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export: diag(6601, ts.DiagnosticCategory.Message, "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601", "Allow 'import x from y' when a module doesn't have a default export."),
+ Allow_accessing_UMD_globals_from_modules: diag(6602, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_6602", "Allow accessing UMD globals from modules."),
+ Disable_error_reporting_for_unreachable_code: diag(6603, ts.DiagnosticCategory.Message, "Disable_error_reporting_for_unreachable_code_6603", "Disable error reporting for unreachable code."),
+ Disable_error_reporting_for_unused_labels: diag(6604, ts.DiagnosticCategory.Message, "Disable_error_reporting_for_unused_labels_6604", "Disable error reporting for unused labels."),
+ Ensure_use_strict_is_always_emitted: diag(6605, ts.DiagnosticCategory.Message, "Ensure_use_strict_is_always_emitted_6605", "Ensure 'use strict' is always emitted."),
+ Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6606, ts.DiagnosticCategory.Message, "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606", "Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it."),
+ Specify_the_base_directory_to_resolve_non_relative_module_names: diag(6607, ts.DiagnosticCategory.Message, "Specify_the_base_directory_to_resolve_non_relative_module_names_6607", "Specify the base directory to resolve non-relative module names."),
+ No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files: diag(6608, ts.DiagnosticCategory.Message, "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608", "No longer supported. In early versions, manually set the text encoding for reading files."),
+ Enable_error_reporting_in_type_checked_JavaScript_files: diag(6609, ts.DiagnosticCategory.Message, "Enable_error_reporting_in_type_checked_JavaScript_files_6609", "Enable error reporting in type-checked JavaScript files."),
+ Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references: diag(6611, ts.DiagnosticCategory.Message, "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611", "Enable constraints that allow a TypeScript project to be used with project references."),
+ Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project: diag(6612, ts.DiagnosticCategory.Message, "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612", "Generate .d.ts files from TypeScript and JavaScript files in your project."),
+ Specify_the_output_directory_for_generated_declaration_files: diag(6613, ts.DiagnosticCategory.Message, "Specify_the_output_directory_for_generated_declaration_files_6613", "Specify the output directory for generated declaration files."),
+ Create_sourcemaps_for_d_ts_files: diag(6614, ts.DiagnosticCategory.Message, "Create_sourcemaps_for_d_ts_files_6614", "Create sourcemaps for d.ts files."),
+ Output_compiler_performance_information_after_building: diag(6615, ts.DiagnosticCategory.Message, "Output_compiler_performance_information_after_building_6615", "Output compiler performance information after building."),
+ Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project: diag(6616, ts.DiagnosticCategory.Message, "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616", "Disables inference for type acquisition by looking at filenames in a project."),
+ Reduce_the_number_of_projects_loaded_automatically_by_TypeScript: diag(6617, ts.DiagnosticCategory.Message, "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617", "Reduce the number of projects loaded automatically by TypeScript."),
+ Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server: diag(6618, ts.DiagnosticCategory.Message, "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618", "Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server."),
+ Opt_a_project_out_of_multi_project_reference_checking_when_editing: diag(6619, ts.DiagnosticCategory.Message, "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619", "Opt a project out of multi-project reference checking when editing."),
+ Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects: diag(6620, ts.DiagnosticCategory.Message, "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620", "Disable preferring source files instead of declaration files when referencing composite projects"),
+ Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration: diag(6621, ts.DiagnosticCategory.Message, "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621", "Emit more compliant, but verbose and less performant JavaScript for iteration."),
+ Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6622, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
+ Only_output_d_ts_files_and_not_JavaScript_files: diag(6623, ts.DiagnosticCategory.Message, "Only_output_d_ts_files_and_not_JavaScript_files_6623", "Only output d.ts files and not JavaScript files."),
+ Emit_design_type_metadata_for_decorated_declarations_in_source_files: diag(6624, ts.DiagnosticCategory.Message, "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624", "Emit design-type metadata for decorated declarations in source files."),
+ Disable_the_type_acquisition_for_JavaScript_projects: diag(6625, ts.DiagnosticCategory.Message, "Disable_the_type_acquisition_for_JavaScript_projects_6625", "Disable the type acquisition for JavaScript projects"),
+ Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility: diag(6626, ts.DiagnosticCategory.Message, "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626", "Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility."),
+ Filters_results_from_the_include_option: diag(6627, ts.DiagnosticCategory.Message, "Filters_results_from_the_include_option_6627", "Filters results from the `include` option."),
+ Remove_a_list_of_directories_from_the_watch_process: diag(6628, ts.DiagnosticCategory.Message, "Remove_a_list_of_directories_from_the_watch_process_6628", "Remove a list of directories from the watch process."),
+ Remove_a_list_of_files_from_the_watch_mode_s_processing: diag(6629, ts.DiagnosticCategory.Message, "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629", "Remove a list of files from the watch mode's processing."),
+ Enable_experimental_support_for_TC39_stage_2_draft_decorators: diag(6630, ts.DiagnosticCategory.Message, "Enable_experimental_support_for_TC39_stage_2_draft_decorators_6630", "Enable experimental support for TC39 stage 2 draft decorators."),
+ Print_files_read_during_the_compilation_including_why_it_was_included: diag(6631, ts.DiagnosticCategory.Message, "Print_files_read_during_the_compilation_including_why_it_was_included_6631", "Print files read during the compilation including why it was included."),
+ Output_more_detailed_compiler_performance_information_after_building: diag(6632, ts.DiagnosticCategory.Message, "Output_more_detailed_compiler_performance_information_after_building_6632", "Output more detailed compiler performance information after building."),
+ Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_are_inherited: diag(6633, ts.DiagnosticCategory.Message, "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633", "Specify one or more path or node module references to base configuration files from which settings are inherited."),
+ Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers: diag(6634, ts.DiagnosticCategory.Message, "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634", "Specify what approach the watcher should use if the system runs out of native file watchers."),
+ Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include: diag(6635, ts.DiagnosticCategory.Message, "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635", "Include a list of files. This does not support glob patterns, as opposed to `include`."),
+ Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6636, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636", "Build all projects, including those that appear to be up to date"),
+ Ensure_that_casing_is_correct_in_imports: diag(6637, ts.DiagnosticCategory.Message, "Ensure_that_casing_is_correct_in_imports_6637", "Ensure that casing is correct in imports."),
+ Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging: diag(6638, ts.DiagnosticCategory.Message, "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638", "Emit a v8 CPU profile of the compiler run for debugging."),
+ Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file: diag(6639, ts.DiagnosticCategory.Message, "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639", "Allow importing helper functions from tslib once per project, instead of including them per-file."),
+ Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation: diag(6641, ts.DiagnosticCategory.Message, "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641", "Specify a list of glob patterns that match files to be included in compilation."),
+ Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects: diag(6642, ts.DiagnosticCategory.Message, "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642", "Save .tsbuildinfo files to allow for incremental compilation of projects."),
+ Include_sourcemap_files_inside_the_emitted_JavaScript: diag(6643, ts.DiagnosticCategory.Message, "Include_sourcemap_files_inside_the_emitted_JavaScript_6643", "Include sourcemap files inside the emitted JavaScript."),
+ Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript: diag(6644, ts.DiagnosticCategory.Message, "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644", "Include source code in the sourcemaps inside the emitted JavaScript."),
+ Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports: diag(6645, ts.DiagnosticCategory.Message, "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645", "Ensure that each file can be safely transpiled without relying on other imports."),
+ Specify_what_JSX_code_is_generated: diag(6646, ts.DiagnosticCategory.Message, "Specify_what_JSX_code_is_generated_6646", "Specify what JSX code is generated."),
+ Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h: diag(6647, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647", "Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'"),
+ Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment: diag(6648, ts.DiagnosticCategory.Message, "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648", "Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'."),
+ Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk: diag(6649, ts.DiagnosticCategory.Message, "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649", "Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`"),
+ Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option: diag(6650, ts.DiagnosticCategory.Message, "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650", "Make keyof only return strings instead of string, numbers or symbols. Legacy option."),
+ Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment: diag(6651, ts.DiagnosticCategory.Message, "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651", "Specify a set of bundled library declaration files that describe the target runtime environment."),
+ Print_the_names_of_emitted_files_after_a_compilation: diag(6652, ts.DiagnosticCategory.Message, "Print_the_names_of_emitted_files_after_a_compilation_6652", "Print the names of emitted files after a compilation."),
+ Print_all_of_the_files_read_during_the_compilation: diag(6653, ts.DiagnosticCategory.Message, "Print_all_of_the_files_read_during_the_compilation_6653", "Print all of the files read during the compilation."),
+ Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit: diag(6654, ts.DiagnosticCategory.Message, "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654", "Set the language of the messaging from TypeScript. This does not affect emit."),
+ Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6655, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655", "Specify the location where debugger should locate map files instead of generated locations."),
+ Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs: diag(6656, ts.DiagnosticCategory.Message, "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656", "Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`."),
+ Specify_what_module_code_is_generated: diag(6657, ts.DiagnosticCategory.Message, "Specify_what_module_code_is_generated_6657", "Specify what module code is generated."),
+ Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier: diag(6658, ts.DiagnosticCategory.Message, "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658", "Specify how TypeScript looks up a file from a given module specifier."),
+ Set_the_newline_character_for_emitting_files: diag(6659, ts.DiagnosticCategory.Message, "Set_the_newline_character_for_emitting_files_6659", "Set the newline character for emitting files."),
+ Disable_emitting_files_from_a_compilation: diag(6660, ts.DiagnosticCategory.Message, "Disable_emitting_files_from_a_compilation_6660", "Disable emitting files from a compilation."),
+ Disable_generating_custom_helper_functions_like_extends_in_compiled_output: diag(6661, ts.DiagnosticCategory.Message, "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661", "Disable generating custom helper functions like `__extends` in compiled output."),
+ Disable_emitting_files_if_any_type_checking_errors_are_reported: diag(6662, ts.DiagnosticCategory.Message, "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662", "Disable emitting files if any type checking errors are reported."),
+ Disable_truncating_types_in_error_messages: diag(6663, ts.DiagnosticCategory.Message, "Disable_truncating_types_in_error_messages_6663", "Disable truncating types in error messages."),
+ Enable_error_reporting_for_fallthrough_cases_in_switch_statements: diag(6664, ts.DiagnosticCategory.Message, "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664", "Enable error reporting for fallthrough cases in switch statements."),
+ Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type: diag(6665, ts.DiagnosticCategory.Message, "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665", "Enable error reporting for expressions and declarations with an implied `any` type.."),
+ Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6666, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666", "Ensure overriding members in derived classes are marked with an override modifier."),
+ Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function: diag(6667, ts.DiagnosticCategory.Message, "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667", "Enable error reporting for codepaths that do not explicitly return in a function."),
+ Enable_error_reporting_when_this_is_given_the_type_any: diag(6668, ts.DiagnosticCategory.Message, "Enable_error_reporting_when_this_is_given_the_type_any_6668", "Enable error reporting when `this` is given the type `any`."),
+ Disable_adding_use_strict_directives_in_emitted_JavaScript_files: diag(6669, ts.DiagnosticCategory.Message, "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669", "Disable adding 'use strict' directives in emitted JavaScript files."),
+ Disable_including_any_library_files_including_the_default_lib_d_ts: diag(6670, ts.DiagnosticCategory.Message, "Disable_including_any_library_files_including_the_default_lib_d_ts_6670", "Disable including any library files, including the default lib.d.ts."),
+ Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type: diag(6671, ts.DiagnosticCategory.Message, "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671", "Enforces using indexed accessors for keys declared using an indexed type"),
+ Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project: diag(6672, ts.DiagnosticCategory.Message, "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672", "Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project."),
+ Disable_strict_checking_of_generic_signatures_in_function_types: diag(6673, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6673", "Disable strict checking of generic signatures in function types."),
+ Add_undefined_to_a_type_when_accessed_using_an_index: diag(6674, ts.DiagnosticCategory.Message, "Add_undefined_to_a_type_when_accessed_using_an_index_6674", "Add `undefined` to a type when accessed using an index."),
+ Enable_error_reporting_when_a_local_variables_aren_t_read: diag(6675, ts.DiagnosticCategory.Message, "Enable_error_reporting_when_a_local_variables_aren_t_read_6675", "Enable error reporting when a local variables aren't read."),
+ Raise_an_error_when_a_function_parameter_isn_t_read: diag(6676, ts.DiagnosticCategory.Message, "Raise_an_error_when_a_function_parameter_isn_t_read_6676", "Raise an error when a function parameter isn't read"),
+ Deprecated_setting_Use_outFile_instead: diag(6677, ts.DiagnosticCategory.Message, "Deprecated_setting_Use_outFile_instead_6677", "Deprecated setting. Use `outFile` instead."),
+ Specify_an_output_folder_for_all_emitted_files: diag(6678, ts.DiagnosticCategory.Message, "Specify_an_output_folder_for_all_emitted_files_6678", "Specify an output folder for all emitted files."),
+ Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output: diag(6679, ts.DiagnosticCategory.Message, "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679", "Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output."),
+ Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations: diag(6680, ts.DiagnosticCategory.Message, "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680", "Specify a set of entries that re-map imports to additional lookup locations."),
+ Specify_a_list_of_language_service_plugins_to_include: diag(6681, ts.DiagnosticCategory.Message, "Specify_a_list_of_language_service_plugins_to_include_6681", "Specify a list of language service plugins to include."),
+ Disable_erasing_const_enum_declarations_in_generated_code: diag(6682, ts.DiagnosticCategory.Message, "Disable_erasing_const_enum_declarations_in_generated_code_6682", "Disable erasing `const enum` declarations in generated code."),
+ Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node: diag(6683, ts.DiagnosticCategory.Message, "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683", "Disable resolving symlinks to their realpath. This correlates to the same flag in node."),
+ Disable_wiping_the_console_in_watch_mode: diag(6684, ts.DiagnosticCategory.Message, "Disable_wiping_the_console_in_watch_mode_6684", "Disable wiping the console in watch mode"),
+ Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read: diag(6685, ts.DiagnosticCategory.Message, "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685", "Enable color and formatting in TypeScript's output to make compiler errors easier to read"),
+ Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit: diag(6686, ts.DiagnosticCategory.Message, "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686", "Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit."),
+ Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references: diag(6687, ts.DiagnosticCategory.Message, "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687", "Specify an array of objects that specify paths for projects. Used in project references."),
+ Disable_emitting_comments: diag(6688, ts.DiagnosticCategory.Message, "Disable_emitting_comments_6688", "Disable emitting comments."),
+ Enable_importing_json_files: diag(6689, ts.DiagnosticCategory.Message, "Enable_importing_json_files_6689", "Enable importing .json files"),
+ Specify_the_root_folder_within_your_source_files: diag(6690, ts.DiagnosticCategory.Message, "Specify_the_root_folder_within_your_source_files_6690", "Specify the root folder within your source files."),
+ Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules: diag(6691, ts.DiagnosticCategory.Message, "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691", "Allow multiple folders to be treated as one when resolving modules."),
+ Skip_type_checking_d_ts_files_that_are_included_with_TypeScript: diag(6692, ts.DiagnosticCategory.Message, "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692", "Skip type checking .d.ts files that are included with TypeScript."),
+ Skip_type_checking_all_d_ts_files: diag(6693, ts.DiagnosticCategory.Message, "Skip_type_checking_all_d_ts_files_6693", "Skip type checking all .d.ts files."),
+ Create_source_map_files_for_emitted_JavaScript_files: diag(6694, ts.DiagnosticCategory.Message, "Create_source_map_files_for_emitted_JavaScript_files_6694", "Create source map files for emitted JavaScript files."),
+ Specify_the_root_path_for_debuggers_to_find_the_reference_source_code: diag(6695, ts.DiagnosticCategory.Message, "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695", "Specify the root path for debuggers to find the reference source code."),
+ Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function: diag(6697, ts.DiagnosticCategory.Message, "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697", "Check that the arguments for `bind`, `call`, and `apply` methods match the original function."),
+ When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible: diag(6698, ts.DiagnosticCategory.Message, "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698", "When assigning functions, check to ensure parameters and the return values are subtype-compatible."),
+ When_type_checking_take_into_account_null_and_undefined: diag(6699, ts.DiagnosticCategory.Message, "When_type_checking_take_into_account_null_and_undefined_6699", "When type checking, take into account `null` and `undefined`."),
+ Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor: diag(6700, ts.DiagnosticCategory.Message, "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700", "Check for class properties that are declared but not set in the constructor."),
+ Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments: diag(6701, ts.DiagnosticCategory.Message, "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701", "Disable emitting declarations that have `@internal` in their JSDoc comments."),
+ Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals: diag(6702, ts.DiagnosticCategory.Message, "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702", "Disable reporting of excess property errors during the creation of object literals."),
+ Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures: diag(6703, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703", "Suppress `noImplicitAny` errors when indexing objects that lack index signatures."),
+ Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6704, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704", "Synchronously call callbacks and update the state of directory watchers on platforms that don`t support recursive watching natively."),
+ Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations: diag(6705, ts.DiagnosticCategory.Message, "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705", "Set the JavaScript language version for emitted JavaScript and include compatible library declarations."),
+ Log_paths_used_during_the_moduleResolution_process: diag(6706, ts.DiagnosticCategory.Message, "Log_paths_used_during_the_moduleResolution_process_6706", "Log paths used during the `moduleResolution` process."),
+ Specify_the_folder_for_tsbuildinfo_incremental_compilation_files: diag(6707, ts.DiagnosticCategory.Message, "Specify_the_folder_for_tsbuildinfo_incremental_compilation_files_6707", "Specify the folder for .tsbuildinfo incremental compilation files."),
+ Specify_options_for_automatic_acquisition_of_declaration_files: diag(6709, ts.DiagnosticCategory.Message, "Specify_options_for_automatic_acquisition_of_declaration_files_6709", "Specify options for automatic acquisition of declaration files."),
+ Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types: diag(6710, ts.DiagnosticCategory.Message, "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710", "Specify multiple folders that act like `./node_modules/@types`."),
+ Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file: diag(6711, ts.DiagnosticCategory.Message, "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711", "Specify type package names to be included without being referenced in a source file."),
+ Emit_ECMAScript_standard_compliant_class_fields: diag(6712, ts.DiagnosticCategory.Message, "Emit_ECMAScript_standard_compliant_class_fields_6712", "Emit ECMAScript-standard-compliant class fields."),
+ Enable_verbose_logging: diag(6713, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6713", "Enable verbose logging"),
+ Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality: diag(6714, ts.DiagnosticCategory.Message, "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714", "Specify how directories are watched on systems that lack recursive file-watching functionality."),
+ Specify_how_the_TypeScript_watch_mode_works: diag(6715, ts.DiagnosticCategory.Message, "Specify_how_the_TypeScript_watch_mode_works_6715", "Specify how the TypeScript watch mode works."),
+ Include_undefined_in_index_signature_results: diag(6716, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6716", "Include 'undefined' in index signature results"),
+ Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6717, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717", "Require undeclared properties from index signatures to use element accesses."),
+ Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(6718, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718", "Specify emit/checking behavior for imports that are only used for types"),
+ Type_catch_clause_variables_as_unknown_instead_of_any: diag(6803, ts.DiagnosticCategory.Message, "Type_catch_clause_variables_as_unknown_instead_of_any_6803", "Type catch clause variables as 'unknown' instead of 'any'."),
+ one_of_Colon: diag(6900, ts.DiagnosticCategory.Message, "one_of_Colon_6900", "one of:"),
+ one_or_more_Colon: diag(6901, ts.DiagnosticCategory.Message, "one_or_more_Colon_6901", "one or more:"),
+ type_Colon: diag(6902, ts.DiagnosticCategory.Message, "type_Colon_6902", "type:"),
+ default_Colon: diag(6903, ts.DiagnosticCategory.Message, "default_Colon_6903", "default:"),
+ module_system_or_esModuleInterop: diag(6904, ts.DiagnosticCategory.Message, "module_system_or_esModuleInterop_6904", "module === \"system\" or esModuleInterop"),
+ false_unless_strict_is_set: diag(6905, ts.DiagnosticCategory.Message, "false_unless_strict_is_set_6905", "`false`, unless `strict` is set"),
+ false_unless_composite_is_set: diag(6906, ts.DiagnosticCategory.Message, "false_unless_composite_is_set_6906", "`false`, unless `composite` is set"),
+ node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified: diag(6907, ts.DiagnosticCategory.Message, "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907", "`[\"node_modules\", \"bower_components\", \"jspm_packages\"]`, plus the value of `outDir` if one is specified."),
+ if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk: diag(6908, ts.DiagnosticCategory.Message, "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908", "`[]` if `files` is specified, otherwise `[\"**/*\"]`"),
+ true_if_composite_false_otherwise: diag(6909, ts.DiagnosticCategory.Message, "true_if_composite_false_otherwise_6909", "`true` if `composite`, `false` otherwise"),
+ module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node: diag(69010, ts.DiagnosticCategory.Message, "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010", "module === `AMD` or `UMD` or `System` or `ES6`, then `Classic`, Otherwise `Node`"),
+ Computed_from_the_list_of_input_files: diag(6911, ts.DiagnosticCategory.Message, "Computed_from_the_list_of_input_files_6911", "Computed from the list of input files"),
+ Platform_specific: diag(6912, ts.DiagnosticCategory.Message, "Platform_specific_6912", "Platform specific"),
+ You_can_learn_about_all_of_the_compiler_options_at_0: diag(6913, ts.DiagnosticCategory.Message, "You_can_learn_about_all_of_the_compiler_options_at_0_6913", "You can learn about all of the compiler options at {0}"),
+ Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon: diag(6914, ts.DiagnosticCategory.Message, "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914", "Including --watch, -w will start watching the current project for the file changes. Once set, you can config watch mode with:"),
+ Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0: diag(6915, ts.DiagnosticCategory.Message, "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915", "Using --build, -b will make tsc behave more like a build orchestrator than a compiler. This is used to trigger building composite projects which you can learn more about at {0}"),
+ COMMON_COMMANDS: diag(6916, ts.DiagnosticCategory.Message, "COMMON_COMMANDS_6916", "COMMON COMMANDS"),
+ ALL_COMPILER_OPTIONS: diag(6917, ts.DiagnosticCategory.Message, "ALL_COMPILER_OPTIONS_6917", "ALL COMPILER OPTIONS"),
+ WATCH_OPTIONS: diag(6918, ts.DiagnosticCategory.Message, "WATCH_OPTIONS_6918", "WATCH OPTIONS"),
+ BUILD_OPTIONS: diag(6919, ts.DiagnosticCategory.Message, "BUILD_OPTIONS_6919", "BUILD OPTIONS"),
+ COMMON_COMPILER_OPTIONS: diag(6920, ts.DiagnosticCategory.Message, "COMMON_COMPILER_OPTIONS_6920", "COMMON COMPILER OPTIONS"),
+ COMMAND_LINE_FLAGS: diag(6921, ts.DiagnosticCategory.Message, "COMMAND_LINE_FLAGS_6921", "COMMAND LINE FLAGS"),
+ tsc_Colon_The_TypeScript_Compiler: diag(6922, ts.DiagnosticCategory.Message, "tsc_Colon_The_TypeScript_Compiler_6922", "tsc: The TypeScript Compiler"),
+ Compiles_the_current_project_tsconfig_json_in_the_working_directory: diag(6923, ts.DiagnosticCategory.Message, "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923", "Compiles the current project (tsconfig.json in the working directory.)"),
+ Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options: diag(6924, ts.DiagnosticCategory.Message, "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924", "Ignoring tsconfig.json, compiles the specified files with default compiler options."),
+ Build_a_composite_project_in_the_working_directory: diag(6925, ts.DiagnosticCategory.Message, "Build_a_composite_project_in_the_working_directory_6925", "Build a composite project in the working directory."),
+ Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory: diag(6926, ts.DiagnosticCategory.Message, "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926", "Creates a tsconfig.json with the recommended settings in the working directory."),
+ Compiles_the_TypeScript_project_located_at_the_specified_path: diag(6927, ts.DiagnosticCategory.Message, "Compiles_the_TypeScript_project_located_at_the_specified_path_6927", "Compiles the TypeScript project located at the specified path."),
+ An_expanded_version_of_this_information_showing_all_possible_compiler_options: diag(6928, ts.DiagnosticCategory.Message, "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928", "An expanded version of this information, showing all possible compiler options"),
+ Compiles_the_current_project_with_additional_settings: diag(6929, ts.DiagnosticCategory.Message, "Compiles_the_current_project_with_additional_settings_6929", "Compiles the current project, with additional settings."),
+ true_for_ES2022_and_above_including_ESNext: diag(6930, ts.DiagnosticCategory.Message, "true_for_ES2022_and_above_including_ESNext_6930", "`true` for ES2022 and above, including ESNext."),
+ Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
+ Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
+ Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
+ new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."),
+ _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."),
+ Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."),
+ Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."),
+ Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."),
+ Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."),
+ Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."),
+ Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."),
+ Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."),
+ Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."),
+ Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."),
+ _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."),
+ _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
+ Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: 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_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_retu_7025", "Generator implicitly has yield type '{0}' because it does not yield any values. Consider supplying a return type annotation."),
+ 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.", /*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."),
+ Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."),
+ Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."),
+ Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."),
+ Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035", "Try `npm i --save-dev @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
+ Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."),
+ Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."),
+ Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."),
+ Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."),
+ If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
+ Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),
+ Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
+ Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
+ Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
+ Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."),
+ Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."),
+ Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
+ Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
+ _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
+ Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1: diag(7052, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052", "Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?"),
+ Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1: diag(7053, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053", "Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'."),
+ No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1: diag(7054, ts.DiagnosticCategory.Error, "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054", "No index signature with a parameter of type '{0}' was found on type '{1}'."),
+ _0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type: diag(7055, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055", "'{0}', which lacks return-type annotation, implicitly has an '{1}' yield type."),
+ The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed: diag(7056, ts.DiagnosticCategory.Error, "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056", "The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed."),
+ yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation: diag(7057, ts.DiagnosticCategory.Error, "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057", "'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation."),
+ If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"),
+ This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."),
+ This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."),
+ A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."),
+ JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."),
+ You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
+ You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."),
+ import_can_only_be_used_in_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."),
+ export_can_only_be_used_in_TypeScript_files: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_TypeScript_files_8003", "'export =' can only be used in TypeScript files."),
+ Type_parameter_declarations_can_only_be_used_in_TypeScript_files: diag(8004, ts.DiagnosticCategory.Error, "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004", "Type parameter declarations can only be used in TypeScript files."),
+ implements_clauses_can_only_be_used_in_TypeScript_files: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_TypeScript_files_8005", "'implements' clauses can only be used in TypeScript files."),
+ _0_declarations_can_only_be_used_in_TypeScript_files: diag(8006, ts.DiagnosticCategory.Error, "_0_declarations_can_only_be_used_in_TypeScript_files_8006", "'{0}' declarations can only be used in TypeScript files."),
+ Type_aliases_can_only_be_used_in_TypeScript_files: diag(8008, ts.DiagnosticCategory.Error, "Type_aliases_can_only_be_used_in_TypeScript_files_8008", "Type aliases can only be used in TypeScript files."),
+ The_0_modifier_can_only_be_used_in_TypeScript_files: diag(8009, ts.DiagnosticCategory.Error, "The_0_modifier_can_only_be_used_in_TypeScript_files_8009", "The '{0}' modifier can only be used in TypeScript files."),
+ Type_annotations_can_only_be_used_in_TypeScript_files: diag(8010, ts.DiagnosticCategory.Error, "Type_annotations_can_only_be_used_in_TypeScript_files_8010", "Type annotations can only be used in TypeScript files."),
+ Type_arguments_can_only_be_used_in_TypeScript_files: diag(8011, ts.DiagnosticCategory.Error, "Type_arguments_can_only_be_used_in_TypeScript_files_8011", "Type arguments can only be used in TypeScript files."),
+ Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, ts.DiagnosticCategory.Error, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."),
+ Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, ts.DiagnosticCategory.Error, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."),
+ Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, ts.DiagnosticCategory.Error, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."),
+ Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."),
+ Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."),
+ Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
+ JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."),
+ JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."),
+ JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."),
+ JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."),
+ JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."),
+ Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."),
+ Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."),
+ Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."),
+ JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."),
+ JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."),
+ The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."),
+ You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."),
+ Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."),
+ A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."),
+ The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."),
+ Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."),
+ Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."),
+ JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."),
+ JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."),
+ Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."),
+ Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."),
+ A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."),
+ An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
+ A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
+ JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."),
+ super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."),
+ Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
+ super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."),
+ _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"),
+ Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."),
+ JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
+ Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
+ The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option: diag(17016, ts.DiagnosticCategory.Error, "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016", "The 'jsxFragmentFactory' compiler option must be provided to use JSX fragments with the 'jsxFactory' compiler option."),
+ An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments: diag(17017, ts.DiagnosticCategory.Error, "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017", "An @jsxFrag pragma is required when using an @jsx pragma with JSX fragments."),
+ Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"),
+ Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
+ The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
+ No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
+ require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."),
+ This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."),
+ await_has_no_effect_on_the_type_of_this_expression: diag(80007, ts.DiagnosticCategory.Suggestion, "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."),
+ Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, ts.DiagnosticCategory.Suggestion, "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."),
+ Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
+ Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
+ Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
+ Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
+ Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
+ Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
+ Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
+ Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
+ Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
+ Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
+ Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
+ Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
+ Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
+ Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
+ Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
+ Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
+ Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
+ Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
+ Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
+ Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
+ Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
+ Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
+ Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
+ Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"),
+ Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
+ Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
+ Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
+ Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
+ Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
+ Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
+ Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
+ Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
+ Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"),
+ Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"),
+ Declare_private_method_0: diag(90038, ts.DiagnosticCategory.Message, "Declare_private_method_0_90038", "Declare private method '{0}'"),
+ Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"),
+ Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"),
+ Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
+ Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"),
+ Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
+ Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"),
+ Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
+ Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
+ Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
+ Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
+ Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
+ Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
+ Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
+ Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
+ Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
+ Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
+ Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
+ Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
+ Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
+ Convert_all_type_literals_to_mapped_type: diag(95021, ts.DiagnosticCategory.Message, "Convert_all_type_literals_to_mapped_type_95021", "Convert all type literals to mapped type"),
+ Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
+ Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
+ Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
+ Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"),
+ Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
+ Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
+ Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"),
+ Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"),
+ Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"),
+ Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"),
+ Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
+ Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
+ Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
+ Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
+ Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"),
+ Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"),
+ Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
+ Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
+ Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
+ Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
+ Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"),
+ Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
+ Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
+ Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
+ Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
+ Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
+ Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
+ Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
+ Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
+ Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
+ Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
+ Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
+ Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
+ Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
+ Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
+ Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"),
+ Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
+ Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
+ Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
+ Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
+ Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
+ Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
+ Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
+ Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
+ Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
+ Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
+ Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
+ Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
+ Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
+ Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
+ Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
+ Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
+ Infer_this_type_of_0_from_usage: diag(95080, ts.DiagnosticCategory.Message, "Infer_this_type_of_0_from_usage_95080", "Infer 'this' type of '{0}' from usage"),
+ Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
+ Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
+ Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
+ Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
+ Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
+ Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
+ Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
+ Enable_the_jsx_flag_in_your_configuration_file: diag(95088, ts.DiagnosticCategory.Message, "Enable_the_jsx_flag_in_your_configuration_file_95088", "Enable the '--jsx' flag in your configuration file"),
+ Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
+ Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
+ Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
+ Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
+ Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
+ Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
+ Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"),
+ Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
+ Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"),
+ Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"),
+ Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"),
+ Convert_invalid_character_to_its_html_entity_code: diag(95100, ts.DiagnosticCategory.Message, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"),
+ Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, ts.DiagnosticCategory.Message, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"),
+ Convert_function_expression_0_to_arrow_function: diag(95105, ts.DiagnosticCategory.Message, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"),
+ Convert_function_declaration_0_to_arrow_function: diag(95106, ts.DiagnosticCategory.Message, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"),
+ Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
+ Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"),
+ Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"),
+ Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"),
+ Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
+ Remove_braces_from_arrow_function_body: diag(95112, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"),
+ Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"),
+ Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
+ Remove_braces_from_all_arrow_function_bodies_with_relevant_issues: diag(95115, ts.DiagnosticCategory.Message, "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115", "Remove braces from all arrow function bodies with relevant issues"),
+ Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
+ Move_labeled_tuple_element_modifiers_to_labels: diag(95117, ts.DiagnosticCategory.Message, "Move_labeled_tuple_element_modifiers_to_labels_95117", "Move labeled tuple element modifiers to labels"),
+ Convert_overload_list_to_single_signature: diag(95118, ts.DiagnosticCategory.Message, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"),
+ Generate_get_and_set_accessors_for_all_overriding_properties: diag(95119, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_for_all_overriding_properties_95119", "Generate 'get' and 'set' accessors for all overriding properties"),
+ Wrap_in_JSX_fragment: diag(95120, ts.DiagnosticCategory.Message, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"),
+ Wrap_all_unparented_JSX_in_JSX_fragment: diag(95121, ts.DiagnosticCategory.Message, "Wrap_all_unparented_JSX_in_JSX_fragment_95121", "Wrap all unparented JSX in JSX fragment"),
+ Convert_arrow_function_or_function_expression: diag(95122, ts.DiagnosticCategory.Message, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"),
+ Convert_to_anonymous_function: diag(95123, ts.DiagnosticCategory.Message, "Convert_to_anonymous_function_95123", "Convert to anonymous function"),
+ Convert_to_named_function: diag(95124, ts.DiagnosticCategory.Message, "Convert_to_named_function_95124", "Convert to named function"),
+ Convert_to_arrow_function: diag(95125, ts.DiagnosticCategory.Message, "Convert_to_arrow_function_95125", "Convert to arrow function"),
+ Remove_parentheses: diag(95126, ts.DiagnosticCategory.Message, "Remove_parentheses_95126", "Remove parentheses"),
+ Could_not_find_a_containing_arrow_function: diag(95127, ts.DiagnosticCategory.Message, "Could_not_find_a_containing_arrow_function_95127", "Could not find a containing arrow function"),
+ Containing_function_is_not_an_arrow_function: diag(95128, ts.DiagnosticCategory.Message, "Containing_function_is_not_an_arrow_function_95128", "Containing function is not an arrow function"),
+ Could_not_find_export_statement: diag(95129, ts.DiagnosticCategory.Message, "Could_not_find_export_statement_95129", "Could not find export statement"),
+ This_file_already_has_a_default_export: diag(95130, ts.DiagnosticCategory.Message, "This_file_already_has_a_default_export_95130", "This file already has a default export"),
+ Could_not_find_import_clause: diag(95131, ts.DiagnosticCategory.Message, "Could_not_find_import_clause_95131", "Could not find import clause"),
+ Could_not_find_namespace_import_or_named_imports: diag(95132, ts.DiagnosticCategory.Message, "Could_not_find_namespace_import_or_named_imports_95132", "Could not find namespace import or named imports"),
+ Selection_is_not_a_valid_type_node: diag(95133, ts.DiagnosticCategory.Message, "Selection_is_not_a_valid_type_node_95133", "Selection is not a valid type node"),
+ No_type_could_be_extracted_from_this_type_node: diag(95134, ts.DiagnosticCategory.Message, "No_type_could_be_extracted_from_this_type_node_95134", "No type could be extracted from this type node"),
+ Could_not_find_property_for_which_to_generate_accessor: diag(95135, ts.DiagnosticCategory.Message, "Could_not_find_property_for_which_to_generate_accessor_95135", "Could not find property for which to generate accessor"),
+ Name_is_not_valid: diag(95136, ts.DiagnosticCategory.Message, "Name_is_not_valid_95136", "Name is not valid"),
+ Can_only_convert_property_with_modifier: diag(95137, ts.DiagnosticCategory.Message, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"),
+ Switch_each_misused_0_to_1: diag(95138, ts.DiagnosticCategory.Message, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"),
+ Convert_to_optional_chain_expression: diag(95139, ts.DiagnosticCategory.Message, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"),
+ Could_not_find_convertible_access_expression: diag(95140, ts.DiagnosticCategory.Message, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"),
+ Could_not_find_matching_access_expressions: diag(95141, ts.DiagnosticCategory.Message, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"),
+ Can_only_convert_logical_AND_access_chains: diag(95142, ts.DiagnosticCategory.Message, "Can_only_convert_logical_AND_access_chains_95142", "Can only convert logical AND access chains"),
+ Add_void_to_Promise_resolved_without_a_value: diag(95143, ts.DiagnosticCategory.Message, "Add_void_to_Promise_resolved_without_a_value_95143", "Add 'void' to Promise resolved without a value"),
+ Add_void_to_all_Promises_resolved_without_a_value: diag(95144, ts.DiagnosticCategory.Message, "Add_void_to_all_Promises_resolved_without_a_value_95144", "Add 'void' to all Promises resolved without a value"),
+ Use_element_access_for_0: diag(95145, ts.DiagnosticCategory.Message, "Use_element_access_for_0_95145", "Use element access for '{0}'"),
+ Use_element_access_for_all_undeclared_properties: diag(95146, ts.DiagnosticCategory.Message, "Use_element_access_for_all_undeclared_properties_95146", "Use element access for all undeclared properties."),
+ Delete_all_unused_imports: diag(95147, ts.DiagnosticCategory.Message, "Delete_all_unused_imports_95147", "Delete all unused imports"),
+ Infer_function_return_type: diag(95148, ts.DiagnosticCategory.Message, "Infer_function_return_type_95148", "Infer function return type"),
+ Return_type_must_be_inferred_from_a_function: diag(95149, ts.DiagnosticCategory.Message, "Return_type_must_be_inferred_from_a_function_95149", "Return type must be inferred from a function"),
+ Could_not_determine_function_return_type: diag(95150, ts.DiagnosticCategory.Message, "Could_not_determine_function_return_type_95150", "Could not determine function return type"),
+ Could_not_convert_to_arrow_function: diag(95151, ts.DiagnosticCategory.Message, "Could_not_convert_to_arrow_function_95151", "Could not convert to arrow function"),
+ Could_not_convert_to_named_function: diag(95152, ts.DiagnosticCategory.Message, "Could_not_convert_to_named_function_95152", "Could not convert to named function"),
+ Could_not_convert_to_anonymous_function: diag(95153, ts.DiagnosticCategory.Message, "Could_not_convert_to_anonymous_function_95153", "Could not convert to anonymous function"),
+ Can_only_convert_string_concatenation: diag(95154, ts.DiagnosticCategory.Message, "Can_only_convert_string_concatenation_95154", "Can only convert string concatenation"),
+ Selection_is_not_a_valid_statement_or_statements: diag(95155, ts.DiagnosticCategory.Message, "Selection_is_not_a_valid_statement_or_statements_95155", "Selection is not a valid statement or statements"),
+ Add_missing_function_declaration_0: diag(95156, ts.DiagnosticCategory.Message, "Add_missing_function_declaration_0_95156", "Add missing function declaration '{0}'"),
+ Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"),
+ Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."),
+ Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."),
+ Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"),
+ Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"),
+ Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"),
+ Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"),
+ Can_only_convert_named_export: diag(95164, ts.DiagnosticCategory.Message, "Can_only_convert_named_export_95164", "Can only convert named export"),
+ Add_missing_properties: diag(95165, ts.DiagnosticCategory.Message, "Add_missing_properties_95165", "Add missing properties"),
+ Add_all_missing_properties: diag(95166, ts.DiagnosticCategory.Message, "Add_all_missing_properties_95166", "Add all missing properties"),
+ Add_missing_attributes: diag(95167, ts.DiagnosticCategory.Message, "Add_missing_attributes_95167", "Add missing attributes"),
+ Add_all_missing_attributes: diag(95168, ts.DiagnosticCategory.Message, "Add_all_missing_attributes_95168", "Add all missing attributes"),
+ Add_undefined_to_optional_property_type: diag(95169, ts.DiagnosticCategory.Message, "Add_undefined_to_optional_property_type_95169", "Add 'undefined' to optional property type"),
+ No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."),
+ Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."),
+ JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"),
+ Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters."),
+ An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."),
+ The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."),
+ constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
+ Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier: diag(18013, ts.DiagnosticCategory.Error, "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013", "Property '{0}' is not accessible outside class '{1}' because it has a private identifier."),
+ The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling: diag(18014, ts.DiagnosticCategory.Error, "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014", "The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling."),
+ Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2: diag(18015, ts.DiagnosticCategory.Error, "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015", "Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'."),
+ Private_identifiers_are_not_allowed_outside_class_bodies: diag(18016, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_outside_class_bodies_18016", "Private identifiers are not allowed outside class bodies."),
+ The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"),
+ The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"),
+ _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."),
+ An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."),
+ can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."),
+ Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."),
+ Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."),
+ Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."),
+ An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."),
+ The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."),
+ The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."),
+ Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."),
+ Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."),
+ Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."),
+ Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."),
+ Await_expression_cannot_be_used_inside_a_class_static_block: diag(18037, ts.DiagnosticCategory.Error, "Await_expression_cannot_be_used_inside_a_class_static_block_18037", "Await expression cannot be used inside a class static block."),
+ For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."),
+ Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."),
+ A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."),
+ };
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ var _a;
+ /* @internal */
+ function tokenIsIdentifierOrKeyword(token) {
+ return token >= 79 /* Identifier */;
+ }
+ ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
+ /* @internal */
+ function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
+ return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
+ }
+ ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
+ /** @internal */
+ ts.textToKeywordObj = (_a = {
+ abstract: 126 /* AbstractKeyword */,
+ any: 130 /* AnyKeyword */,
+ as: 127 /* AsKeyword */,
+ asserts: 128 /* AssertsKeyword */,
+ assert: 129 /* AssertKeyword */,
+ bigint: 157 /* BigIntKeyword */,
+ boolean: 133 /* BooleanKeyword */,
+ break: 81 /* BreakKeyword */,
+ case: 82 /* CaseKeyword */,
+ catch: 83 /* CatchKeyword */,
+ class: 84 /* ClassKeyword */,
+ continue: 86 /* ContinueKeyword */,
+ const: 85 /* ConstKeyword */
+ },
+ _a["" + "constructor"] = 134 /* ConstructorKeyword */,
+ _a.debugger = 87 /* DebuggerKeyword */,
+ _a.declare = 135 /* DeclareKeyword */,
+ _a.default = 88 /* DefaultKeyword */,
+ _a.delete = 89 /* DeleteKeyword */,
+ _a.do = 90 /* DoKeyword */,
+ _a.else = 91 /* ElseKeyword */,
+ _a.enum = 92 /* EnumKeyword */,
+ _a.export = 93 /* ExportKeyword */,
+ _a.extends = 94 /* ExtendsKeyword */,
+ _a.false = 95 /* FalseKeyword */,
+ _a.finally = 96 /* FinallyKeyword */,
+ _a.for = 97 /* ForKeyword */,
+ _a.from = 155 /* FromKeyword */,
+ _a.function = 98 /* FunctionKeyword */,
+ _a.get = 136 /* GetKeyword */,
+ _a.if = 99 /* IfKeyword */,
+ _a.implements = 117 /* ImplementsKeyword */,
+ _a.import = 100 /* ImportKeyword */,
+ _a.in = 101 /* InKeyword */,
+ _a.infer = 137 /* InferKeyword */,
+ _a.instanceof = 102 /* InstanceOfKeyword */,
+ _a.interface = 118 /* InterfaceKeyword */,
+ _a.intrinsic = 138 /* IntrinsicKeyword */,
+ _a.is = 139 /* IsKeyword */,
+ _a.keyof = 140 /* KeyOfKeyword */,
+ _a.let = 119 /* LetKeyword */,
+ _a.module = 141 /* ModuleKeyword */,
+ _a.namespace = 142 /* NamespaceKeyword */,
+ _a.never = 143 /* NeverKeyword */,
+ _a.new = 103 /* NewKeyword */,
+ _a.null = 104 /* NullKeyword */,
+ _a.number = 146 /* NumberKeyword */,
+ _a.object = 147 /* ObjectKeyword */,
+ _a.package = 120 /* PackageKeyword */,
+ _a.private = 121 /* PrivateKeyword */,
+ _a.protected = 122 /* ProtectedKeyword */,
+ _a.public = 123 /* PublicKeyword */,
+ _a.override = 158 /* OverrideKeyword */,
+ _a.readonly = 144 /* ReadonlyKeyword */,
+ _a.require = 145 /* RequireKeyword */,
+ _a.global = 156 /* GlobalKeyword */,
+ _a.return = 105 /* ReturnKeyword */,
+ _a.set = 148 /* SetKeyword */,
+ _a.static = 124 /* StaticKeyword */,
+ _a.string = 149 /* StringKeyword */,
+ _a.super = 106 /* SuperKeyword */,
+ _a.switch = 107 /* SwitchKeyword */,
+ _a.symbol = 150 /* SymbolKeyword */,
+ _a.this = 108 /* ThisKeyword */,
+ _a.throw = 109 /* ThrowKeyword */,
+ _a.true = 110 /* TrueKeyword */,
+ _a.try = 111 /* TryKeyword */,
+ _a.type = 151 /* TypeKeyword */,
+ _a.typeof = 112 /* TypeOfKeyword */,
+ _a.undefined = 152 /* UndefinedKeyword */,
+ _a.unique = 153 /* UniqueKeyword */,
+ _a.unknown = 154 /* UnknownKeyword */,
+ _a.var = 113 /* VarKeyword */,
+ _a.void = 114 /* VoidKeyword */,
+ _a.while = 115 /* WhileKeyword */,
+ _a.with = 116 /* WithKeyword */,
+ _a.yield = 125 /* YieldKeyword */,
+ _a.async = 131 /* AsyncKeyword */,
+ _a.await = 132 /* AwaitKeyword */,
+ _a.of = 159 /* OfKeyword */,
+ _a);
+ var textToKeyword = new ts.Map(ts.getEntries(ts.textToKeywordObj));
+ var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, ts.textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, "": 30 /* LessThanSlashToken */, ">>": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 63 /* EqualsToken */, "+=": 64 /* PlusEqualsToken */, "-=": 65 /* MinusEqualsToken */, "*=": 66 /* AsteriskEqualsToken */, "**=": 67 /* AsteriskAsteriskEqualsToken */, "/=": 68 /* SlashEqualsToken */, "%=": 69 /* PercentEqualsToken */, "<<=": 70 /* LessThanLessThanEqualsToken */, ">>=": 71 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 73 /* AmpersandEqualsToken */, "|=": 74 /* BarEqualsToken */, "^=": 78 /* CaretEqualsToken */, "||=": 75 /* BarBarEqualsToken */, "&&=": 76 /* AmpersandAmpersandEqualsToken */, "??=": 77 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "#": 62 /* HashToken */, "`": 61 /* BacktickToken */ })));
+ /*
+ 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,];
+ /**
+ * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
+ * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
+ * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
+ * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
+ */
+ var unicodeESNextIdentifierStart = [65, 90, 97, 122, 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, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 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, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 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, 2809, 2809, 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, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 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, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 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, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 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, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 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, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 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, 43824, 43866, 43868, 43879, 43888, 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, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101];
+ var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 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, 2556, 2556, 2558, 2558, 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, 2809, 2815, 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, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 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, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 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, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 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, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 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, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 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, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 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, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 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, 65071, 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, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999];
+ /**
+ * Test for whether a single line comment with leading whitespace trimmed's text contains a directive.
+ */
+ var commentDirectiveRegExSingleLine = /^\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
+ /**
+ * Test for whether a multi-line comment with leading whitespace trimmed's last line contains a directive.
+ */
+ var commentDirectiveRegExMultiLine = /^(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
+ function lookupInUnicodeMap(code, map) {
+ // Bail out quickly if it couldn't possibly be in the map.
+ if (code < map[0]) {
+ return false;
}
- function parseCatchClause() {
- var result = createNode(280 /* CatchClause */);
- parseExpected(79 /* CatchKeyword */);
- if (parseOptional(20 /* OpenParenToken */)) {
- result.variableDeclaration = parseVariableDeclaration();
- parseExpected(21 /* CloseParenToken */);
- }
- else {
- // Keep shape of node to avoid degrading performance.
- result.variableDeclaration = undefined;
+ // 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;
}
- result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
- return finishNode(result);
- }
- function parseDebuggerStatement() {
- var node = createNode(241 /* DebuggerStatement */);
- parseExpected(83 /* DebuggerKeyword */);
- parseSemicolon();
- return finishNode(node);
- }
- function parseExpressionOrLabeledStatement() {
- // 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(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
- var expression = allowInAnd(parseExpression);
- if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
- node.kind = 238 /* LabeledStatement */;
- node.label = expression;
- node.statement = parseStatement();
+ if (code < map[mid]) {
+ hi = mid;
}
else {
- node.kind = 226 /* ExpressionStatement */;
- node.expression = expression;
- parseSemicolon();
- }
- return finishNode(node);
- }
- function nextTokenIsIdentifierOrKeywordOnSameLine() {
- nextToken();
- return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
- }
- function nextTokenIsClassKeywordOnSameLine() {
- nextToken();
- return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
- }
- function nextTokenIsFunctionKeywordOnSameLine() {
- nextToken();
- return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
- }
- function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
- nextToken();
- return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
- }
- function isDeclaration() {
- while (true) {
- switch (token()) {
- case 109 /* VarKeyword */:
- case 115 /* LetKeyword */:
- case 81 /* ConstKeyword */:
- case 94 /* FunctionKeyword */:
- case 80 /* ClassKeyword */:
- case 88 /* EnumKeyword */:
- return true;
- // '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 114 /* InterfaceKeyword */:
- case 145 /* TypeKeyword */:
- return nextTokenIsIdentifierOnSameLine();
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- return nextTokenIsIdentifierOrStringLiteralOnSameLine();
- case 122 /* AbstractKeyword */:
- case 126 /* AsyncKeyword */:
- case 130 /* DeclareKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 119 /* PublicKeyword */:
- case 138 /* ReadonlyKeyword */:
- nextToken();
- // ASI takes effect for this modifier.
- if (scanner.hasPrecedingLineBreak()) {
- return false;
- }
- continue;
- case 150 /* GlobalKeyword */:
- nextToken();
- return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
- case 96 /* ImportKeyword */:
- nextToken();
- return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
- token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
- case 89 /* ExportKeyword */:
- var currentToken_1 = nextToken();
- if (currentToken_1 === 145 /* TypeKeyword */) {
- currentToken_1 = lookAhead(nextToken);
- }
- if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
- currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
- currentToken_1 === 123 /* AsKeyword */) {
- return true;
- }
- continue;
- case 120 /* StaticKeyword */:
- nextToken();
- continue;
- default:
- return false;
- }
- }
- }
- function isStartOfDeclaration() {
- return lookAhead(isDeclaration);
- }
- function isStartOfStatement() {
- switch (token()) {
- case 59 /* AtToken */:
- case 26 /* SemicolonToken */:
- case 18 /* OpenBraceToken */:
- case 109 /* VarKeyword */:
- case 115 /* LetKeyword */:
- case 94 /* FunctionKeyword */:
- case 80 /* ClassKeyword */:
- case 88 /* EnumKeyword */:
- case 95 /* IfKeyword */:
- case 86 /* DoKeyword */:
- case 111 /* WhileKeyword */:
- case 93 /* ForKeyword */:
- case 82 /* ContinueKeyword */:
- case 77 /* BreakKeyword */:
- case 101 /* ReturnKeyword */:
- case 112 /* WithKeyword */:
- case 103 /* SwitchKeyword */:
- case 105 /* ThrowKeyword */:
- case 107 /* TryKeyword */:
- case 83 /* 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.
- // falls through
- case 79 /* CatchKeyword */:
- case 92 /* FinallyKeyword */:
- return true;
- case 96 /* ImportKeyword */:
- return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
- case 81 /* ConstKeyword */:
- case 89 /* ExportKeyword */:
- return isStartOfDeclaration();
- case 126 /* AsyncKeyword */:
- case 130 /* DeclareKeyword */:
- case 114 /* InterfaceKeyword */:
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- case 145 /* TypeKeyword */:
- case 150 /* GlobalKeyword */:
- // When these don't start a declaration, they're an identifier in an expression statement
- return true;
- case 119 /* PublicKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 120 /* StaticKeyword */:
- case 138 /* 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();
+ lo = mid + 2;
}
}
- function nextTokenIsIdentifierOrStartOfDestructuring() {
- nextToken();
- return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* 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 26 /* SemicolonToken */:
- return parseEmptyStatement();
- case 18 /* OpenBraceToken */:
- return parseBlock(/*ignoreMissingOpenBrace*/ false);
- case 109 /* VarKeyword */:
- return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
- case 115 /* LetKeyword */:
- if (isLetDeclaration()) {
- return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
+ return false;
+ }
+ /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
+ return languageVersion >= 2 /* ES2015 */ ?
+ lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
+ languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
+ lookupInUnicodeMap(code, unicodeES3IdentifierStart);
+ }
+ ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
+ function isUnicodeIdentifierPart(code, languageVersion) {
+ return languageVersion >= 2 /* ES2015 */ ?
+ lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
+ languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
+ lookupInUnicodeMap(code, unicodeES3IdentifierPart);
+ }
+ function makeReverseMap(source) {
+ var result = [];
+ source.forEach(function (value, name) {
+ result[value] = name;
+ });
+ return result;
+ }
+ var tokenStrings = makeReverseMap(textToToken);
+ function tokenToString(t) {
+ 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;
+ var lineStart = 0;
+ while (pos < text.length) {
+ var ch = text.charCodeAt(pos);
+ pos++;
+ switch (ch) {
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos) === 10 /* lineFeed */) {
+ pos++;
}
- break;
- case 94 /* FunctionKeyword */:
- return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
- case 80 /* ClassKeyword */:
- return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
- case 95 /* IfKeyword */:
- return parseIfStatement();
- case 86 /* DoKeyword */:
- return parseDoStatement();
- case 111 /* WhileKeyword */:
- return parseWhileStatement();
- case 93 /* ForKeyword */:
- return parseForOrForInOrForOfStatement();
- case 82 /* ContinueKeyword */:
- return parseBreakOrContinueStatement(233 /* ContinueStatement */);
- case 77 /* BreakKeyword */:
- return parseBreakOrContinueStatement(234 /* BreakStatement */);
- case 101 /* ReturnKeyword */:
- return parseReturnStatement();
- case 112 /* WithKeyword */:
- return parseWithStatement();
- case 103 /* SwitchKeyword */:
- return parseSwitchStatement();
- case 105 /* ThrowKeyword */:
- return parseThrowStatement();
- case 107 /* TryKeyword */:
- // Include 'catch' and 'finally' for error recovery.
// falls through
- case 79 /* CatchKeyword */:
- case 92 /* FinallyKeyword */:
- return parseTryStatement();
- case 83 /* DebuggerKeyword */:
- return parseDebuggerStatement();
- case 59 /* AtToken */:
- return parseDeclaration();
- case 126 /* AsyncKeyword */:
- case 114 /* InterfaceKeyword */:
- case 145 /* TypeKeyword */:
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- case 130 /* DeclareKeyword */:
- case 81 /* ConstKeyword */:
- case 88 /* EnumKeyword */:
- case 89 /* ExportKeyword */:
- case 96 /* ImportKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 119 /* PublicKeyword */:
- case 122 /* AbstractKeyword */:
- case 120 /* StaticKeyword */:
- case 138 /* ReadonlyKeyword */:
- case 150 /* GlobalKeyword */:
- if (isStartOfDeclaration()) {
- return parseDeclaration();
- }
+ case 10 /* lineFeed */:
+ result.push(lineStart);
+ lineStart = pos;
break;
- }
- return parseExpressionOrLabeledStatement();
- }
- function isDeclareModifier(modifier) {
- return modifier.kind === 130 /* DeclareKeyword */;
- }
- function parseDeclaration() {
- var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
- // `parseListElement` attempted to get the reused node at this position,
- // but the ambient context flag was not yet set, so the node appeared
- // not reusable in that context.
- var isAmbient = ts.some(modifiers, isDeclareModifier);
- if (isAmbient) {
- var node_3 = tryReuseAmbientDeclaration();
- if (node_3) {
- return node_3;
- }
- }
- var node = createNodeWithJSDoc(0 /* Unknown */);
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers();
- if (isAmbient) {
- for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
- var m = _a[_i];
- m.flags |= 8388608 /* Ambient */;
- }
- return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
- }
- else {
- return parseDeclarationWorker(node);
- }
- }
- function tryReuseAmbientDeclaration() {
- return doInsideOfContext(8388608 /* Ambient */, function () {
- var node = currentNode(parsingContext);
- if (node) {
- return consumeNode(node);
- }
- });
- }
- function parseDeclarationWorker(node) {
- switch (token()) {
- case 109 /* VarKeyword */:
- case 115 /* LetKeyword */:
- case 81 /* ConstKeyword */:
- return parseVariableStatement(node);
- case 94 /* FunctionKeyword */:
- return parseFunctionDeclaration(node);
- case 80 /* ClassKeyword */:
- return parseClassDeclaration(node);
- case 114 /* InterfaceKeyword */:
- return parseInterfaceDeclaration(node);
- case 145 /* TypeKeyword */:
- return parseTypeAliasDeclaration(node);
- case 88 /* EnumKeyword */:
- return parseEnumDeclaration(node);
- case 150 /* GlobalKeyword */:
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- return parseModuleDeclaration(node);
- case 96 /* ImportKeyword */:
- return parseImportDeclarationOrImportEqualsDeclaration(node);
- case 89 /* ExportKeyword */:
- nextToken();
- switch (token()) {
- case 84 /* DefaultKeyword */:
- case 62 /* EqualsToken */:
- return parseExportAssignment(node);
- case 123 /* AsKeyword */:
- return parseNamespaceExportDeclaration(node);
- default:
- return parseExportDeclaration(node);
- }
default:
- if (node.decorators || node.modifiers) {
- // 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(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
- missing.pos = node.pos;
- missing.decorators = node.decorators;
- missing.modifiers = node.modifiers;
- return finishNode(missing);
+ if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
+ result.push(lineStart);
+ lineStart = pos;
}
- return undefined; // TODO: GH#18217
- }
- }
- function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
- nextToken();
- return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
- }
- function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
- if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
- parseSemicolon();
- return;
- }
- return parseFunctionBlock(flags, diagnosticMessage);
- }
- // DECLARATIONS
- function parseArrayBindingElement() {
- if (token() === 27 /* CommaToken */) {
- return createNode(215 /* OmittedExpression */);
+ break;
}
- var node = createNode(191 /* BindingElement */);
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- node.name = parseIdentifierOrPattern();
- node.initializer = parseInitializer();
- return finishNode(node);
}
- function parseObjectBindingElement() {
- var node = createNode(191 /* BindingElement */);
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- var tokenIsIdentifier = isIdentifier();
- var propertyName = parsePropertyName();
- if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
- node.name = propertyName;
+ result.push(lineStart);
+ return result;
+ }
+ ts.computeLineStarts = computeLineStarts;
+ function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
+ return sourceFile.getPositionOfLineAndCharacter ?
+ sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
+ computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
+ }
+ ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
+ /* @internal */
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
+ if (line < 0 || line >= lineStarts.length) {
+ if (allowEdits) {
+ // Clamp line to nearest allowable value
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
}
else {
- parseExpected(58 /* ColonToken */);
- node.propertyName = propertyName;
- node.name = parseIdentifierOrPattern();
+ ts.Debug.fail("Bad line number. Line: ".concat(line, ", lineStarts.length: ").concat(lineStarts.length, " , line map is correct? ").concat(debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
}
- node.initializer = parseInitializer();
- return finishNode(node);
}
- function parseObjectBindingPattern() {
- var node = createNode(189 /* ObjectBindingPattern */);
- parseExpected(18 /* OpenBraceToken */);
- node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
- parseExpected(19 /* CloseBraceToken */);
- return finishNode(node);
+ var res = lineStarts[line] + character;
+ if (allowEdits) {
+ // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
+ // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
+ // apply them to the computed position to improve accuracy
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
}
- function parseArrayBindingPattern() {
- var node = createNode(190 /* ArrayBindingPattern */);
- parseExpected(22 /* OpenBracketToken */);
- node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
- parseExpected(23 /* CloseBracketToken */);
- return finishNode(node);
+ if (line < lineStarts.length - 1) {
+ ts.Debug.assert(res < lineStarts[line + 1]);
}
- function isIdentifierOrPrivateIdentifierOrPattern() {
- return token() === 18 /* OpenBraceToken */
- || token() === 22 /* OpenBracketToken */
- || token() === 76 /* PrivateIdentifier */
- || isIdentifier();
+ else if (debugText !== undefined) {
+ ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
}
- function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
- if (token() === 22 /* OpenBracketToken */) {
- return parseArrayBindingPattern();
- }
- if (token() === 18 /* OpenBraceToken */) {
- return parseObjectBindingPattern();
- }
- return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
+ return res;
+ }
+ ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
+ /* @internal */
+ function getLineStarts(sourceFile) {
+ return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
+ }
+ ts.getLineStarts = getLineStarts;
+ /* @internal */
+ function computeLineAndCharacterOfPosition(lineStarts, position) {
+ var lineNumber = computeLineOfPosition(lineStarts, position);
+ return {
+ line: lineNumber,
+ character: position - lineStarts[lineNumber]
+ };
+ }
+ ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
+ /**
+ * @internal
+ * We assume the first line starts at position 0 and 'position' is non-negative.
+ */
+ function computeLineOfPosition(lineStarts, position, lowerBound) {
+ var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
+ 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");
}
- function parseVariableDeclarationAllowExclamation() {
- return parseVariableDeclaration(/*allowExclamation*/ true);
+ return lineNumber;
+ }
+ ts.computeLineOfPosition = computeLineOfPosition;
+ /** @internal */
+ function getLinesBetweenPositions(sourceFile, pos1, pos2) {
+ if (pos1 === pos2)
+ return 0;
+ var lineStarts = getLineStarts(sourceFile);
+ var lower = Math.min(pos1, pos2);
+ var isNegative = lower === pos2;
+ var upper = isNegative ? pos1 : pos2;
+ var lowerLine = computeLineOfPosition(lineStarts, lower);
+ var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
+ return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
+ }
+ ts.getLinesBetweenPositions = getLinesBetweenPositions;
+ function getLineAndCharacterOfPosition(sourceFile, position) {
+ return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
+ }
+ ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
+ function isWhiteSpaceLike(ch) {
+ return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
+ }
+ ts.isWhiteSpaceLike = isWhiteSpaceLike;
+ /** Does not include line breaks. For that, see isWhiteSpaceLike. */
+ function isWhiteSpaceSingleLine(ch) {
+ // 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) {
+ // 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 /* _0 */ && ch <= 57 /* _9 */;
+ }
+ function isHexDigit(ch) {
+ return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
+ }
+ function isCodePoint(code) {
+ return code <= 0x10FFFF;
+ }
+ /* @internal */
+ function isOctalDigit(ch) {
+ 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 /* carriageReturn */:
+ case 10 /* lineFeed */:
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
+ case 47 /* slash */:
+ // starts of normal trivia
+ // falls through
+ case 60 /* lessThan */:
+ case 124 /* bar */:
+ case 61 /* equals */:
+ case 62 /* greaterThan */:
+ // Starts of conflict marker trivia
+ return true;
+ case 35 /* hash */:
+ // Only if its the beginning can we have #! trivia
+ return pos === 0;
+ default:
+ return ch > 127 /* maxAsciiCharacter */;
}
- function parseVariableDeclaration(allowExclamation) {
- var node = createNode(242 /* VariableDeclaration */);
- node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
- if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
- token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
- node.exclamationToken = parseTokenNode();
- }
- node.type = parseTypeAnnotation();
- if (!isInOrOfKeyword(token())) {
- node.initializer = parseInitializer();
- }
- return finishNode(node);
+ }
+ ts.couldStartTrivia = couldStartTrivia;
+ /* @internal */
+ function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) {
+ if (ts.positionIsSynthesized(pos)) {
+ return pos;
}
- function parseVariableDeclarationList(inForStatementInitializer) {
- var node = createNode(243 /* VariableDeclarationList */);
- switch (token()) {
- case 109 /* VarKeyword */:
+ var canConsumeStar = false;
+ // Keep in sync with couldStartTrivia
+ while (true) {
+ var ch = text.charCodeAt(pos);
+ switch (ch) {
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
+ pos++;
+ }
+ // falls through
+ case 10 /* lineFeed */:
+ pos++;
+ if (stopAfterLineBreak) {
+ return pos;
+ }
+ canConsumeStar = !!inJSDoc;
+ continue;
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
+ pos++;
+ continue;
+ case 47 /* slash */:
+ if (stopAtComments) {
+ break;
+ }
+ if (text.charCodeAt(pos + 1) === 47 /* slash */) {
+ pos += 2;
+ while (pos < text.length) {
+ if (isLineBreak(text.charCodeAt(pos))) {
+ break;
+ }
+ pos++;
+ }
+ canConsumeStar = false;
+ continue;
+ }
+ if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
+ pos += 2;
+ while (pos < text.length) {
+ if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
+ pos += 2;
+ break;
+ }
+ pos++;
+ }
+ canConsumeStar = false;
+ continue;
+ }
+ break;
+ case 60 /* lessThan */:
+ case 124 /* bar */:
+ case 61 /* equals */:
+ case 62 /* greaterThan */:
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos);
+ canConsumeStar = false;
+ continue;
+ }
break;
- case 115 /* LetKeyword */:
- node.flags |= 1 /* Let */;
+ case 35 /* hash */:
+ if (pos === 0 && isShebangTrivia(text, pos)) {
+ pos = scanShebangTrivia(text, pos);
+ canConsumeStar = false;
+ continue;
+ }
break;
- case 81 /* ConstKeyword */:
- node.flags |= 2 /* Const */;
+ case 42 /* asterisk */:
+ if (canConsumeStar) {
+ pos++;
+ canConsumeStar = false;
+ continue;
+ }
break;
default:
- ts.Debug.fail();
- }
- nextToken();
- // 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() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
- node.declarations = createMissingList();
- }
- else {
- var savedDisallowIn = inDisallowInContext();
- setDisallowInContext(inForStatementInitializer);
- node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
- setDisallowInContext(savedDisallowIn);
- }
- return finishNode(node);
- }
- function canFollowContextualOfKeyword() {
- return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
- }
- function parseVariableStatement(node) {
- node.kind = 225 /* VariableStatement */;
- node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
- parseSemicolon();
- return finishNode(node);
- }
- function parseFunctionDeclaration(node) {
- node.kind = 244 /* FunctionDeclaration */;
- parseExpected(94 /* FunctionKeyword */);
- node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
- var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
- fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
- node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
- return finishNode(node);
- }
- function parseConstructorName() {
- if (token() === 129 /* ConstructorKeyword */) {
- return parseExpected(129 /* ConstructorKeyword */);
- }
- if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
- return tryParse(function () {
- var literalNode = parseLiteralNode();
- return literalNode.text === "constructor" ? literalNode : undefined;
- });
+ if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
+ pos++;
+ continue;
+ }
+ break;
}
+ return pos;
}
- function tryParseConstructorDeclaration(node) {
- return tryParse(function () {
- if (parseConstructorName()) {
- node.kind = 162 /* Constructor */;
- fillSignature(58 /* ColonToken */, 0 /* None */, node);
- node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
- return finishNode(node);
+ }
+ 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) {
+ for (var i = 0; i < mergeConflictMarkerLength; i++) {
+ if (text.charCodeAt(pos + i) !== ch) {
+ return false;
+ }
}
- });
- }
- function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
- node.kind = 161 /* MethodDeclaration */;
- node.asteriskToken = asteriskToken;
- var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
- fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
- node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
- return finishNode(node);
- }
- function parsePropertyDeclaration(node) {
- node.kind = 159 /* PropertyDeclaration */;
- if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
- node.exclamationToken = parseTokenNode();
- }
- node.type = parseTypeAnnotation();
- node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
- parseSemicolon();
- return finishNode(node);
- }
- function parsePropertyOrMethodDeclaration(node) {
- var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- node.name = parsePropertyName();
- // 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(57 /* QuestionToken */);
- if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
- return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
+ return ch === 61 /* equals */ ||
+ text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
}
- return parsePropertyDeclaration(node);
}
- function parseAccessorDeclaration(node, kind) {
- node.kind = kind;
- node.name = parsePropertyName();
- fillSignature(58 /* ColonToken */, 0 /* None */, node);
- node.body = parseFunctionBlockOrSemicolon(0 /* None */);
- return finishNode(node);
+ return false;
+ }
+ function scanConflictMarkerTrivia(text, pos, error) {
+ if (error) {
+ error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
}
- function isClassMemberStart() {
- var idToken;
- if (token() === 59 /* 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() === 41 /* 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();
- }
- // Index signatures and computed properties are class members; we can parse.
- if (token() === 22 /* OpenBracketToken */) {
- return true;
- }
- // If we were able to get any potential identifier...
- if (idToken !== undefined) {
- // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
- if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* 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 20 /* OpenParenToken */: // Method declaration
- case 29 /* LessThanToken */: // Generic Method declaration
- case 53 /* ExclamationToken */: // Non-null assertion on property name
- case 58 /* ColonToken */: // Type Annotation for declaration
- case 62 /* EqualsToken */: // Initializer for declaration
- case 57 /* 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();
- }
+ var ch = text.charCodeAt(pos);
+ var len = text.length;
+ if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
+ while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
+ pos++;
}
- return false;
}
- function parseDecorators() {
- var list;
- var listPos = getNodePos();
- while (true) {
- var decoratorStart = getNodePos();
- if (!parseOptional(59 /* AtToken */)) {
+ else {
+ 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 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
break;
}
- var decorator = createNode(157 /* 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() === 81 /* 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;
- }
- }
- else {
- if (!parseAnyContextualModifier()) {
- break;
- }
- }
- var modifier = finishNode(createNode(modifierKind, modifierStart));
- (list || (list = [])).push(modifier);
+ pos++;
}
- return list && createNodeArray(list, listPos);
}
- function parseModifiersForArrowFunction() {
- var modifiers;
- if (token() === 126 /* AsyncKeyword */) {
- var modifierStart = scanner.getStartPos();
- var modifierKind = token();
- nextToken();
- var modifier = finishNode(createNode(modifierKind, modifierStart));
- modifiers = createNodeArray([modifier], modifierStart);
+ return pos;
+ }
+ var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
+ 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);
+ }
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
+ function scanShebangTrivia(text, pos) {
+ var shebang = shebangTriviaRegex.exec(text)[0];
+ pos = pos + shebang.length;
+ return pos;
+ }
+ ts.scanShebangTrivia = scanShebangTrivia;
+ /**
+ * 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;
+ var pendingKind;
+ var pendingHasTrailingNewLine;
+ var hasPendingCommentRange = false;
+ var collecting = trailing;
+ var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
}
- return modifiers;
}
- function parseClassElement() {
- if (token() === 26 /* SemicolonToken */) {
- var result = createNode(222 /* SemicolonClassElement */);
- nextToken();
- return finishNode(result);
- }
- var node = createNodeWithJSDoc(0 /* Unknown */);
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
- if (parseContextualModifier(131 /* GetKeyword */)) {
- return parseAccessorDeclaration(node, 163 /* GetAccessor */);
- }
- if (parseContextualModifier(142 /* SetKeyword */)) {
- return parseAccessorDeclaration(node, 164 /* SetAccessor */);
- }
- if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
- var constructorDeclaration = tryParseConstructorDeclaration(node);
- if (constructorDeclaration) {
- return constructorDeclaration;
- }
- }
- 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() === 10 /* StringLiteral */ ||
- token() === 8 /* NumericLiteral */ ||
- token() === 41 /* AsteriskToken */ ||
- token() === 22 /* OpenBracketToken */) {
- var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
- if (isAmbient) {
- for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
- var m = _a[_i];
- m.flags |= 8388608 /* Ambient */;
+ scan: while (pos >= 0 && pos < text.length) {
+ var ch = text.charCodeAt(pos);
+ switch (ch) {
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
+ pos++;
}
- return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
- }
- else {
- return parsePropertyOrMethodDeclaration(node);
- }
- }
- if (node.decorators || node.modifiers) {
- // treat this as a property declaration with a missing name.
- node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
- return parsePropertyDeclaration(node);
+ // falls through
+ case 10 /* lineFeed */:
+ pos++;
+ if (trailing) {
+ break scan;
+ }
+ collecting = true;
+ if (hasPendingCommentRange) {
+ pendingHasTrailingNewLine = true;
+ }
+ continue;
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
+ pos++;
+ continue;
+ case 47 /* slash */:
+ var nextChar = text.charCodeAt(pos + 1);
+ var hasTrailingNewLine = false;
+ if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
+ var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
+ var startPos = pos;
+ pos += 2;
+ if (nextChar === 47 /* slash */) {
+ while (pos < text.length) {
+ if (isLineBreak(text.charCodeAt(pos))) {
+ hasTrailingNewLine = true;
+ break;
+ }
+ pos++;
+ }
+ }
+ else {
+ while (pos < text.length) {
+ if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
+ pos += 2;
+ break;
+ }
+ pos++;
+ }
+ }
+ if (collecting) {
+ 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;
+ }
+ }
+ pendingPos = startPos;
+ pendingEnd = pos;
+ pendingKind = kind;
+ pendingHasTrailingNewLine = hasTrailingNewLine;
+ hasPendingCommentRange = true;
+ }
+ continue;
+ }
+ break scan;
+ default:
+ if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
+ if (hasPendingCommentRange && isLineBreak(ch)) {
+ pendingHasTrailingNewLine = true;
+ }
+ pos++;
+ continue;
+ }
+ break scan;
}
- // '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 /* Unknown */), 214 /* ClassExpression */);
}
- function parseClassDeclaration(node) {
- return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
+ if (hasPendingCommentRange) {
+ accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
}
- function parseClassDeclarationOrExpression(node, kind) {
- node.kind = kind;
- parseExpected(80 /* ClassKeyword */);
- node.name = parseNameOfClassDeclarationOrExpression();
- node.typeParameters = parseTypeParameters();
- node.heritageClauses = parseHeritageClauses();
- if (parseExpected(18 /* OpenBraceToken */)) {
- // ClassTail[Yield,Await] : (Modified) See 14.5
- // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
- node.members = parseClassMembers();
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- node.members = createMissingList();
- }
- return finishNode(node);
+ return accumulator;
+ }
+ function forEachLeadingCommentRange(text, pos, cb, state) {
+ return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
+ }
+ ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
+ function forEachTrailingCommentRange(text, pos, cb, state) {
+ return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
+ }
+ ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
+ function reduceEachLeadingCommentRange(text, pos, 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(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
+ }
+ ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
+ function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
+ if (!comments) {
+ comments = [];
}
- 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;
+ comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
+ return comments;
+ }
+ function getLeadingCommentRanges(text, pos) {
+ return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
+ }
+ ts.getLeadingCommentRanges = getLeadingCommentRanges;
+ function getTrailingCommentRanges(text, pos) {
+ 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) {
+ return match[0];
}
- function isImplementsClause() {
- return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
+ }
+ ts.getShebang = getShebang;
+ function isIdentifierStart(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, identifierVariant) {
+ return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
+ ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
+ // "-" and ":" are valid in JSX Identifiers
+ (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
+ ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
+ }
+ ts.isIdentifierPart = isIdentifierPart;
+ /* @internal */
+ function isIdentifierText(name, languageVersion, identifierVariant) {
+ var ch = codePointAt(name, 0);
+ if (!isIdentifierStart(ch, languageVersion)) {
+ return false;
}
- function parseHeritageClauses() {
- // ClassTail[Yield,Await] : (Modified) See 14.5
- // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
- if (isHeritageClause()) {
- return parseList(22 /* HeritageClauses */, parseHeritageClause);
+ for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
+ if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
+ return false;
}
- return undefined;
- }
- function parseHeritageClause() {
- var tok = token();
- ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
- var node = createNode(279 /* HeritageClause */);
- node.token = tok;
- nextToken();
- node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
- return finishNode(node);
- }
- function parseExpressionWithTypeArguments() {
- var node = createNode(216 /* ExpressionWithTypeArguments */);
- node.expression = parseLeftHandSideExpressionOrHigher();
- node.typeArguments = tryParseTypeArguments();
- return finishNode(node);
- }
- function tryParseTypeArguments() {
- return token() === 29 /* LessThanToken */ ?
- parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
- }
- function isHeritageClause() {
- return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
}
- function parseClassMembers() {
- return parseList(5 /* ClassMembers */, parseClassElement);
+ 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 /* 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;
+ var tokenFlags;
+ var commentDirectives;
+ var inJSDocType = 0;
+ setText(text, start, length);
+ var scanner = {
+ getStartPos: function () { return startPos; },
+ getTextPos: function () { return pos; },
+ getToken: function () { return token; },
+ getTokenPos: function () { return tokenPos; },
+ getTokenText: function () { return text.substring(tokenPos, pos); },
+ getTokenValue: function () { return tokenValue; },
+ hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
+ hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
+ hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
+ hasPrecedingJSDocComment: function () { return (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0; },
+ isIdentifier: function () { return token === 79 /* Identifier */ || token > 116 /* LastReservedWord */; },
+ isReservedWord: function () { return token >= 81 /* FirstReservedWord */ && token <= 116 /* LastReservedWord */; },
+ isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
+ getCommentDirectives: function () { return commentDirectives; },
+ getNumericLiteralFlags: function () { return tokenFlags & 1008 /* NumericLiteralFlags */; },
+ getTokenFlags: function () { return tokenFlags; },
+ reScanGreaterToken: reScanGreaterToken,
+ reScanAsteriskEqualsToken: reScanAsteriskEqualsToken,
+ reScanSlashToken: reScanSlashToken,
+ reScanTemplateToken: reScanTemplateToken,
+ reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
+ scanJsxIdentifier: scanJsxIdentifier,
+ scanJsxAttributeValue: scanJsxAttributeValue,
+ reScanJsxAttributeValue: reScanJsxAttributeValue,
+ reScanJsxToken: reScanJsxToken,
+ reScanLessThanToken: reScanLessThanToken,
+ reScanHashToken: reScanHashToken,
+ reScanQuestionToken: reScanQuestionToken,
+ reScanInvalidIdentifier: reScanInvalidIdentifier,
+ scanJsxToken: scanJsxToken,
+ scanJsDocToken: scanJsDocToken,
+ scan: scan,
+ getText: getText,
+ clearCommentDirectives: clearCommentDirectives,
+ setText: setText,
+ setScriptTarget: setScriptTarget,
+ setLanguageVariant: setLanguageVariant,
+ setOnError: setOnError,
+ setTextPos: setTextPos,
+ setInJSDocType: setInJSDocType,
+ tryScan: tryScan,
+ lookAhead: lookAhead,
+ scanRange: scanRange,
+ };
+ if (ts.Debug.isDebugging) {
+ Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
+ get: function () {
+ var text = scanner.getText();
+ return text.slice(0, scanner.getStartPos()) + "â" + text.slice(scanner.getStartPos());
+ },
+ });
}
- function parseInterfaceDeclaration(node) {
- node.kind = 246 /* InterfaceDeclaration */;
- parseExpected(114 /* InterfaceKeyword */);
- node.name = parseIdentifier();
- node.typeParameters = parseTypeParameters();
- node.heritageClauses = parseHeritageClauses();
- node.members = parseObjectTypeMembers();
- return finishNode(node);
- }
- function parseTypeAliasDeclaration(node) {
- node.kind = 247 /* TypeAliasDeclaration */;
- parseExpected(145 /* TypeKeyword */);
- node.name = parseIdentifier();
- node.typeParameters = parseTypeParameters();
- parseExpected(62 /* EqualsToken */);
- node.type = parseType();
- parseSemicolon();
- return finishNode(node);
+ return scanner;
+ function error(message, errPos, length) {
+ if (errPos === void 0) { errPos = pos; }
+ if (onError) {
+ var oldPos = pos;
+ pos = errPos;
+ onError(message, length || 0);
+ pos = oldPos;
+ }
}
- // 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(284 /* EnumMember */);
- node.name = parsePropertyName();
- node.initializer = allowInAnd(parseInitializer);
- return finishNode(node);
- }
- function parseEnumDeclaration(node) {
- node.kind = 248 /* EnumDeclaration */;
- parseExpected(88 /* EnumKeyword */);
- node.name = parseIdentifier();
- if (parseExpected(18 /* OpenBraceToken */)) {
- node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
- parseExpected(19 /* CloseBraceToken */);
+ function scanNumberFragment() {
+ var start = pos;
+ var allowSeparator = false;
+ var isPreviousTokenSeparator = false;
+ var result = "";
+ while (true) {
+ var ch = text.charCodeAt(pos);
+ if (ch === 95 /* _ */) {
+ tokenFlags |= 512 /* ContainsSeparator */;
+ if (allowSeparator) {
+ allowSeparator = false;
+ isPreviousTokenSeparator = true;
+ result += text.substring(start, pos);
+ }
+ else if (isPreviousTokenSeparator) {
+ error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
+ }
+ else {
+ error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
+ }
+ pos++;
+ start = pos;
+ continue;
+ }
+ if (isDigit(ch)) {
+ allowSeparator = true;
+ isPreviousTokenSeparator = false;
+ pos++;
+ continue;
+ }
+ break;
}
- else {
- node.members = createMissingList();
+ if (text.charCodeAt(pos - 1) === 95 /* _ */) {
+ error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
}
- return finishNode(node);
+ return result + text.substring(start, pos);
}
- function parseModuleBlock() {
- var node = createNode(250 /* ModuleBlock */);
- if (parseExpected(18 /* OpenBraceToken */)) {
- node.statements = parseList(1 /* BlockStatements */, parseStatement);
- parseExpected(19 /* CloseBraceToken */);
+ function scanNumber() {
+ var start = pos;
+ var mainFragment = scanNumberFragment();
+ var decimalFragment;
+ var scientificFragment;
+ if (text.charCodeAt(pos) === 46 /* dot */) {
+ pos++;
+ decimalFragment = scanNumberFragment();
}
- else {
- node.statements = createMissingList();
+ var end = pos;
+ if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
+ pos++;
+ tokenFlags |= 16 /* Scientific */;
+ if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
+ pos++;
+ var preNumericPart = pos;
+ var finalFragment = scanNumberFragment();
+ if (!finalFragment) {
+ error(ts.Diagnostics.Digit_expected);
+ }
+ else {
+ scientificFragment = text.substring(end, preNumericPart) + finalFragment;
+ end = pos;
+ }
}
- return finishNode(node);
- }
- function parseModuleOrNamespaceDeclaration(node, flags) {
- node.kind = 249 /* 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(24 /* DotToken */)
- ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
- : parseModuleBlock();
- return finishNode(node);
- }
- function parseAmbientExternalModuleDeclaration(node) {
- node.kind = 249 /* ModuleDeclaration */;
- if (token() === 150 /* GlobalKeyword */) {
- // parse 'global' as name of global scope augmentation
- node.name = parseIdentifier();
- node.flags |= 1024 /* GlobalAugmentation */;
+ var result;
+ if (tokenFlags & 512 /* ContainsSeparator */) {
+ result = mainFragment;
+ if (decimalFragment) {
+ result += "." + decimalFragment;
+ }
+ if (scientificFragment) {
+ result += scientificFragment;
+ }
}
else {
- node.name = parseLiteralNode();
- node.name.text = internIdentifier(node.name.text);
+ result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
}
- if (token() === 18 /* OpenBraceToken */) {
- node.body = parseModuleBlock();
+ if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
+ checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
+ return {
+ type: 8 /* NumericLiteral */,
+ value: "" + +result // if value is not an integer, it can be safely coerced to a number
+ };
}
else {
- parseSemicolon();
+ tokenValue = result;
+ var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
+ checkForIdentifierStartAfterNumericLiteral(start);
+ return { type: type, value: tokenValue };
}
- return finishNode(node);
}
- function parseModuleDeclaration(node) {
- var flags = 0;
- if (token() === 150 /* GlobalKeyword */) {
- // global augmentation
- return parseAmbientExternalModuleDeclaration(node);
+ function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
+ if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
+ return;
}
- else if (parseOptional(136 /* NamespaceKeyword */)) {
- flags |= 16 /* Namespace */;
+ var identifierStart = pos;
+ var length = scanIdentifierParts().length;
+ if (length === 1 && text[identifierStart] === "n") {
+ if (isScientific) {
+ error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
+ }
+ else {
+ error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
+ }
}
else {
- parseExpected(135 /* ModuleKeyword */);
- if (token() === 10 /* StringLiteral */) {
- return parseAmbientExternalModuleDeclaration(node);
- }
+ error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
+ pos = identifierStart;
}
- return parseModuleOrNamespaceDeclaration(node, flags);
- }
- function isExternalModuleReference() {
- return token() === 139 /* RequireKeyword */ &&
- lookAhead(nextTokenIsOpenParen);
}
- function nextTokenIsOpenParen() {
- return nextToken() === 20 /* OpenParenToken */;
+ function scanOctalDigits() {
+ var start = pos;
+ while (isOctalDigit(text.charCodeAt(pos))) {
+ pos++;
+ }
+ return +(text.substring(start, pos));
}
- function nextTokenIsSlash() {
- return nextToken() === 43 /* SlashToken */;
+ /**
+ * Scans the given number of hexadecimal digits in the text,
+ * returning -1 if the given number is unavailable.
+ */
+ function scanExactNumberOfHexDigits(count, canHaveSeparators) {
+ var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
+ return valueString ? parseInt(valueString, 16) : -1;
}
- function parseNamespaceExportDeclaration(node) {
- node.kind = 252 /* NamespaceExportDeclaration */;
- parseExpected(123 /* AsKeyword */);
- parseExpected(136 /* NamespaceKeyword */);
- node.name = parseIdentifier();
- parseSemicolon();
- return finishNode(node);
+ /**
+ * Scans as many hexadecimal digits as are available in the text,
+ * returning "" if the given number of digits was unavailable.
+ */
+ function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
+ return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
}
- function parseImportDeclarationOrImportEqualsDeclaration(node) {
- parseExpected(96 /* ImportKeyword */);
- var afterImportPos = scanner.getStartPos();
- var identifier;
- if (isIdentifier()) {
- identifier = parseIdentifier();
- }
- var isTypeOnly = false;
- if (token() !== 149 /* FromKeyword */ &&
- (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
- (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
- isTypeOnly = true;
- identifier = isIdentifier() ? parseIdentifier() : undefined;
+ function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
+ var valueChars = [];
+ var allowSeparator = false;
+ var isPreviousTokenSeparator = false;
+ while (valueChars.length < minCount || scanAsManyAsPossible) {
+ var ch = text.charCodeAt(pos);
+ if (canHaveSeparators && ch === 95 /* _ */) {
+ tokenFlags |= 512 /* ContainsSeparator */;
+ if (allowSeparator) {
+ allowSeparator = false;
+ isPreviousTokenSeparator = true;
+ }
+ else if (isPreviousTokenSeparator) {
+ error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
+ }
+ else {
+ error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
+ }
+ pos++;
+ continue;
+ }
+ allowSeparator = canHaveSeparators;
+ if (ch >= 65 /* A */ && ch <= 70 /* F */) {
+ ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
+ }
+ else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
+ (ch >= 97 /* a */ && ch <= 102 /* f */))) {
+ break;
+ }
+ valueChars.push(ch);
+ pos++;
+ isPreviousTokenSeparator = false;
}
- if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
- return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
+ if (valueChars.length < minCount) {
+ valueChars = [];
}
- // Import statement
- node.kind = 254 /* ImportDeclaration */;
- // ImportDeclaration:
- // import ImportClause from ModuleSpecifier ;
- // import ModuleSpecifier;
- if (identifier || // import id
- token() === 41 /* AsteriskToken */ || // import *
- token() === 18 /* OpenBraceToken */ // import {
- ) {
- node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
- parseExpected(149 /* FromKeyword */);
+ if (text.charCodeAt(pos - 1) === 95 /* _ */) {
+ error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
}
- node.moduleSpecifier = parseModuleSpecifier();
- parseSemicolon();
- return finishNode(node);
- }
- function tokenAfterImportDefinitelyProducesImportDeclaration() {
- return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
+ return String.fromCharCode.apply(String, valueChars);
}
- function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
- // In `import id ___`, the current token decides whether to produce
- // an ImportDeclaration or ImportEqualsDeclaration.
- return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
+ function scanString(jsxAttributeString) {
+ if (jsxAttributeString === void 0) { jsxAttributeString = false; }
+ var quote = text.charCodeAt(pos);
+ pos++;
+ var result = "";
+ var start = pos;
+ while (true) {
+ if (pos >= end) {
+ result += text.substring(start, pos);
+ tokenFlags |= 4 /* Unterminated */;
+ error(ts.Diagnostics.Unterminated_string_literal);
+ break;
+ }
+ var ch = text.charCodeAt(pos);
+ if (ch === quote) {
+ result += text.substring(start, pos);
+ pos++;
+ break;
+ }
+ if (ch === 92 /* backslash */ && !jsxAttributeString) {
+ result += text.substring(start, pos);
+ result += scanEscapeSequence();
+ start = pos;
+ continue;
+ }
+ if (isLineBreak(ch) && !jsxAttributeString) {
+ result += text.substring(start, pos);
+ tokenFlags |= 4 /* Unterminated */;
+ error(ts.Diagnostics.Unterminated_string_literal);
+ break;
+ }
+ pos++;
+ }
+ return result;
}
- function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
- node.kind = 253 /* ImportEqualsDeclaration */;
- node.name = identifier;
- parseExpected(62 /* EqualsToken */);
- node.moduleReference = parseModuleReference();
- parseSemicolon();
- var finished = finishNode(node);
- if (isTypeOnly) {
- parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
+ /**
+ * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
+ * a literal component of a TemplateExpression.
+ */
+ function scanTemplateAndSetTokenValue(isTaggedTemplate) {
+ var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
+ pos++;
+ var start = pos;
+ var contents = "";
+ var resultingToken;
+ while (true) {
+ if (pos >= end) {
+ contents += text.substring(start, pos);
+ tokenFlags |= 4 /* Unterminated */;
+ error(ts.Diagnostics.Unterminated_template_literal);
+ resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
+ break;
+ }
+ var currChar = text.charCodeAt(pos);
+ // '`'
+ if (currChar === 96 /* backtick */) {
+ contents += text.substring(start, pos);
+ pos++;
+ resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
+ break;
+ }
+ // '${'
+ if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
+ contents += text.substring(start, pos);
+ pos += 2;
+ resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
+ break;
+ }
+ // Escape character
+ if (currChar === 92 /* backslash */) {
+ contents += text.substring(start, pos);
+ contents += scanEscapeSequence(isTaggedTemplate);
+ start = pos;
+ continue;
+ }
+ // 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 /* lineFeed */) {
+ pos++;
+ }
+ contents += "\n";
+ start = pos;
+ continue;
+ }
+ pos++;
}
- return finished;
+ ts.Debug.assert(resultingToken !== undefined);
+ tokenValue = contents;
+ return resultingToken;
}
- function parseImportClause(identifier, fullStart, isTypeOnly) {
- // ImportClause:
- // ImportedDefaultBinding
- // NameSpaceImport
- // NamedImports
- // ImportedDefaultBinding, NameSpaceImport
- // ImportedDefaultBinding, NamedImports
- var importClause = createNode(255 /* ImportClause */, fullStart);
- importClause.isTypeOnly = isTypeOnly;
- if (identifier) {
- // ImportedDefaultBinding:
- // ImportedBinding
- importClause.name = identifier;
+ function scanEscapeSequence(isTaggedTemplate) {
+ var start = pos;
+ pos++;
+ if (pos >= end) {
+ error(ts.Diagnostics.Unexpected_end_of_text);
+ return "";
}
- // If there was no default import or if there is comma token after default import
- // parse namespace or named imports
- if (!importClause.name ||
- parseOptional(27 /* CommaToken */)) {
- importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
+ var ch = text.charCodeAt(pos);
+ pos++;
+ switch (ch) {
+ case 48 /* _0 */:
+ // '\01'
+ if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
+ pos++;
+ tokenFlags |= 2048 /* ContainsInvalidEscape */;
+ return text.substring(start, pos);
+ }
+ return "\0";
+ case 98 /* b */:
+ return "\b";
+ case 116 /* t */:
+ return "\t";
+ case 110 /* n */:
+ return "\n";
+ case 118 /* v */:
+ return "\v";
+ case 102 /* f */:
+ return "\f";
+ case 114 /* r */:
+ return "\r";
+ case 39 /* singleQuote */:
+ return "\'";
+ case 34 /* doubleQuote */:
+ return "\"";
+ case 117 /* u */:
+ if (isTaggedTemplate) {
+ // '\u' or '\u0' or '\u00' or '\u000'
+ for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
+ if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
+ pos = escapePos;
+ tokenFlags |= 2048 /* ContainsInvalidEscape */;
+ return text.substring(start, pos);
+ }
+ }
+ }
+ // '\u{DDDDDDDD}'
+ if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
+ pos++;
+ // '\u{'
+ if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
+ tokenFlags |= 2048 /* ContainsInvalidEscape */;
+ return text.substring(start, pos);
+ }
+ if (isTaggedTemplate) {
+ var savePos = pos;
+ var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
+ var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
+ // '\u{Not Code Point' or '\u{CodePoint'
+ if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
+ tokenFlags |= 2048 /* ContainsInvalidEscape */;
+ return text.substring(start, pos);
+ }
+ else {
+ pos = savePos;
+ }
+ }
+ tokenFlags |= 8 /* ExtendedUnicodeEscape */;
+ return scanExtendedUnicodeEscape();
+ }
+ tokenFlags |= 1024 /* UnicodeEscape */;
+ // '\uDDDD'
+ return scanHexadecimalEscape(/*numDigits*/ 4);
+ case 120 /* x */:
+ if (isTaggedTemplate) {
+ if (!isHexDigit(text.charCodeAt(pos))) {
+ tokenFlags |= 2048 /* ContainsInvalidEscape */;
+ return text.substring(start, pos);
+ }
+ else if (!isHexDigit(text.charCodeAt(pos + 1))) {
+ pos++;
+ tokenFlags |= 2048 /* ContainsInvalidEscape */;
+ return text.substring(start, pos);
+ }
+ }
+ // '\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++;
+ }
+ // falls through
+ case 10 /* lineFeed */:
+ case 8232 /* lineSeparator */:
+ case 8233 /* paragraphSeparator */:
+ return "";
+ default:
+ return String.fromCharCode(ch);
}
- return finishNode(importClause);
- }
- function parseModuleReference() {
- return isExternalModuleReference()
- ? parseExternalModuleReference()
- : parseEntityName(/*allowReservedWords*/ false);
- }
- function parseExternalModuleReference() {
- var node = createNode(265 /* ExternalModuleReference */);
- parseExpected(139 /* RequireKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = parseModuleSpecifier();
- parseExpected(21 /* CloseParenToken */);
- return finishNode(node);
}
- function parseModuleSpecifier() {
- if (token() === 10 /* StringLiteral */) {
- var result = parseLiteralNode();
- result.text = internIdentifier(result.text);
- return result;
+ function scanHexadecimalEscape(numDigits) {
+ var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
+ if (escapedValue >= 0) {
+ return String.fromCharCode(escapedValue);
}
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();
+ error(ts.Diagnostics.Hexadecimal_digit_expected);
+ return "";
}
}
- function parseNamespaceImport() {
- // NameSpaceImport:
- // * as ImportedBinding
- var namespaceImport = createNode(256 /* NamespaceImport */);
- parseExpected(41 /* AsteriskToken */);
- parseExpected(123 /* AsKeyword */);
- namespaceImport.name = parseIdentifier();
- return finishNode(namespaceImport);
- }
- function parseNamedImportsOrExports(kind) {
- var node = createNode(kind);
- // NamedImports:
- // { }
- // { ImportsList }
- // { ImportsList, }
- // ImportsList:
- // ImportSpecifier
- // ImportsList, ImportSpecifier
- node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
- return finishNode(node);
- }
- function parseExportSpecifier() {
- return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
- }
- function parseImportSpecifier() {
- return parseImportOrExportSpecifier(258 /* 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() === 123 /* AsKeyword */) {
- node.propertyName = identifierName;
- parseExpected(123 /* AsKeyword */);
- checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
- checkIdentifierStart = scanner.getTokenPos();
- checkIdentifierEnd = scanner.getTextPos();
- node.name = parseIdentifierName();
+ function scanExtendedUnicodeEscape() {
+ var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
+ var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
+ var isInvalidExtendedEscape = false;
+ // Validate the value of the digit
+ if (escapedValue < 0) {
+ error(ts.Diagnostics.Hexadecimal_digit_expected);
+ isInvalidExtendedEscape = true;
+ }
+ else if (escapedValue > 0x10FFFF) {
+ error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
+ isInvalidExtendedEscape = true;
+ }
+ if (pos >= end) {
+ error(ts.Diagnostics.Unexpected_end_of_text);
+ isInvalidExtendedEscape = true;
+ }
+ else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
+ // Only swallow the following character up if it's a '}'.
+ pos++;
}
else {
- node.name = identifierName;
+ error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
+ isInvalidExtendedEscape = true;
}
- if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
- parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
+ if (isInvalidExtendedEscape) {
+ return "";
+ }
+ return utf16EncodeAsString(escapedValue);
+ }
+ // 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 /* u */) {
+ var start_1 = pos;
+ pos += 2;
+ var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
+ pos = start_1;
+ return value;
+ }
+ return -1;
+ }
+ function peekExtendedUnicodeEscape() {
+ if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
+ var start_2 = pos;
+ pos += 3;
+ var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
+ var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
+ pos = start_2;
+ return escapedValue;
}
- return finishNode(node);
+ return -1;
}
- function parseNamespaceExport(pos) {
- var node = createNode(262 /* NamespaceExport */, pos);
- node.name = parseIdentifier();
- return finishNode(node);
- }
- function parseExportDeclaration(node) {
- node.kind = 260 /* ExportDeclaration */;
- node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
- var namespaceExportPos = scanner.getStartPos();
- if (parseOptional(41 /* AsteriskToken */)) {
- if (parseOptional(123 /* AsKeyword */)) {
- node.exportClause = parseNamespaceExport(namespaceExportPos);
+ function scanIdentifierParts() {
+ var result = "";
+ var start = pos;
+ while (pos < end) {
+ var ch = codePointAt(text, pos);
+ if (isIdentifierPart(ch, languageVersion)) {
+ pos += charSize(ch);
+ }
+ else if (ch === 92 /* backslash */) {
+ ch = peekExtendedUnicodeEscape();
+ if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
+ pos += 3;
+ tokenFlags |= 8 /* ExtendedUnicodeEscape */;
+ result += scanExtendedUnicodeEscape();
+ start = pos;
+ continue;
+ }
+ ch = peekUnicodeEscape();
+ if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
+ break;
+ }
+ tokenFlags |= 1024 /* UnicodeEscape */;
+ result += text.substring(start, pos);
+ result += utf16EncodeAsString(ch);
+ // Valid Unicode escape is always six characters
+ pos += 6;
+ start = pos;
+ }
+ else {
+ break;
}
- parseExpected(149 /* FromKeyword */);
- node.moduleSpecifier = parseModuleSpecifier();
}
- else {
- node.exportClause = parseNamedImportsOrExports(261 /* 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() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
- parseExpected(149 /* FromKeyword */);
- node.moduleSpecifier = parseModuleSpecifier();
+ result += text.substring(start, pos);
+ return result;
+ }
+ function getIdentifierToken() {
+ // Reserved words are between 2 and 12 characters long and start with a lowercase letter
+ var len = tokenValue.length;
+ if (len >= 2 && len <= 12) {
+ var ch = tokenValue.charCodeAt(0);
+ if (ch >= 97 /* a */ && ch <= 122 /* z */) {
+ var keyword = textToKeyword.get(tokenValue);
+ if (keyword !== undefined) {
+ return token = keyword;
+ }
}
}
- parseSemicolon();
- return finishNode(node);
+ return token = 79 /* Identifier */;
}
- function parseExportAssignment(node) {
- node.kind = 259 /* ExportAssignment */;
- if (parseOptional(62 /* EqualsToken */)) {
- node.isExportEquals = true;
+ function scanBinaryOrOctalDigits(base) {
+ var value = "";
+ // 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 separatorAllowed = false;
+ var isPreviousTokenSeparator = false;
+ while (true) {
+ var ch = text.charCodeAt(pos);
+ // 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;
+ }
+ else if (isPreviousTokenSeparator) {
+ error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
+ }
+ else {
+ error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
+ }
+ pos++;
+ continue;
+ }
+ separatorAllowed = true;
+ if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
+ break;
+ }
+ value += text[pos];
+ pos++;
+ isPreviousTokenSeparator = false;
}
- else {
- parseExpected(84 /* DefaultKeyword */);
+ if (text.charCodeAt(pos - 1) === 95 /* _ */) {
+ // Literal ends with underscore - not allowed
+ error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
}
- 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 hasModifierOfKind(node, 89 /* ExportKeyword */)
- || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
- || node.kind === 254 /* ImportDeclaration */
- || node.kind === 259 /* ExportAssignment */
- || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
- }
- function getImportMetaIfNecessary(sourceFile) {
- return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
- walkTreeForExternalModuleIndicators(sourceFile) :
- undefined;
- }
- function walkTreeForExternalModuleIndicators(node) {
- return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
- }
- /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
- function hasModifierOfKind(node, kind) {
- return ts.some(node.modifiers, function (m) { return m.kind === kind; });
- }
- function isImportMeta(node) {
- return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
+ return value;
}
- var ParsingContext;
- (function (ParsingContext) {
- ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
- ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
- ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
- ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
- ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
- ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
- ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
- ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
- ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
- ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
- ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
- ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
- ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
- ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
- ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
- ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
- ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
- ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
- ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
- ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
- ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
- ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
- ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
- ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
- ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
- })(ParsingContext || (ParsingContext = {}));
- var Tristate;
- (function (Tristate) {
- Tristate[Tristate["False"] = 0] = "False";
- Tristate[Tristate["True"] = 1] = "True";
- Tristate[Tristate["Unknown"] = 2] = "Unknown";
- })(Tristate || (Tristate = {}));
- var JSDocParser;
- (function (JSDocParser) {
- function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
- scanner.setText(content, start, length);
- currentToken = scanner.scan();
- var jsDocTypeExpression = parseJSDocTypeExpression();
- var diagnostics = parseDiagnostics;
- clearState();
- return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
- }
- JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
- // Parses out a JSDoc type expression.
- function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(294 /* JSDocTypeExpression */);
- var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
- result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
- if (!mayOmitBraces || hasBrace) {
- parseExpectedJSDoc(19 /* CloseBraceToken */);
+ function checkBigIntSuffix() {
+ if (text.charCodeAt(pos) === 110 /* n */) {
+ tokenValue += "n";
+ // Use base 10 instead of base 2 or base 8 for shorter literals
+ if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
+ tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
}
- fixupParentReferences(result);
- return finishNode(result);
+ pos++;
+ return 9 /* BigIntLiteral */;
}
- JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
- function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = { languageVariant: 0 /* Standard */, text: content };
- var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
- var diagnostics = parseDiagnostics;
- clearState();
- return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
+ else { // not a bigint, so can convert to number in simplified form
+ // Number() may not support 0b or 0o, so use parseInt() instead
+ var numericValue = tokenFlags & 128 /* BinarySpecifier */
+ ? parseInt(tokenValue.slice(2), 2) // skip "0b"
+ : tokenFlags & 256 /* OctalSpecifier */
+ ? parseInt(tokenValue.slice(2), 8) // skip "0o"
+ : +tokenValue;
+ tokenValue = "" + numericValue;
+ return 8 /* NumericLiteral */;
}
- JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
- function parseJSDocComment(parent, start, length) {
- var _a;
- var saveToken = currentToken;
- var saveParseDiagnosticsLength = parseDiagnostics.length;
- var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
- var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
- if (comment) {
- comment.parent = parent;
+ }
+ function scan() {
+ var _a;
+ startPos = pos;
+ tokenFlags = 0 /* None */;
+ var asteriskSeen = false;
+ while (true) {
+ tokenPos = pos;
+ if (pos >= end) {
+ return token = 1 /* EndOfFileToken */;
}
- if (contextFlags & 131072 /* JavaScriptFile */) {
- if (!sourceFile.jsDocDiagnostics) {
- sourceFile.jsDocDiagnostics = [];
+ var ch = codePointAt(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 /* ShebangTrivia */;
}
- (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
- }
- currentToken = saveToken;
- parseDiagnostics.length = saveParseDiagnosticsLength;
- parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
- return comment;
- }
- JSDocParser.parseJSDocComment = parseJSDocComment;
- var JSDocState;
- (function (JSDocState) {
- JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
- JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
- JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
- JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
- })(JSDocState || (JSDocState = {}));
- var PropertyLikeParse;
- (function (PropertyLikeParse) {
- PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
- PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
- PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
- })(PropertyLikeParse || (PropertyLikeParse = {}));
- function parseJSDocCommentWorker(start, length) {
- if (start === void 0) { start = 0; }
- var content = sourceText;
- var end = length === undefined ? content.length : start + length;
- length = end - start;
- ts.Debug.assert(start >= 0);
- ts.Debug.assert(start <= end);
- ts.Debug.assert(end <= content.length);
- // Check for /** (JSDoc opening part)
- if (!isJSDocLikeText(content, start)) {
- return undefined;
}
- var tags;
- var tagsPos;
- var tagsEnd;
- var comments = [];
- // + 3 for leading /**, - 5 in total for /** */
- return scanner.scanRange(start + 3, length - 5, function () {
- // 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) {
- margin = indent;
+ switch (ch) {
+ case 10 /* lineFeed */:
+ case 13 /* carriageReturn */:
+ tokenFlags |= 1 /* PrecedingLineBreak */;
+ if (skipTrivia) {
+ pos++;
+ continue;
+ }
+ else {
+ 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 /* NewLineTrivia */;
+ }
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
+ case 160 /* nonBreakingSpace */:
+ case 5760 /* ogham */:
+ case 8192 /* enQuad */:
+ case 8193 /* emQuad */:
+ case 8194 /* enSpace */:
+ case 8195 /* emSpace */:
+ case 8196 /* threePerEmSpace */:
+ case 8197 /* fourPerEmSpace */:
+ case 8198 /* sixPerEmSpace */:
+ case 8199 /* figureSpace */:
+ case 8200 /* punctuationSpace */:
+ case 8201 /* thinSpace */:
+ case 8202 /* hairSpace */:
+ case 8203 /* zeroWidthSpace */:
+ case 8239 /* narrowNoBreakSpace */:
+ case 8287 /* mathematicalSpace */:
+ case 12288 /* ideographicSpace */:
+ case 65279 /* byteOrderMark */:
+ if (skipTrivia) {
+ pos++;
+ continue;
+ }
+ else {
+ while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
+ pos++;
+ }
+ return token = 5 /* WhitespaceTrivia */;
+ }
+ case 33 /* exclamation */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
+ }
+ return pos += 2, token = 35 /* ExclamationEqualsToken */;
+ }
+ pos++;
+ return token = 53 /* ExclamationToken */;
+ case 34 /* doubleQuote */:
+ case 39 /* singleQuote */:
+ tokenValue = scanString();
+ return token = 10 /* StringLiteral */;
+ case 96 /* backtick */:
+ return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
+ case 37 /* percent */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 69 /* PercentEqualsToken */;
+ }
+ pos++;
+ return token = 44 /* PercentToken */;
+ case 38 /* ampersand */:
+ if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 76 /* AmpersandAmpersandEqualsToken */;
+ }
+ return pos += 2, token = 55 /* AmpersandAmpersandToken */;
+ }
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 73 /* AmpersandEqualsToken */;
+ }
+ pos++;
+ return token = 50 /* AmpersandToken */;
+ case 40 /* openParen */:
+ pos++;
+ return token = 20 /* OpenParenToken */;
+ case 41 /* closeParen */:
+ pos++;
+ return token = 21 /* CloseParenToken */;
+ case 42 /* asterisk */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 66 /* AsteriskEqualsToken */;
+ }
+ if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 67 /* AsteriskAsteriskEqualsToken */;
+ }
+ return pos += 2, token = 42 /* AsteriskAsteriskToken */;
+ }
+ pos++;
+ if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
+ // decoration at the start of a JSDoc comment line
+ asteriskSeen = true;
+ continue;
+ }
+ return token = 41 /* AsteriskToken */;
+ case 43 /* plus */:
+ if (text.charCodeAt(pos + 1) === 43 /* plus */) {
+ return pos += 2, token = 45 /* PlusPlusToken */;
+ }
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 64 /* PlusEqualsToken */;
+ }
+ pos++;
+ return token = 39 /* PlusToken */;
+ case 44 /* comma */:
+ pos++;
+ return token = 27 /* CommaToken */;
+ case 45 /* minus */:
+ if (text.charCodeAt(pos + 1) === 45 /* minus */) {
+ return pos += 2, token = 46 /* MinusMinusToken */;
+ }
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 65 /* MinusEqualsToken */;
+ }
+ pos++;
+ return token = 40 /* MinusToken */;
+ case 46 /* dot */:
+ if (isDigit(text.charCodeAt(pos + 1))) {
+ tokenValue = scanNumber().value;
+ return token = 8 /* NumericLiteral */;
+ }
+ if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
+ return pos += 3, token = 25 /* DotDotDotToken */;
+ }
+ pos++;
+ return token = 24 /* DotToken */;
+ case 47 /* slash */:
+ // Single-line comment
+ if (text.charCodeAt(pos + 1) === 47 /* slash */) {
+ pos += 2;
+ while (pos < end) {
+ if (isLineBreak(text.charCodeAt(pos))) {
+ break;
+ }
+ pos++;
+ }
+ commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ return token = 2 /* SingleLineCommentTrivia */;
+ }
+ }
+ // Multi-line comment
+ if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
+ pos += 2;
+ if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
+ tokenFlags |= 2 /* PrecedingJSDocComment */;
+ }
+ var commentClosed = false;
+ var lastLineStart = tokenPos;
+ while (pos < end) {
+ var ch_1 = text.charCodeAt(pos);
+ if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
+ pos += 2;
+ commentClosed = true;
+ break;
+ }
+ pos++;
+ if (isLineBreak(ch_1)) {
+ lastLineStart = pos;
+ tokenFlags |= 1 /* PrecedingLineBreak */;
+ }
+ }
+ commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
+ if (!commentClosed) {
+ error(ts.Diagnostics.Asterisk_Slash_expected);
+ }
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ if (!commentClosed) {
+ tokenFlags |= 4 /* Unterminated */;
+ }
+ return token = 3 /* MultiLineCommentTrivia */;
+ }
+ }
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 68 /* SlashEqualsToken */;
+ }
+ pos++;
+ return token = 43 /* SlashToken */;
+ case 48 /* _0 */:
+ if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
+ pos += 2;
+ tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
+ if (!tokenValue) {
+ error(ts.Diagnostics.Hexadecimal_digit_expected);
+ tokenValue = "0";
+ }
+ tokenValue = "0x" + tokenValue;
+ tokenFlags |= 64 /* HexSpecifier */;
+ return token = checkBigIntSuffix();
+ }
+ else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
+ pos += 2;
+ tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
+ if (!tokenValue) {
+ error(ts.Diagnostics.Binary_digit_expected);
+ tokenValue = "0";
+ }
+ tokenValue = "0b" + tokenValue;
+ tokenFlags |= 128 /* BinarySpecifier */;
+ return token = checkBigIntSuffix();
+ }
+ else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
+ pos += 2;
+ tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
+ if (!tokenValue) {
+ error(ts.Diagnostics.Octal_digit_expected);
+ tokenValue = "0";
+ }
+ tokenValue = "0o" + tokenValue;
+ tokenFlags |= 256 /* OctalSpecifier */;
+ return token = checkBigIntSuffix();
+ }
+ // Try to parse as an octal
+ if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
+ tokenValue = "" + scanOctalDigits();
+ tokenFlags |= 32 /* Octal */;
+ return token = 8 /* NumericLiteral */;
+ }
+ // 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 */:
+ (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
+ return token;
+ case 58 /* colon */:
+ pos++;
+ return token = 58 /* ColonToken */;
+ case 59 /* semicolon */:
+ pos++;
+ return token = 26 /* SemicolonToken */;
+ case 60 /* lessThan */:
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ return token = 7 /* ConflictMarkerTrivia */;
+ }
+ }
+ if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 70 /* LessThanLessThanEqualsToken */;
+ }
+ return pos += 2, token = 47 /* LessThanLessThanToken */;
}
- comments.push(text);
- indent += text.length;
- }
- nextTokenJSDoc();
- while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
- ;
- if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
- state = 0 /* BeginningOfLine */;
- indent = 0;
- }
- loop: while (true) {
- switch (token()) {
- case 59 /* AtToken */:
- if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
- removeTrailingWhitespace(comments);
- addTag(parseTag(indent));
- // 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;
- }
- else {
- pushComment(scanner.getTokenText());
- }
- break;
- case 4 /* NewLineTrivia */:
- comments.push(scanner.getTokenText());
- state = 0 /* BeginningOfLine */;
- indent = 0;
- break;
- case 41 /* AsteriskToken */:
- var asterisk = scanner.getTokenText();
- 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 {
- // Ignore the first asterisk on a line
- state = 1 /* SawAsterisk */;
- indent += asterisk.length;
- }
- break;
- 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 /* SavingComments */) {
- comments.push(whitespace);
- }
- else if (margin !== undefined && indent + whitespace.length > margin) {
- comments.push(whitespace.slice(margin - indent - 1));
- }
- indent += whitespace.length;
- break;
- case 1 /* EndOfFileToken */:
- break loop;
- default:
- // 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.
- state = 2 /* SavingComments */;
- pushComment(scanner.getTokenText());
- break;
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 32 /* LessThanEqualsToken */;
}
- nextTokenJSDoc();
- }
- removeLeadingNewlines(comments);
- removeTrailingWhitespace(comments);
- return createJSDocComment();
- });
- function removeLeadingNewlines(comments) {
- while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
- comments.shift();
- }
- }
- function removeTrailingWhitespace(comments) {
- while (comments.length && comments[comments.length - 1].trim() === "") {
- comments.pop();
- }
- }
- function createJSDocComment() {
- var result = createNode(303 /* 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) {
- nextTokenJSDoc();
- if (token() === 1 /* EndOfFileToken */) {
- return true;
+ if (languageVariant === 1 /* JSX */ &&
+ text.charCodeAt(pos + 1) === 47 /* slash */ &&
+ text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
+ return pos += 2, token = 30 /* LessThanSlashToken */;
}
- if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
- return false;
+ pos++;
+ return token = 29 /* LessThanToken */;
+ case 61 /* equals */:
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ return token = 7 /* ConflictMarkerTrivia */;
+ }
}
- }
- }
- function skipWhitespace() {
- if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
- return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
+ }
+ return pos += 2, token = 34 /* EqualsEqualsToken */;
}
- }
- while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- nextTokenJSDoc();
- }
- }
- function skipWhitespaceOrAsterisk() {
- if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
- return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
+ if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
+ return pos += 2, token = 38 /* EqualsGreaterThanToken */;
}
- }
- var precedingLineBreak = scanner.hasPrecedingLineBreak();
- var seenLineBreak = false;
- var indentText = "";
- while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- indentText += scanner.getTokenText();
- if (token() === 4 /* NewLineTrivia */) {
- precedingLineBreak = true;
- seenLineBreak = true;
- indentText = "";
+ pos++;
+ return token = 63 /* EqualsToken */;
+ case 62 /* greaterThan */:
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ return token = 7 /* ConflictMarkerTrivia */;
+ }
}
- else if (token() === 41 /* AsteriskToken */) {
- precedingLineBreak = false;
+ pos++;
+ return token = 31 /* GreaterThanToken */;
+ case 63 /* question */:
+ if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) {
+ return pos += 2, token = 28 /* QuestionDotToken */;
}
- nextTokenJSDoc();
- }
- return seenLineBreak ? indentText : "";
- }
- function parseTag(margin) {
- ts.Debug.assert(token() === 59 /* AtToken */);
- var start = scanner.getTokenPos();
- nextTokenJSDoc();
- var tagName = parseJSDocIdentifierName(/*message*/ undefined);
- var indentText = skipWhitespaceOrAsterisk();
- var tag;
- switch (tagName.escapedText) {
- case "author":
- tag = parseAuthorTag(start, tagName, margin);
- break;
- case "implements":
- tag = parseImplementsTag(start, tagName);
- break;
- case "augments":
- case "extends":
- tag = parseAugmentsTag(start, tagName);
- break;
- case "class":
- case "constructor":
- tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
- break;
- case "public":
- tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
- break;
- case "private":
- tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
- break;
- case "protected":
- tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
- break;
- case "readonly":
- tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
- break;
- case "this":
- tag = parseThisTag(start, tagName);
- break;
- case "enum":
- tag = parseEnumTag(start, tagName);
- break;
- case "arg":
- case "argument":
- case "param":
- return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
- case "return":
- case "returns":
- tag = parseReturnTag(start, tagName);
- break;
- case "template":
- tag = parseTemplateTag(start, tagName);
- break;
- case "type":
- tag = parseTypeTag(start, tagName);
- break;
- case "typedef":
- tag = parseTypedefTag(start, tagName, margin);
- break;
- case "callback":
- tag = parseCallbackTag(start, tagName, margin);
- break;
- default:
- tag = parseUnknownTag(start, tagName);
- break;
- }
- if (!tag.comment) {
- // some tags, like typedef and callback, have already parsed their comments earlier
- if (!indentText) {
- margin += tag.end - tag.pos;
+ if (text.charCodeAt(pos + 1) === 63 /* question */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 77 /* QuestionQuestionEqualsToken */;
+ }
+ return pos += 2, token = 60 /* QuestionQuestionToken */;
}
- tag.comment = parseTagComments(margin, indentText.slice(margin));
- }
- return tag;
- }
- function parseTagComments(indent, initialMargin) {
- var comments = [];
- var state = 0 /* BeginningOfLine */;
- var margin;
- function pushComment(text) {
- if (!margin) {
- margin = indent;
+ pos++;
+ return token = 57 /* QuestionToken */;
+ case 91 /* openBracket */:
+ pos++;
+ return token = 22 /* OpenBracketToken */;
+ case 93 /* closeBracket */:
+ pos++;
+ return token = 23 /* CloseBracketToken */;
+ case 94 /* caret */:
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 78 /* CaretEqualsToken */;
}
- comments.push(text);
- indent += text.length;
- }
- if (initialMargin !== undefined) {
- // jump straight to saving comments if there is some initial indentation
- if (initialMargin !== "") {
- pushComment(initialMargin);
+ pos++;
+ return token = 52 /* CaretToken */;
+ case 123 /* openBrace */:
+ pos++;
+ return token = 18 /* OpenBraceToken */;
+ case 124 /* bar */:
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ return token = 7 /* ConflictMarkerTrivia */;
+ }
}
- state = 1 /* SawAsterisk */;
- }
- var tok = token();
- loop: while (true) {
- switch (tok) {
- case 4 /* NewLineTrivia */:
- if (state >= 1 /* SawAsterisk */) {
- state = 0 /* BeginningOfLine */;
- // don't use pushComment here because we want to keep the margin unchanged
- comments.push(scanner.getTokenText());
- }
- indent = 0;
- break;
- case 59 /* AtToken */:
- if (state === 3 /* SavingBackticks */) {
- comments.push(scanner.getTokenText());
- break;
- }
- scanner.setTextPos(scanner.getTextPos() - 1);
- // falls through
- case 1 /* EndOfFileToken */:
- // Done
- break loop;
- case 5 /* WhitespaceTrivia */:
- if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
- 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));
- }
- indent += whitespace.length;
- }
- break;
- case 18 /* OpenBraceToken */:
- state = 2 /* SavingComments */;
- if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
- pushComment(scanner.getTokenText());
- nextTokenJSDoc();
- pushComment(scanner.getTokenText());
- nextTokenJSDoc();
- }
- pushComment(scanner.getTokenText());
- break;
- case 61 /* BacktickToken */:
- if (state === 3 /* SavingBackticks */) {
- state = 2 /* SavingComments */;
- }
- else {
- state = 3 /* SavingBackticks */;
- }
- pushComment(scanner.getTokenText());
- break;
- case 41 /* 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:
- if (state !== 3 /* SavingBackticks */) {
- state = 2 /* SavingComments */; // leading identifiers start recording as well
- }
- pushComment(scanner.getTokenText());
- break;
+ if (text.charCodeAt(pos + 1) === 124 /* bar */) {
+ if (text.charCodeAt(pos + 2) === 61 /* equals */) {
+ return pos += 3, token = 75 /* BarBarEqualsToken */;
+ }
+ return pos += 2, token = 56 /* BarBarToken */;
}
- tok = nextTokenJSDoc();
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 74 /* BarEqualsToken */;
+ }
+ pos++;
+ return token = 51 /* BarToken */;
+ case 125 /* closeBrace */:
+ pos++;
+ return token = 19 /* CloseBraceToken */;
+ case 126 /* tilde */:
+ pos++;
+ return token = 54 /* TildeToken */;
+ case 64 /* at */:
+ pos++;
+ return token = 59 /* AtToken */;
+ case 92 /* backslash */:
+ var extendedCookedChar = peekExtendedUnicodeEscape();
+ if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
+ pos += 3;
+ tokenFlags |= 8 /* ExtendedUnicodeEscape */;
+ tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
+ return token = getIdentifierToken();
+ }
+ var cookedChar = peekUnicodeEscape();
+ if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
+ pos += 6;
+ tokenFlags |= 1024 /* UnicodeEscape */;
+ tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
+ return token = getIdentifierToken();
+ }
+ error(ts.Diagnostics.Invalid_character);
+ pos++;
+ return token = 0 /* Unknown */;
+ case 35 /* hash */:
+ if (pos !== 0 && text[pos + 1] === "!") {
+ error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
+ pos++;
+ return token = 0 /* Unknown */;
+ }
+ if (isIdentifierStart(codePointAt(text, pos + 1), languageVersion)) {
+ pos++;
+ scanIdentifier(codePointAt(text, pos), languageVersion);
+ }
+ else {
+ tokenValue = String.fromCharCode(codePointAt(text, pos));
+ error(ts.Diagnostics.Invalid_character, pos++, charSize(ch));
+ }
+ return token = 80 /* PrivateIdentifier */;
+ default:
+ var identifierKind = scanIdentifier(ch, languageVersion);
+ if (identifierKind) {
+ return token = identifierKind;
+ }
+ else if (isWhiteSpaceSingleLine(ch)) {
+ pos += charSize(ch);
+ continue;
+ }
+ else if (isLineBreak(ch)) {
+ tokenFlags |= 1 /* PrecedingLineBreak */;
+ pos += charSize(ch);
+ continue;
+ }
+ var size = charSize(ch);
+ error(ts.Diagnostics.Invalid_character, pos, size);
+ pos += size;
+ return token = 0 /* Unknown */;
+ }
+ }
+ }
+ function reScanInvalidIdentifier() {
+ ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'.");
+ pos = tokenPos = startPos;
+ tokenFlags = 0;
+ var ch = codePointAt(text, pos);
+ var identifierKind = scanIdentifier(ch, 99 /* ESNext */);
+ if (identifierKind) {
+ return token = identifierKind;
+ }
+ pos += charSize(ch);
+ return token; // Still `SyntaKind.Unknown`
+ }
+ function scanIdentifier(startCharacter, languageVersion) {
+ var ch = startCharacter;
+ if (isIdentifierStart(ch, languageVersion)) {
+ pos += charSize(ch);
+ while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
+ pos += charSize(ch);
+ tokenValue = text.substring(tokenPos, pos);
+ if (ch === 92 /* backslash */) {
+ tokenValue += scanIdentifierParts();
+ }
+ return getIdentifierToken();
+ }
+ }
+ function reScanGreaterToken() {
+ if (token === 31 /* 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 = 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
+ }
+ return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
}
- removeLeadingNewlines(comments);
- removeTrailingWhitespace(comments);
- return comments.length === 0 ? undefined : comments.join("");
+ if (text.charCodeAt(pos + 1) === 61 /* equals */) {
+ return pos += 2, token = 71 /* GreaterThanGreaterThanEqualsToken */;
+ }
+ pos++;
+ return token = 48 /* GreaterThanGreaterThanToken */;
}
- function parseUnknownTag(start, tagName) {
- var result = createNode(306 /* JSDocTag */, start);
- result.tagName = tagName;
- return finishNode(result);
+ if (text.charCodeAt(pos) === 61 /* equals */) {
+ pos++;
+ return token = 33 /* GreaterThanEqualsToken */;
}
- function addTag(tag) {
- if (!tag) {
- return;
+ }
+ return token;
+ }
+ function reScanAsteriskEqualsToken() {
+ ts.Debug.assert(token === 66 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='");
+ pos = tokenPos + 1;
+ return token = 63 /* EqualsToken */;
+ }
+ function reScanSlashToken() {
+ if (token === 43 /* SlashToken */ || token === 68 /* 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 /* Unterminated */;
+ error(ts.Diagnostics.Unterminated_regular_expression_literal);
+ break;
}
- if (!tags) {
- tags = [tag];
- tagsPos = tag.pos;
+ var ch = text.charCodeAt(p);
+ if (isLineBreak(ch)) {
+ tokenFlags |= 4 /* Unterminated */;
+ error(ts.Diagnostics.Unterminated_regular_expression_literal);
+ break;
}
- else {
- tags.push(tag);
+ if (inEscape) {
+ // Parsing an escape character;
+ // reset the flag and just advance to the next char.
+ inEscape = false;
}
- tagsEnd = tag.end;
+ 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 /* openBracket */) {
+ inCharacterClass = true;
+ }
+ else if (ch === 92 /* backslash */) {
+ inEscape = true;
+ }
+ else if (ch === 93 /* closeBracket */) {
+ inCharacterClass = false;
+ }
+ p++;
}
- function tryParseTypeExpression() {
- skipWhitespaceOrAsterisk();
- return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
+ while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
+ p++;
+ }
+ pos = p;
+ tokenValue = text.substring(tokenPos, pos);
+ token = 13 /* RegularExpressionLiteral */;
+ }
+ return token;
+ }
+ function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
+ var type = getDirectiveFromComment(ts.trimStringStart(text), commentDirectiveRegEx);
+ if (type === undefined) {
+ return commentDirectives;
+ }
+ return ts.append(commentDirectives, {
+ range: { pos: lineStart, end: pos },
+ type: type,
+ });
+ }
+ function getDirectiveFromComment(text, commentDirectiveRegEx) {
+ var match = commentDirectiveRegEx.exec(text);
+ if (!match) {
+ return undefined;
+ }
+ switch (match[1]) {
+ case "ts-expect-error":
+ return 0 /* ExpectError */;
+ case "ts-ignore":
+ return 1 /* Ignore */;
+ }
+ return undefined;
+ }
+ /**
+ * Unconditionally back up and scan a template expression portion.
+ */
+ function reScanTemplateToken(isTaggedTemplate) {
+ ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
+ pos = tokenPos;
+ return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
+ }
+ function reScanTemplateHeadOrNoSubstitutionTemplate() {
+ pos = tokenPos;
+ return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
+ }
+ function reScanJsxToken(allowMultilineJsxText) {
+ if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; }
+ pos = tokenPos = startPos;
+ return token = scanJsxToken(allowMultilineJsxText);
+ }
+ function reScanLessThanToken() {
+ if (token === 47 /* LessThanLessThanToken */) {
+ pos = tokenPos + 1;
+ return token = 29 /* LessThanToken */;
+ }
+ return token;
+ }
+ function reScanHashToken() {
+ if (token === 80 /* PrivateIdentifier */) {
+ pos = tokenPos + 1;
+ return token = 62 /* HashToken */;
+ }
+ return token;
+ }
+ function reScanQuestionToken() {
+ ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
+ pos = tokenPos + 1;
+ return token = 57 /* QuestionToken */;
+ }
+ function scanJsxToken(allowMultilineJsxText) {
+ if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; }
+ startPos = tokenPos = pos;
+ if (pos >= end) {
+ return token = 1 /* EndOfFileToken */;
+ }
+ var char = text.charCodeAt(pos);
+ if (char === 60 /* lessThan */) {
+ if (text.charCodeAt(pos + 1) === 47 /* slash */) {
+ pos += 2;
+ return token = 30 /* LessThanSlashToken */;
}
- function parseBracketNameInPropertyAndParamTag() {
- // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
- var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
- if (isBracketed) {
- skipWhitespace();
- }
- // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
- var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
- var name = parseJSDocEntityName();
- if (isBackquoted) {
- parseExpectedTokenJSDoc(61 /* BacktickToken */);
- }
- if (isBracketed) {
- skipWhitespace();
- // May have an optional default, e.g. '[foo = 42]'
- if (parseOptionalToken(62 /* EqualsToken */)) {
- parseExpression();
- }
- parseExpected(23 /* CloseBracketToken */);
- }
- return { name: name, isBracketed: isBracketed };
+ pos++;
+ return token = 29 /* LessThanToken */;
+ }
+ if (char === 123 /* openBrace */) {
+ pos++;
+ return token = 18 /* 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 whitespace,
+ while (pos < end) {
+ char = text.charCodeAt(pos);
+ if (char === 123 /* openBrace */) {
+ break;
}
- function isObjectOrObjectArrayTypeReference(node) {
- switch (node.kind) {
- case 141 /* ObjectKeyword */:
- return true;
- case 174 /* ArrayType */:
- return isObjectOrObjectArrayTypeReference(node.elementType);
- default:
- return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
+ if (char === 60 /* lessThan */) {
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ return token = 7 /* ConflictMarkerTrivia */;
}
+ break;
}
- function parseParameterOrPropertyTag(start, tagName, target, indent) {
- var typeExpression = tryParseTypeExpression();
- var isNameFirst = !typeExpression;
- skipWhitespaceOrAsterisk();
- var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
- skipWhitespace();
- if (isNameFirst) {
- typeExpression = tryParseTypeExpression();
- }
- var result = target === 1 /* Property */ ?
- createNode(323 /* JSDocPropertyTag */, start) :
- createNode(317 /* JSDocParameterTag */, start);
- var comment = parseTagComments(indent + scanner.getStartPos() - start);
- var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
- if (nestedTypeLiteral) {
- typeExpression = nestedTypeLiteral;
- isNameFirst = true;
- }
- result.tagName = tagName;
- result.typeExpression = typeExpression;
- result.name = name;
- result.isNameFirst = isNameFirst;
- result.isBracketed = isBracketed;
- result.comment = comment;
- return finishNode(result);
+ if (char === 62 /* greaterThan */) {
+ error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
}
- function parseNestedTypeLiteral(typeExpression, name, target, indent) {
- if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
- var child = void 0;
- var jsdocTypeLiteral = void 0;
- var start_3 = scanner.getStartPos();
- var children = void 0;
- while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
- children = ts.append(children, child);
- }
- }
- if (children) {
- jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
- jsdocTypeLiteral.jsDocPropertyTags = children;
- if (typeExpression.type.kind === 174 /* ArrayType */) {
- jsdocTypeLiteral.isArrayType = true;
- }
- typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
- return finishNode(typeLiteralExpression);
- }
- }
+ if (char === 125 /* closeBrace */) {
+ error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
}
- function parseReturnTag(start, tagName) {
- if (ts.some(tags, ts.isJSDocReturnTag)) {
- parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
- }
- var result = createNode(318 /* JSDocReturnTag */, start);
- result.tagName = tagName;
- result.typeExpression = tryParseTypeExpression();
- return finishNode(result);
+ // 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;
}
- function parseTypeTag(start, tagName) {
- if (ts.some(tags, ts.isJSDocTypeTag)) {
- parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
- }
- var result = createNode(320 /* JSDocTypeTag */, start);
- result.tagName = tagName;
- result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
- return finishNode(result);
+ else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) {
+ // Stop JsxText on each line during formatting. This allows the formatter to
+ // indent each line correctly.
+ break;
}
- function parseAuthorTag(start, tagName, indent) {
- var result = createNode(309 /* JSDocAuthorTag */, start);
- result.tagName = tagName;
- var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
- if (!authorInfoWithEmail) {
- return finishNode(result);
- }
- result.comment = authorInfoWithEmail;
- if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
- var comment = parseTagComments(indent);
- if (comment) {
- result.comment += comment;
- }
- }
- return finishNode(result);
+ else if (!isWhiteSpaceLike(char)) {
+ firstNonWhitespace = pos;
}
- function tryParseAuthorNameAndEmail() {
- var comments = [];
- var seenLessThan = false;
- var seenGreaterThan = false;
- var token = scanner.getToken();
- loop: while (true) {
- switch (token) {
- case 75 /* Identifier */:
- case 5 /* WhitespaceTrivia */:
- case 24 /* DotToken */:
- case 59 /* AtToken */:
- comments.push(scanner.getTokenText());
- break;
- case 29 /* LessThanToken */:
- if (seenLessThan || seenGreaterThan) {
- return;
- }
- seenLessThan = true;
- comments.push(scanner.getTokenText());
- break;
- case 31 /* GreaterThanToken */:
- if (!seenLessThan || seenGreaterThan) {
- return;
- }
- seenGreaterThan = true;
- comments.push(scanner.getTokenText());
- scanner.setTextPos(scanner.getTokenPos() + 1);
- break loop;
- case 4 /* NewLineTrivia */:
- case 1 /* EndOfFileToken */:
- break loop;
- }
- token = nextTokenJSDoc();
- }
- if (seenLessThan && seenGreaterThan) {
- return comments.length === 0 ? undefined : comments.join("");
+ pos++;
+ }
+ tokenValue = text.substring(startPos, pos);
+ return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
+ }
+ // Scans a JSX identifier; these differ from normal identifiers in that
+ // they allow dashes
+ function scanJsxIdentifier() {
+ if (tokenIsIdentifierOrKeyword(token)) {
+ // An identifier or keyword has already been parsed - check for a `-` or a single instance of `:` and then append it and
+ // everything after it to the token
+ // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
+ // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
+ var namespaceSeparator = false;
+ while (pos < end) {
+ var ch = text.charCodeAt(pos);
+ if (ch === 45 /* minus */) {
+ tokenValue += "-";
+ pos++;
+ continue;
}
- }
- function parseImplementsTag(start, tagName) {
- var result = createNode(308 /* JSDocImplementsTag */, start);
- result.tagName = tagName;
- result.class = parseExpressionWithTypeArgumentsForAugments();
- return finishNode(result);
- }
- function parseAugmentsTag(start, tagName) {
- var result = createNode(307 /* JSDocAugmentsTag */, start);
- result.tagName = tagName;
- result.class = parseExpressionWithTypeArgumentsForAugments();
- return finishNode(result);
- }
- function parseExpressionWithTypeArgumentsForAugments() {
- var usedBrace = parseOptional(18 /* OpenBraceToken */);
- var node = createNode(216 /* ExpressionWithTypeArguments */);
- node.expression = parsePropertyAccessEntityNameExpression();
- node.typeArguments = tryParseTypeArguments();
- var res = finishNode(node);
- if (usedBrace) {
- parseExpected(19 /* CloseBraceToken */);
+ else if (ch === 58 /* colon */ && !namespaceSeparator) {
+ tokenValue += ":";
+ pos++;
+ namespaceSeparator = true;
+ token = 79 /* Identifier */; // swap from keyword kind to identifier kind
+ continue;
}
- return res;
- }
- function parsePropertyAccessEntityNameExpression() {
- var node = parseJSDocIdentifierName();
- while (parseOptional(24 /* DotToken */)) {
- var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
- prop.expression = node;
- prop.name = parseJSDocIdentifierName();
- node = finishNode(prop);
+ var oldPos = pos;
+ tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
+ if (pos === oldPos) {
+ break;
}
- return node;
- }
- function parseSimpleTag(start, kind, tagName) {
- var tag = createNode(kind, start);
- tag.tagName = tagName;
- return finishNode(tag);
- }
- function parseThisTag(start, tagName) {
- var tag = createNode(319 /* JSDocThisTag */, start);
- tag.tagName = tagName;
- tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
- skipWhitespace();
- return finishNode(tag);
}
- function parseEnumTag(start, tagName) {
- var tag = createNode(316 /* JSDocEnumTag */, start);
- tag.tagName = tagName;
- tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
- skipWhitespace();
- return finishNode(tag);
+ // Do not include a trailing namespace separator in the token, since this is against the spec.
+ if (tokenValue.slice(-1) === ":") {
+ tokenValue = tokenValue.slice(0, -1);
+ pos--;
}
- function parseTypedefTag(start, tagName, indent) {
- var typeExpression = tryParseTypeExpression();
- skipWhitespaceOrAsterisk();
- var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
- typedefTag.tagName = tagName;
- typedefTag.fullName = parseJSDocTypeNameWithNamespace();
- typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
- skipWhitespace();
- typedefTag.comment = parseTagComments(indent);
- typedefTag.typeExpression = typeExpression;
- var end;
- if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var child = void 0;
- var jsdocTypeLiteral = void 0;
- var childTypeTag = void 0;
- while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
- if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
- }
- if (child.kind === 320 /* JSDocTypeTag */) {
- if (childTypeTag) {
- break;
- }
- else {
- childTypeTag = child;
- }
- }
- else {
- jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
- }
- }
- if (jsdocTypeLiteral) {
- if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
- jsdocTypeLiteral.isArrayType = true;
- }
- typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
- childTypeTag.typeExpression :
- finishNode(jsdocTypeLiteral);
- end = typedefTag.typeExpression.end;
- }
+ }
+ return token;
+ }
+ function scanJsxAttributeValue() {
+ startPos = pos;
+ switch (text.charCodeAt(pos)) {
+ case 34 /* doubleQuote */:
+ case 39 /* singleQuote */:
+ tokenValue = scanString(/*jsxAttributeString*/ true);
+ return token = 10 /* StringLiteral */;
+ default:
+ // If this scans anything other than `{`, it's a parse error.
+ return scan();
+ }
+ }
+ function reScanJsxAttributeValue() {
+ pos = tokenPos = startPos;
+ return scanJsxAttributeValue();
+ }
+ function scanJsDocToken() {
+ startPos = tokenPos = pos;
+ tokenFlags = 0 /* None */;
+ if (pos >= end) {
+ return token = 1 /* EndOfFileToken */;
+ }
+ var ch = codePointAt(text, pos);
+ pos += charSize(ch);
+ switch (ch) {
+ case 9 /* tab */:
+ case 11 /* verticalTab */:
+ case 12 /* formFeed */:
+ case 32 /* space */:
+ while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
+ pos++;
}
- // 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) {
- var pos = scanner.getTokenPos();
- if (!ts.tokenIsIdentifierOrKeyword(token())) {
- return undefined;
+ return token = 5 /* WhitespaceTrivia */;
+ case 64 /* at */:
+ return token = 59 /* AtToken */;
+ case 13 /* carriageReturn */:
+ if (text.charCodeAt(pos) === 10 /* lineFeed */) {
+ pos++;
}
- var typeNameOrNamespaceName = parseJSDocIdentifierName();
- if (parseOptional(24 /* DotToken */)) {
- var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
- if (nested) {
- jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
- }
- jsDocNamespaceNode.name = typeNameOrNamespaceName;
- jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
- return finishNode(jsDocNamespaceNode);
+ // falls through
+ case 10 /* lineFeed */:
+ tokenFlags |= 1 /* PrecedingLineBreak */;
+ return token = 4 /* NewLineTrivia */;
+ case 42 /* asterisk */:
+ return token = 41 /* AsteriskToken */;
+ case 123 /* openBrace */:
+ return token = 18 /* OpenBraceToken */;
+ case 125 /* closeBrace */:
+ return token = 19 /* CloseBraceToken */;
+ case 91 /* openBracket */:
+ return token = 22 /* OpenBracketToken */;
+ case 93 /* closeBracket */:
+ return token = 23 /* CloseBracketToken */;
+ case 60 /* lessThan */:
+ return token = 29 /* LessThanToken */;
+ case 62 /* greaterThan */:
+ return token = 31 /* GreaterThanToken */;
+ case 61 /* equals */:
+ return token = 63 /* EqualsToken */;
+ case 44 /* comma */:
+ return token = 27 /* CommaToken */;
+ case 46 /* dot */:
+ return token = 24 /* DotToken */;
+ case 96 /* backtick */:
+ return token = 61 /* BacktickToken */;
+ case 35 /* hash */:
+ return token = 62 /* HashToken */;
+ case 92 /* backslash */:
+ pos--;
+ var extendedCookedChar = peekExtendedUnicodeEscape();
+ if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
+ pos += 3;
+ tokenFlags |= 8 /* ExtendedUnicodeEscape */;
+ tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
+ return token = getIdentifierToken();
}
- if (nested) {
- typeNameOrNamespaceName.isInJSDocNamespace = true;
+ var cookedChar = peekUnicodeEscape();
+ if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
+ pos += 6;
+ tokenFlags |= 1024 /* UnicodeEscape */;
+ tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
+ return token = getIdentifierToken();
}
- return typeNameOrNamespaceName;
+ pos++;
+ return token = 0 /* Unknown */;
+ }
+ if (isIdentifierStart(ch, languageVersion)) {
+ var char = ch;
+ while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
+ pos += charSize(char);
+ tokenValue = text.substring(tokenPos, pos);
+ if (char === 92 /* backslash */) {
+ tokenValue += scanIdentifierParts();
+ }
+ return token = getIdentifierToken();
+ }
+ else {
+ return token = 0 /* Unknown */;
+ }
+ }
+ function speculationHelper(callback, isLookahead) {
+ var savePos = pos;
+ var saveStartPos = startPos;
+ var saveTokenPos = tokenPos;
+ var saveToken = token;
+ 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;
+ tokenPos = saveTokenPos;
+ token = saveToken;
+ tokenValue = saveTokenValue;
+ tokenFlags = saveTokenFlags;
+ }
+ return result;
+ }
+ function scanRange(start, length, callback) {
+ var saveEnd = end;
+ var savePos = pos;
+ var saveStartPos = startPos;
+ var saveTokenPos = tokenPos;
+ var saveToken = token;
+ var saveTokenValue = tokenValue;
+ var saveTokenFlags = tokenFlags;
+ var saveErrorExpectations = commentDirectives;
+ setText(text, start, length);
+ var result = callback();
+ end = saveEnd;
+ pos = savePos;
+ startPos = saveStartPos;
+ tokenPos = saveTokenPos;
+ token = saveToken;
+ tokenValue = saveTokenValue;
+ tokenFlags = saveTokenFlags;
+ commentDirectives = saveErrorExpectations;
+ return result;
+ }
+ function lookAhead(callback) {
+ return speculationHelper(callback, /*isLookahead*/ true);
+ }
+ function tryScan(callback) {
+ return speculationHelper(callback, /*isLookahead*/ false);
+ }
+ function getText() {
+ return text;
+ }
+ function clearCommentDirectives() {
+ commentDirectives = undefined;
+ }
+ function setText(newText, start, length) {
+ text = newText || "";
+ end = length === undefined ? text.length : start + length;
+ setTextPos(start || 0);
+ }
+ function setOnError(errorCallback) {
+ onError = errorCallback;
+ }
+ function setScriptTarget(scriptTarget) {
+ languageVersion = scriptTarget;
+ }
+ function setLanguageVariant(variant) {
+ languageVariant = variant;
+ }
+ function setTextPos(textPos) {
+ ts.Debug.assert(textPos >= 0);
+ pos = textPos;
+ startPos = textPos;
+ tokenPos = textPos;
+ token = 0 /* Unknown */;
+ tokenValue = undefined;
+ tokenFlags = 0 /* None */;
+ }
+ function setInJSDocType(inType) {
+ inJSDocType += inType ? 1 : -1;
+ }
+ }
+ ts.createScanner = createScanner;
+ /* @internal */
+ var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
+ // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
+ var size = str.length;
+ // Account for out-of-bounds indices:
+ if (i < 0 || i >= size) {
+ return undefined; // String.codePointAt returns `undefined` for OOB indexes
+ }
+ // Get the first code unit
+ var first = str.charCodeAt(i);
+ // check if itâs the start of a surrogate pair
+ if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
+ var second = str.charCodeAt(i + 1);
+ if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
+ // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+ return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+ }
+ }
+ return first;
+ };
+ /* @internal */
+ function charSize(ch) {
+ if (ch >= 0x10000) {
+ return 2;
+ }
+ return 1;
+ }
+ // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
+ function utf16EncodeAsStringFallback(codePoint) {
+ ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
+ if (codePoint <= 65535) {
+ return String.fromCharCode(codePoint);
+ }
+ var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
+ var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
+ return String.fromCharCode(codeUnit1, codeUnit2);
+ }
+ var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
+ /* @internal */
+ function utf16EncodeAsString(codePoint) {
+ return utf16EncodeAsStringWorker(codePoint);
+ }
+ ts.utf16EncodeAsString = utf16EncodeAsString;
+})(ts || (ts = {}));
+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;
+ function sortAndDeduplicateDiagnostics(diagnostics) {
+ return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
+ }
+ ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
+ function getDefaultLibFileName(options) {
+ switch (ts.getEmitScriptTarget(options)) {
+ case 99 /* ESNext */:
+ return "lib.esnext.full.d.ts";
+ case 8 /* ES2021 */:
+ return "lib.es2021.full.d.ts";
+ case 7 /* ES2020 */:
+ return "lib.es2020.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
+ case 5 /* ES2018 */:
+ return "lib.es2018.full.d.ts";
+ case 4 /* ES2017 */:
+ return "lib.es2017.full.d.ts";
+ case 3 /* ES2016 */:
+ return "lib.es2016.full.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";
+ }
+ }
+ ts.getDefaultLibFileName = getDefaultLibFileName;
+ function textSpanEnd(span) {
+ return span.start + span.length;
+ }
+ ts.textSpanEnd = textSpanEnd;
+ function textSpanIsEmpty(span) {
+ return span.length === 0;
+ }
+ ts.textSpanIsEmpty = textSpanIsEmpty;
+ function textSpanContainsPosition(span, position) {
+ return position >= span.start && position < textSpanEnd(span);
+ }
+ ts.textSpanContainsPosition = textSpanContainsPosition;
+ /* @internal */
+ function textRangeContainsPositionInclusive(span, position) {
+ return position >= span.pos && position <= span.end;
+ }
+ ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
+ // Returns true if 'span' contains 'other'.
+ function textSpanContainsTextSpan(span, other) {
+ return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
+ }
+ ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
+ function textSpanOverlapsWith(span, other) {
+ return textSpanOverlap(span, other) !== undefined;
+ }
+ ts.textSpanOverlapsWith = textSpanOverlapsWith;
+ function textSpanOverlap(span1, span2) {
+ var overlap = textSpanIntersection(span1, span2);
+ return overlap && overlap.length === 0 ? undefined : overlap;
+ }
+ ts.textSpanOverlap = textSpanOverlap;
+ function textSpanIntersectsWithTextSpan(span, other) {
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
+ }
+ ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
+ function textSpanIntersectsWith(span, start, length) {
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
+ }
+ ts.textSpanIntersectsWith = textSpanIntersectsWith;
+ function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
+ var end1 = start1 + length1;
+ var end2 = start2 + length2;
+ return start2 <= end1 && end2 >= start1;
+ }
+ ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
+ function textSpanIntersectsWithPosition(span, position) {
+ return position <= textSpanEnd(span) && position >= span.start;
+ }
+ ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
+ function textSpanIntersection(span1, span2) {
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
+ }
+ ts.textSpanIntersection = textSpanIntersection;
+ function createTextSpan(start, length) {
+ if (start < 0) {
+ throw new Error("start < 0");
+ }
+ if (length < 0) {
+ throw new Error("length < 0");
+ }
+ return { start: start, length: length };
+ }
+ ts.createTextSpan = createTextSpan;
+ function createTextSpanFromBounds(start, end) {
+ return createTextSpan(start, end - start);
+ }
+ ts.createTextSpanFromBounds = createTextSpanFromBounds;
+ function textChangeRangeNewSpan(range) {
+ return createTextSpan(range.span.start, range.newLength);
+ }
+ ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
+ function textChangeRangeIsUnchanged(range) {
+ return textSpanIsEmpty(range.span) && range.newLength === 0;
+ }
+ ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
+ function createTextChangeRange(span, newLength) {
+ if (newLength < 0) {
+ throw new Error("newLength < 0");
+ }
+ return { span: span, newLength: newLength };
+ }
+ ts.createTextChangeRange = createTextChangeRange;
+ ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
+ /**
+ * 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;
+ }
+ 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;
+ var oldStart2 = nextChange.span.start;
+ var oldEnd2 = textSpanEnd(nextChange.span);
+ var newEnd2 = oldStart2 + nextChange.newLength;
+ oldStartN = Math.min(oldStart1, oldStart2);
+ oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
+ newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
+ }
+ return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
+ }
+ ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
+ function getTypeParameterOwner(d) {
+ if (d && d.kind === 162 /* TypeParameter */) {
+ for (var current = d; current; current = current.parent) {
+ if (isFunctionLike(current) || isClassLike(current) || current.kind === 257 /* InterfaceDeclaration */) {
+ return current;
}
- function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
- callbackTag.tagName = tagName;
- callbackTag.fullName = parseJSDocTypeNameWithNamespace();
- callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
- skipWhitespace();
- callbackTag.comment = parseTagComments(indent);
- var child;
- var jsdocSignature = createNode(305 /* JSDocSignature */, start);
- jsdocSignature.parameters = [];
- while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
- jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
- }
- var returnTag = tryParse(function () {
- if (parseOptionalJsdoc(59 /* AtToken */)) {
- var tag = parseTag(indent);
- if (tag && tag.kind === 318 /* JSDocReturnTag */) {
- return tag;
- }
- }
- });
- if (returnTag) {
- jsdocSignature.type = returnTag;
- }
- callbackTag.typeExpression = finishNode(jsdocSignature);
- return finishNode(callbackTag);
+ }
+ }
+ }
+ ts.getTypeParameterOwner = getTypeParameterOwner;
+ function isParameterPropertyDeclaration(node, parent) {
+ return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 170 /* Constructor */;
+ }
+ ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
+ function isEmptyBindingPattern(node) {
+ if (isBindingPattern(node)) {
+ return ts.every(node.elements, isEmptyBindingElement);
+ }
+ return false;
+ }
+ ts.isEmptyBindingPattern = isEmptyBindingPattern;
+ function isEmptyBindingElement(node) {
+ if (ts.isOmittedExpression(node)) {
+ return true;
+ }
+ return isEmptyBindingPattern(node.name);
+ }
+ ts.isEmptyBindingElement = isEmptyBindingElement;
+ function walkUpBindingElementsAndPatterns(binding) {
+ var node = binding.parent;
+ while (ts.isBindingElement(node.parent)) {
+ node = node.parent.parent;
+ }
+ return node.parent;
+ }
+ ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
+ function getCombinedFlags(node, getFlags) {
+ if (ts.isBindingElement(node)) {
+ node = walkUpBindingElementsAndPatterns(node);
+ }
+ var flags = getFlags(node);
+ if (node.kind === 253 /* VariableDeclaration */) {
+ node = node.parent;
+ }
+ if (node && node.kind === 254 /* VariableDeclarationList */) {
+ flags |= getFlags(node);
+ node = node.parent;
+ }
+ if (node && node.kind === 236 /* VariableStatement */) {
+ flags |= getFlags(node);
+ }
+ return flags;
+ }
+ function getCombinedModifierFlags(node) {
+ return getCombinedFlags(node, ts.getEffectiveModifierFlags);
+ }
+ ts.getCombinedModifierFlags = getCombinedModifierFlags;
+ /* @internal */
+ function getCombinedNodeFlagsAlwaysIncludeJSDoc(node) {
+ return getCombinedFlags(node, ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc);
+ }
+ ts.getCombinedNodeFlagsAlwaysIncludeJSDoc = getCombinedNodeFlagsAlwaysIncludeJSDoc;
+ // 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 stored 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) {
+ return getCombinedFlags(node, function (n) { return n.flags; });
+ }
+ ts.getCombinedNodeFlags = getCombinedNodeFlags;
+ /* @internal */
+ ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"];
+ /**
+ * 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 lowerCaseLocale = locale.toLowerCase();
+ var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale);
+ if (!matchResult) {
+ if (errors) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
+ }
+ return;
+ }
+ 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 (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, 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());
+ var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
+ var filePath = ts.combinePaths(containingDirectoryPath, language);
+ if (territory) {
+ filePath = filePath + "-" + territory;
+ }
+ filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
+ if (!sys.fileExists(filePath)) {
+ return false;
+ }
+ // TODO: Add codePage support for readFile?
+ var fileContents = "";
+ try {
+ fileContents = sys.readFile(filePath);
+ }
+ catch (e) {
+ if (errors) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
}
- function getJSDocTypeAliasName(fullName) {
- if (fullName) {
- var rightNode = fullName;
- while (true) {
- if (ts.isIdentifier(rightNode) || !rightNode.body) {
- return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
- }
- rightNode = rightNode.body;
- }
- }
+ return false;
+ }
+ try {
+ // this is a global mutation (or live binding update)!
+ ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
+ }
+ catch (_a) {
+ if (errors) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
}
- function escapedTextsEqual(a, b) {
- while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
- if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
- a = a.left;
- b = b.left;
- }
- else {
- return false;
- }
- }
- return a.escapedText === b.escapedText;
+ return false;
+ }
+ return true;
+ }
+ }
+ ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
+ function getOriginalNode(node, nodeTest) {
+ if (node) {
+ while (node.original !== undefined) {
+ node = node.original;
+ }
+ }
+ return !nodeTest || nodeTest(node) ? node : undefined;
+ }
+ ts.getOriginalNode = getOriginalNode;
+ function findAncestor(node, callback) {
+ while (node) {
+ var result = callback(node);
+ if (result === "quit") {
+ return undefined;
+ }
+ else if (result) {
+ return node;
+ }
+ node = node.parent;
+ }
+ return undefined;
+ }
+ ts.findAncestor = findAncestor;
+ /**
+ * 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 /* Synthesized */) === 0;
+ }
+ ts.isParseTreeNode = isParseTreeNode;
+ function getParseTreeNode(node, nodeTest) {
+ if (node === undefined || isParseTreeNode(node)) {
+ return node;
+ }
+ node = node.original;
+ while (node) {
+ if (isParseTreeNode(node)) {
+ return !nodeTest || nodeTest(node) ? node : undefined;
+ }
+ node = node.original;
+ }
+ }
+ ts.getParseTreeNode = getParseTreeNode;
+ /** 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);
+ }
+ ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
+ /**
+ * 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;
+ }
+ ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
+ function idText(identifierOrPrivateName) {
+ return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
+ }
+ ts.idText = idText;
+ function symbolName(symbol) {
+ if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) {
+ return idText(symbol.valueDeclaration.name);
+ }
+ return unescapeLeadingUnderscores(symbol.escapedName);
+ }
+ ts.symbolName = symbolName;
+ /**
+ * 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 (isDeclaration(hostNode)) {
+ return getDeclarationIdentifier(hostNode);
+ }
+ // Covers remaining cases (returning undefined if none match).
+ switch (hostNode.kind) {
+ case 236 /* VariableStatement */:
+ if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
+ return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
}
- function parseChildPropertyTag(indent) {
- return parseChildParameterOrPropertyTag(1 /* Property */, indent);
+ break;
+ case 237 /* ExpressionStatement */:
+ var expr = hostNode.expression;
+ if (expr.kind === 220 /* BinaryExpression */ && expr.operatorToken.kind === 63 /* EqualsToken */) {
+ expr = expr.left;
}
- function parseChildParameterOrPropertyTag(target, indent, name) {
- var canParseTag = true;
- var seenAsterisk = false;
- while (true) {
- switch (nextTokenJSDoc()) {
- case 59 /* AtToken */:
- if (canParseTag) {
- var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
- target !== 4 /* CallbackParameter */ &&
- name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
- return false;
- }
- return child;
- }
- seenAsterisk = false;
- break;
- case 4 /* NewLineTrivia */:
- canParseTag = true;
- seenAsterisk = false;
- break;
- case 41 /* AsteriskToken */:
- if (seenAsterisk) {
- canParseTag = false;
- }
- seenAsterisk = true;
- break;
- case 75 /* Identifier */:
- canParseTag = false;
- break;
- case 1 /* EndOfFileToken */:
- return false;
+ switch (expr.kind) {
+ case 205 /* PropertyAccessExpression */:
+ return expr.name;
+ case 206 /* ElementAccessExpression */:
+ var arg = expr.argumentExpression;
+ if (ts.isIdentifier(arg)) {
+ return arg;
}
- }
- }
- function tryParseChildTag(target, indent) {
- ts.Debug.assert(token() === 59 /* AtToken */);
- var start = scanner.getStartPos();
- nextTokenJSDoc();
- var tagName = parseJSDocIdentifierName();
- skipWhitespace();
- var t;
- switch (tagName.escapedText) {
- case "type":
- return target === 1 /* Property */ && parseTypeTag(start, tagName);
- case "prop":
- case "property":
- t = 1 /* Property */;
- break;
- case "arg":
- case "argument":
- case "param":
- t = 2 /* Parameter */ | 4 /* CallbackParameter */;
- break;
- default:
- return false;
- }
- if (!(target & t)) {
- return false;
- }
- return parseParameterOrPropertyTag(start, tagName, target, indent);
}
- function parseTemplateTag(start, tagName) {
- // the template tag looks like '@template {Constraint} T,U,V'
- var constraint;
- if (token() === 18 /* OpenBraceToken */) {
- constraint = parseJSDocTypeExpression();
- }
- var typeParameters = [];
- var typeParametersPos = getNodePos();
- do {
- skipWhitespace();
- var typeParameter = createNode(155 /* TypeParameter */);
- typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
- finishNode(typeParameter);
- skipWhitespaceOrAsterisk();
- typeParameters.push(typeParameter);
- } while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(321 /* JSDocTemplateTag */, start);
- result.tagName = tagName;
- result.constraint = constraint;
- result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
- finishNode(result);
- return result;
+ break;
+ case 211 /* ParenthesizedExpression */: {
+ return getDeclarationIdentifier(hostNode.expression);
+ }
+ case 249 /* LabeledStatement */: {
+ if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
+ return getDeclarationIdentifier(hostNode.statement);
}
- function parseOptionalJsdoc(t) {
- if (token() === t) {
- nextTokenJSDoc();
- return true;
- }
- return false;
+ break;
+ }
+ }
+ }
+ function getDeclarationIdentifier(node) {
+ var name = getNameOfDeclaration(node);
+ return name && ts.isIdentifier(name) ? name : undefined;
+ }
+ /** @internal */
+ function nodeHasName(statement, name) {
+ if (isNamedDeclaration(statement) && ts.isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
+ return true;
+ }
+ if (ts.isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
+ return true;
+ }
+ return false;
+ }
+ ts.nodeHasName = nodeHasName;
+ function getNameOfJSDocTypedef(declaration) {
+ return declaration.name || nameForNamelessJSDocTypedef(declaration);
+ }
+ ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
+ /** @internal */
+ function isNamedDeclaration(node) {
+ return !!node.name; // A 'name' property should always be a DeclarationName.
+ }
+ ts.isNamedDeclaration = isNamedDeclaration;
+ /** @internal */
+ function getNonAssignedNameOfDeclaration(declaration) {
+ switch (declaration.kind) {
+ case 79 /* Identifier */:
+ return declaration;
+ case 345 /* JSDocPropertyTag */:
+ case 338 /* JSDocParameterTag */: {
+ var name = declaration.name;
+ if (name.kind === 160 /* QualifiedName */) {
+ return name.right;
}
- function parseJSDocEntityName() {
- var entity = parseJSDocIdentifierName();
- if (parseOptional(22 /* OpenBracketToken */)) {
- parseExpected(23 /* 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(24 /* DotToken */)) {
- var name = parseJSDocIdentifierName();
- if (parseOptional(22 /* OpenBracketToken */)) {
- parseExpected(23 /* CloseBracketToken */);
- }
- entity = createQualifiedName(entity, name);
- }
- return entity;
+ break;
+ }
+ case 207 /* CallExpression */:
+ case 220 /* BinaryExpression */: {
+ var expr_1 = declaration;
+ switch (ts.getAssignmentDeclarationKind(expr_1)) {
+ case 1 /* ExportsProperty */:
+ case 4 /* ThisProperty */:
+ case 5 /* Property */:
+ case 3 /* PrototypeProperty */:
+ return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
+ case 7 /* ObjectDefinePropertyValue */:
+ case 8 /* ObjectDefinePropertyExports */:
+ case 9 /* ObjectDefinePrototypeProperty */:
+ return expr_1.arguments[1];
+ default:
+ return undefined;
}
- function parseJSDocIdentifierName(message) {
- if (!ts.tokenIsIdentifierOrKeyword(token())) {
- return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
- }
- identifierCount++;
- var pos = scanner.getTokenPos();
- var end = scanner.getTextPos();
- var result = createNode(75 /* Identifier */, pos);
- if (token() !== 75 /* Identifier */) {
- result.originalKeywordKind = token();
- }
- result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
- finishNode(result, end);
- nextTokenJSDoc();
- return result;
+ }
+ case 343 /* JSDocTypedefTag */:
+ return getNameOfJSDocTypedef(declaration);
+ case 337 /* JSDocEnumTag */:
+ return nameForNamelessJSDocTypedef(declaration);
+ case 270 /* ExportAssignment */: {
+ var expression = declaration.expression;
+ return ts.isIdentifier(expression) ? expression : undefined;
+ }
+ case 206 /* ElementAccessExpression */:
+ var expr = declaration;
+ if (ts.isBindableStaticElementAccessExpression(expr)) {
+ return expr.argumentExpression;
}
+ }
+ return declaration.name;
+ }
+ ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
+ function getNameOfDeclaration(declaration) {
+ if (declaration === undefined)
+ return undefined;
+ return getNonAssignedNameOfDeclaration(declaration) ||
+ (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
+ }
+ ts.getNameOfDeclaration = getNameOfDeclaration;
+ /*@internal*/
+ function getAssignedName(node) {
+ if (!node.parent) {
+ return undefined;
+ }
+ else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
+ return node.parent.name;
+ }
+ else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
+ if (ts.isIdentifier(node.parent.left)) {
+ return node.parent.left;
}
- })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
- })(Parser || (Parser = {}));
- var IncrementalParser;
- (function (IncrementalParser) {
- function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
- 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;
+ else if (ts.isAccessExpression(node.parent.left)) {
+ return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
}
- if (sourceFile.statements.length === 0) {
- // If we don't have any statements in the current source file, then there's no real
- // way to incrementally parse. So just do a full parse instead.
- return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
+ }
+ else if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
+ return node.parent.name;
+ }
+ }
+ ts.getAssignedName = getAssignedName;
+ function getJSDocParameterTagsWorker(param, noCache) {
+ if (param.name) {
+ if (ts.isIdentifier(param.name)) {
+ var name_1 = param.name.escapedText;
+ return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
}
- // 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);
- // 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);
- result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
- return result;
+ else {
+ var i = param.parent.parameters.indexOf(param);
+ ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
+ var paramTags = getJSDocTagsWorker(param.parent, noCache).filter(ts.isJSDocParameterTag);
+ if (i < paramTags.length) {
+ return [paramTags[i]];
+ }
+ }
+ }
+ // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
+ return ts.emptyArray;
+ }
+ /**
+ * Gets the JSDoc parameter tags for the node if present.
+ *
+ * @remarks Returns any JSDoc param tag whose name 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.
+ *
+ * For binding patterns, parameter tags are matched by position.
+ */
+ function getJSDocParameterTags(param) {
+ return getJSDocParameterTagsWorker(param, /*noCache*/ false);
+ }
+ ts.getJSDocParameterTags = getJSDocParameterTags;
+ /* @internal */
+ function getJSDocParameterTagsNoCache(param) {
+ return getJSDocParameterTagsWorker(param, /*noCache*/ true);
+ }
+ ts.getJSDocParameterTagsNoCache = getJSDocParameterTagsNoCache;
+ function getJSDocTypeParameterTagsWorker(param, noCache) {
+ var name = param.name.escapedText;
+ return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) {
+ return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
+ });
+ }
+ /**
+ * Gets the JSDoc type parameter tags for the node if present.
+ *
+ * @remarks Returns any JSDoc template tag whose names match the provided
+ * parameter, whether a template tag on a containing function
+ * expression, or a template 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 template
+ * tag on the containing function expression would be first.
+ */
+ function getJSDocTypeParameterTags(param) {
+ return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
+ }
+ ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
+ /* @internal */
+ function getJSDocTypeParameterTagsNoCache(param) {
+ return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
+ }
+ ts.getJSDocTypeParameterTagsNoCache = getJSDocTypeParameterTagsNoCache;
+ /**
+ * 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 implements tags for the node if present */
+ function getJSDocImplementsTags(node) {
+ return getAllJSDocTags(node, ts.isJSDocImplementsTag);
+ }
+ ts.getJSDocImplementsTags = getJSDocImplementsTags;
+ /** Gets the JSDoc class tag for the node if present */
+ function getJSDocClassTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocClassTag);
+ }
+ ts.getJSDocClassTag = getJSDocClassTag;
+ /** Gets the JSDoc public tag for the node if present */
+ function getJSDocPublicTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocPublicTag);
+ }
+ ts.getJSDocPublicTag = getJSDocPublicTag;
+ /*@internal*/
+ function getJSDocPublicTagNoCache(node) {
+ return getFirstJSDocTag(node, ts.isJSDocPublicTag, /*noCache*/ true);
+ }
+ ts.getJSDocPublicTagNoCache = getJSDocPublicTagNoCache;
+ /** Gets the JSDoc private tag for the node if present */
+ function getJSDocPrivateTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocPrivateTag);
+ }
+ ts.getJSDocPrivateTag = getJSDocPrivateTag;
+ /*@internal*/
+ function getJSDocPrivateTagNoCache(node) {
+ return getFirstJSDocTag(node, ts.isJSDocPrivateTag, /*noCache*/ true);
+ }
+ ts.getJSDocPrivateTagNoCache = getJSDocPrivateTagNoCache;
+ /** Gets the JSDoc protected tag for the node if present */
+ function getJSDocProtectedTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocProtectedTag);
+ }
+ ts.getJSDocProtectedTag = getJSDocProtectedTag;
+ /*@internal*/
+ function getJSDocProtectedTagNoCache(node) {
+ return getFirstJSDocTag(node, ts.isJSDocProtectedTag, /*noCache*/ true);
+ }
+ ts.getJSDocProtectedTagNoCache = getJSDocProtectedTagNoCache;
+ /** Gets the JSDoc protected tag for the node if present */
+ function getJSDocReadonlyTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocReadonlyTag);
+ }
+ ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
+ /*@internal*/
+ function getJSDocReadonlyTagNoCache(node) {
+ return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true);
+ }
+ ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache;
+ function getJSDocOverrideTagNoCache(node) {
+ return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true);
+ }
+ ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache;
+ /** Gets the JSDoc deprecated tag for the node if present */
+ function getJSDocDeprecatedTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag);
+ }
+ ts.getJSDocDeprecatedTag = getJSDocDeprecatedTag;
+ /*@internal */
+ function getJSDocDeprecatedTagNoCache(node) {
+ return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag, /*noCache*/ true);
+ }
+ ts.getJSDocDeprecatedTagNoCache = getJSDocDeprecatedTagNoCache;
+ /** Gets the JSDoc enum tag for the node if present */
+ function getJSDocEnumTag(node) {
+ return getFirstJSDocTag(node, ts.isJSDocEnumTag);
+ }
+ ts.getJSDocEnumTag = getJSDocEnumTag;
+ /** 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;
+ }
+ 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)) {
+ tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
+ }
+ return tag && tag.typeExpression && tag.typeExpression.type;
+ }
+ ts.getJSDocType = getJSDocType;
+ /**
+ * Gets the return type node for the node if provided via JSDoc return tag or type tag.
+ *
+ * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
+ * gets the type from inside the braces, after the fat arrow, etc.
+ */
+ function getJSDocReturnType(node) {
+ var returnTag = getJSDocReturnTag(node);
+ if (returnTag && returnTag.typeExpression) {
+ return returnTag.typeExpression.type;
+ }
+ var typeTag = getJSDocTypeTag(node);
+ if (typeTag && typeTag.typeExpression) {
+ var type = typeTag.typeExpression.type;
+ if (ts.isTypeLiteralNode(type)) {
+ var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
+ return sig && sig.type;
+ }
+ if (ts.isFunctionTypeNode(type) || ts.isJSDocFunctionType(type)) {
+ return type.type;
+ }
+ }
+ }
+ ts.getJSDocReturnType = getJSDocReturnType;
+ function getJSDocTagsWorker(node, noCache) {
+ 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 || noCache) {
+ var comments = ts.getJSDocCommentsAndTags(node, noCache);
+ ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
+ tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
+ if (!noCache) {
+ node.jsDocCache = tags;
+ }
+ }
+ return tags;
+ }
+ /** Get all JSDoc tags related to a node, including those on parent nodes. */
+ function getJSDocTags(node) {
+ return getJSDocTagsWorker(node, /*noCache*/ false);
+ }
+ ts.getJSDocTags = getJSDocTags;
+ /* @internal */
+ function getJSDocTagsNoCache(node) {
+ return getJSDocTagsWorker(node, /*noCache*/ true);
+ }
+ ts.getJSDocTagsNoCache = getJSDocTagsNoCache;
+ /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
+ function getFirstJSDocTag(node, predicate, noCache) {
+ return ts.find(getJSDocTagsWorker(node, noCache), predicate);
+ }
+ /** Gets all JSDoc tags that match a specified predicate */
+ function getAllJSDocTags(node, predicate) {
+ return getJSDocTags(node).filter(predicate);
+ }
+ ts.getAllJSDocTags = getAllJSDocTags;
+ /** Gets all JSDoc tags of a specified kind */
+ function getAllJSDocTagsOfKind(node, kind) {
+ return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
+ }
+ ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
+ /** Gets the text of a jsdoc comment, flattening links to their text. */
+ function getTextOfJSDocComment(comment) {
+ return typeof comment === "string" ? comment
+ : comment === null || comment === void 0 ? void 0 : comment.map(function (c) {
+ // TODO: Other kinds here
+ return c.kind === 319 /* JSDocText */ ? c.text : "{@link ".concat(c.name ? ts.entityNameToString(c.name) + " " : "").concat(c.text, "}");
+ }).join("");
+ }
+ ts.getTextOfJSDocComment = getTextOfJSDocComment;
+ /**
+ * 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 (ts.isJSDocTypeAlias(node)) {
+ ts.Debug.assert(node.parent.kind === 318 /* JSDocComment */);
+ return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
+ }
+ if (node.typeParameters) {
+ return node.typeParameters;
+ }
+ if (ts.isInJSFile(node)) {
+ var decls = ts.getJSDocTypeParameterDeclarations(node);
+ if (decls.length) {
+ return decls;
+ }
+ var typeTag = getJSDocType(node);
+ if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
+ return typeTag.typeParameters;
+ }
+ }
+ return ts.emptyArray;
+ }
+ ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
+ function getEffectiveConstraintOfTypeParameter(node) {
+ return node.constraint ? node.constraint :
+ ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
+ undefined;
+ }
+ ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
+ // #region
+ function isMemberName(node) {
+ return node.kind === 79 /* Identifier */ || node.kind === 80 /* PrivateIdentifier */;
+ }
+ ts.isMemberName = isMemberName;
+ /* @internal */
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 172 /* SetAccessor */ || node.kind === 171 /* GetAccessor */;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
+ function isPropertyAccessChain(node) {
+ return ts.isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
+ }
+ ts.isPropertyAccessChain = isPropertyAccessChain;
+ function isElementAccessChain(node) {
+ return ts.isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
+ }
+ ts.isElementAccessChain = isElementAccessChain;
+ function isCallChain(node) {
+ return ts.isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
+ }
+ ts.isCallChain = isCallChain;
+ function isOptionalChain(node) {
+ var kind = node.kind;
+ return !!(node.flags & 32 /* OptionalChain */) &&
+ (kind === 205 /* PropertyAccessExpression */
+ || kind === 206 /* ElementAccessExpression */
+ || kind === 207 /* CallExpression */
+ || kind === 229 /* NonNullExpression */);
+ }
+ ts.isOptionalChain = isOptionalChain;
+ /* @internal */
+ function isOptionalChainRoot(node) {
+ return isOptionalChain(node) && !ts.isNonNullExpression(node) && !!node.questionDotToken;
+ }
+ ts.isOptionalChainRoot = isOptionalChainRoot;
+ /**
+ * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
+ */
+ /* @internal */
+ function isExpressionOfOptionalChainRoot(node) {
+ return isOptionalChainRoot(node.parent) && node.parent.expression === node;
+ }
+ ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
+ /**
+ * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
+ *
+ * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
+ * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
+ * 3. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain)
+ * 4. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is
+ * the end of the chain starting at `c?.`)
+ * 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is
+ * the end of the chain starting at `a?.`)
+ */
+ /* @internal */
+ function isOutermostOptionalChain(node) {
+ return !isOptionalChain(node.parent) // cases 1, 2, and 3
+ || isOptionalChainRoot(node.parent) // case 4
+ || node !== node.parent.expression; // case 5
+ }
+ ts.isOutermostOptionalChain = isOutermostOptionalChain;
+ function isNullishCoalesce(node) {
+ return node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
+ }
+ ts.isNullishCoalesce = isNullishCoalesce;
+ function isConstTypeReference(node) {
+ return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
+ function skipPartiallyEmittedExpressions(node) {
+ return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
+ }
+ ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
+ function isNonNullChain(node) {
+ return ts.isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
+ }
+ ts.isNonNullChain = isNonNullChain;
+ function isBreakOrContinueStatement(node) {
+ return node.kind === 245 /* BreakStatement */ || node.kind === 244 /* ContinueStatement */;
+ }
+ ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
+ function isNamedExportBindings(node) {
+ return node.kind === 273 /* NamespaceExport */ || node.kind === 272 /* NamedExports */;
+ }
+ ts.isNamedExportBindings = isNamedExportBindings;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 300 /* UnparsedText */:
+ case 301 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 298 /* UnparsedPrologue */ ||
+ node.kind === 302 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
+ function isJSDocPropertyLikeTag(node) {
+ return node.kind === 345 /* JSDocPropertyTag */ || node.kind === 338 /* JSDocParameterTag */;
+ }
+ ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
+ // #endregion
+ // #region
+ // Node tests
+ //
+ // All node tests in the following list should *not* reference parent pointers so that
+ // they may be used with transformations.
+ /* @internal */
+ function isNode(node) {
+ return isNodeKind(node.kind);
+ }
+ ts.isNode = isNode;
+ /* @internal */
+ function isNodeKind(kind) {
+ return kind >= 160 /* FirstNode */;
+ }
+ ts.isNodeKind = isNodeKind;
+ /**
+ * True if kind 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 isTokenKind(kind) {
+ return kind >= 0 /* FirstToken */ && kind <= 159 /* LastToken */;
+ }
+ ts.isTokenKind = isTokenKind;
+ /**
+ * 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 isTokenKind(n.kind);
+ }
+ 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 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
+ }
+ ts.isLiteralKind = isLiteralKind;
+ function isLiteralExpression(node) {
+ return isLiteralKind(node.kind);
+ }
+ ts.isLiteralExpression = isLiteralExpression;
+ // Pseudo-literals
+ /* @internal */
+ function isTemplateLiteralKind(kind) {
+ return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
+ }
+ ts.isTemplateLiteralKind = isTemplateLiteralKind;
+ function isTemplateLiteralToken(node) {
+ return isTemplateLiteralKind(node.kind);
+ }
+ ts.isTemplateLiteralToken = isTemplateLiteralToken;
+ function isTemplateMiddleOrTemplateTail(node) {
+ var kind = node.kind;
+ return kind === 16 /* TemplateMiddle */
+ || kind === 17 /* TemplateTail */;
+ }
+ ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
+ function isTypeOnlyImportOrExportDeclaration(node) {
+ switch (node.kind) {
+ case 269 /* ImportSpecifier */:
+ case 274 /* ExportSpecifier */:
+ return node.isTypeOnly || node.parent.parent.isTypeOnly;
+ case 267 /* NamespaceImport */:
+ return node.parent.isTypeOnly;
+ case 266 /* ImportClause */:
+ case 264 /* ImportEqualsDeclaration */:
+ return node.isTypeOnly;
+ default:
+ return false;
+ }
+ }
+ ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
+ function isAssertionKey(node) {
+ return ts.isStringLiteral(node) || ts.isIdentifier(node);
+ }
+ ts.isAssertionKey = isAssertionKey;
+ function isStringTextContainingNode(node) {
+ return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
+ }
+ ts.isStringTextContainingNode = isStringTextContainingNode;
+ // Identifiers
+ /* @internal */
+ function isGeneratedIdentifier(node) {
+ return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
+ }
+ ts.isGeneratedIdentifier = isGeneratedIdentifier;
+ // Private Identifiers
+ /*@internal*/
+ function isPrivateIdentifierClassElementDeclaration(node) {
+ return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name);
+ }
+ ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration;
+ /*@internal*/
+ function isPrivateIdentifierPropertyAccessExpression(node) {
+ return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name);
+ }
+ ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
+ // Keywords
+ /* @internal */
+ function isModifierKind(token) {
+ switch (token) {
+ case 126 /* AbstractKeyword */:
+ case 131 /* AsyncKeyword */:
+ case 85 /* ConstKeyword */:
+ case 135 /* DeclareKeyword */:
+ case 88 /* DefaultKeyword */:
+ case 93 /* ExportKeyword */:
+ case 123 /* PublicKeyword */:
+ case 121 /* PrivateKeyword */:
+ case 122 /* ProtectedKeyword */:
+ case 144 /* ReadonlyKeyword */:
+ case 124 /* StaticKeyword */:
+ case 158 /* OverrideKeyword */:
+ return true;
}
- IncrementalParser.updateSourceFile = updateSourceFile;
- function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
- if (!oldDirectives)
- return newDirectives;
- var commentDirectives;
- var addedNewlyScannedDirectives = false;
- for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
- var directive = oldDirectives_1[_i];
- var range = directive.range, type = directive.type;
- // Range before the change
- if (range.end < changeStart) {
- commentDirectives = ts.append(commentDirectives, directive);
- }
- else if (range.pos > changeRangeOldEnd) {
- addNewlyScannedDirectives();
- // Node is entirely past the change range. We need to move both its pos and
- // end, forward or backward appropriately.
- var updatedDirective = {
- range: { pos: range.pos + delta, end: range.end + delta },
- type: type
- };
- commentDirectives = ts.append(commentDirectives, updatedDirective);
- if (aggressiveChecks) {
- ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
- }
- }
- // Ignore ranges that fall in change range
- }
- addNewlyScannedDirectives();
- return commentDirectives;
- function addNewlyScannedDirectives() {
- if (addedNewlyScannedDirectives)
- return;
- addedNewlyScannedDirectives = true;
- if (!commentDirectives) {
- commentDirectives = newDirectives;
- }
- else if (newDirectives) {
- commentDirectives.push.apply(commentDirectives, newDirectives);
- }
- }
+ return false;
+ }
+ ts.isModifierKind = isModifierKind;
+ /* @internal */
+ function isParameterPropertyModifier(kind) {
+ return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */);
+ }
+ ts.isParameterPropertyModifier = isParameterPropertyModifier;
+ /* @internal */
+ function isClassMemberModifier(idToken) {
+ return isParameterPropertyModifier(idToken) || idToken === 124 /* StaticKeyword */ || idToken === 158 /* OverrideKeyword */;
+ }
+ ts.isClassMemberModifier = isClassMemberModifier;
+ function isModifier(node) {
+ return isModifierKind(node.kind);
+ }
+ ts.isModifier = isModifier;
+ function isEntityName(node) {
+ var kind = node.kind;
+ return kind === 160 /* QualifiedName */
+ || kind === 79 /* Identifier */;
+ }
+ ts.isEntityName = isEntityName;
+ function isPropertyName(node) {
+ var kind = node.kind;
+ return kind === 79 /* Identifier */
+ || kind === 80 /* PrivateIdentifier */
+ || kind === 10 /* StringLiteral */
+ || kind === 8 /* NumericLiteral */
+ || kind === 161 /* ComputedPropertyName */;
+ }
+ ts.isPropertyName = isPropertyName;
+ function isBindingName(node) {
+ var kind = node.kind;
+ return kind === 79 /* Identifier */
+ || kind === 200 /* ObjectBindingPattern */
+ || kind === 201 /* ArrayBindingPattern */;
+ }
+ ts.isBindingName = isBindingName;
+ // Functions
+ function isFunctionLike(node) {
+ return !!node && isFunctionLikeKind(node.kind);
+ }
+ ts.isFunctionLike = isFunctionLike;
+ /* @internal */
+ function isFunctionLikeOrClassStaticBlockDeclaration(node) {
+ return !!node && (isFunctionLikeKind(node.kind) || ts.isClassStaticBlockDeclaration(node));
+ }
+ ts.isFunctionLikeOrClassStaticBlockDeclaration = isFunctionLikeOrClassStaticBlockDeclaration;
+ /* @internal */
+ function isFunctionLikeDeclaration(node) {
+ return node && isFunctionLikeDeclarationKind(node.kind);
+ }
+ ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
+ /* @internal */
+ function isBooleanLiteral(node) {
+ return node.kind === 110 /* TrueKeyword */ || node.kind === 95 /* FalseKeyword */;
+ }
+ ts.isBooleanLiteral = isBooleanLiteral;
+ function isFunctionLikeDeclarationKind(kind) {
+ switch (kind) {
+ case 255 /* FunctionDeclaration */:
+ case 168 /* MethodDeclaration */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ return true;
+ default:
+ return false;
}
- function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
- if (isArray) {
- visitArray(element);
- }
- else {
- visitNode(element);
- }
- return;
- function visitNode(node) {
- var text = "";
- 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;
- }
- node.pos += delta;
- node.end += delta;
- if (aggressiveChecks && shouldCheckNode(node)) {
- ts.Debug.assert(text === newText.substring(node.pos, node.end));
- }
- forEachChild(node, visitNode, visitArray);
- if (ts.hasJSDocNodes(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var jsDocComment = _a[_i];
- visitNode(jsDocComment);
- }
- }
- checkNodePositions(node, aggressiveChecks);
- }
- function visitArray(array) {
- array._children = undefined;
- array.pos += delta;
- array.end += delta;
- for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
- var node = array_8[_i];
- visitNode(node);
- }
- }
+ }
+ /* @internal */
+ function isFunctionLikeKind(kind) {
+ switch (kind) {
+ case 167 /* MethodSignature */:
+ case 173 /* CallSignature */:
+ case 321 /* JSDocSignature */:
+ case 174 /* ConstructSignature */:
+ case 175 /* IndexSignature */:
+ case 178 /* FunctionType */:
+ case 315 /* JSDocFunctionType */:
+ case 179 /* ConstructorType */:
+ return true;
+ default:
+ return isFunctionLikeDeclarationKind(kind);
}
- function shouldCheckNode(node) {
- switch (node.kind) {
- case 10 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- case 75 /* Identifier */:
- return true;
- }
- return false;
+ }
+ 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 === 170 /* Constructor */
+ || kind === 166 /* PropertyDeclaration */
+ || kind === 168 /* MethodDeclaration */
+ || kind === 171 /* GetAccessor */
+ || kind === 172 /* SetAccessor */
+ || kind === 175 /* IndexSignature */
+ || kind === 169 /* ClassStaticBlockDeclaration */
+ || kind === 233 /* SemicolonClassElement */;
+ }
+ ts.isClassElement = isClassElement;
+ function isClassLike(node) {
+ return node && (node.kind === 256 /* ClassDeclaration */ || node.kind === 225 /* ClassExpression */);
+ }
+ ts.isClassLike = isClassLike;
+ function isAccessor(node) {
+ return node && (node.kind === 171 /* GetAccessor */ || node.kind === 172 /* SetAccessor */);
+ }
+ ts.isAccessor = isAccessor;
+ /* @internal */
+ function isMethodOrAccessor(node) {
+ switch (node.kind) {
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ return true;
+ default:
+ return false;
}
- function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
- 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);
- if (element.parent) {
- ts.Debug.assert(element.pos >= element.parent.pos);
- ts.Debug.assert(element.end <= element.parent.end);
+ }
+ ts.isMethodOrAccessor = isMethodOrAccessor;
+ // Type members
+ function isTypeElement(node) {
+ var kind = node.kind;
+ return kind === 174 /* ConstructSignature */
+ || kind === 173 /* CallSignature */
+ || kind === 165 /* PropertySignature */
+ || kind === 167 /* MethodSignature */
+ || kind === 175 /* IndexSignature */;
+ }
+ ts.isTypeElement = isTypeElement;
+ function isClassOrTypeElement(node) {
+ return isTypeElement(node) || isClassElement(node);
+ }
+ ts.isClassOrTypeElement = isClassOrTypeElement;
+ function isObjectLiteralElementLike(node) {
+ var kind = node.kind;
+ return kind === 294 /* PropertyAssignment */
+ || kind === 295 /* ShorthandPropertyAssignment */
+ || kind === 296 /* SpreadAssignment */
+ || kind === 168 /* MethodDeclaration */
+ || kind === 171 /* GetAccessor */
+ || kind === 172 /* SetAccessor */;
+ }
+ ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
+ // Type
+ /**
+ * 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 ts.isTypeNodeKind(node.kind);
+ }
+ ts.isTypeNode = isTypeNode;
+ function isFunctionOrConstructorTypeNode(node) {
+ switch (node.kind) {
+ case 178 /* FunctionType */:
+ case 179 /* ConstructorType */:
+ return true;
+ }
+ return false;
+ }
+ ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
+ // Binding patterns
+ /* @internal */
+ function isBindingPattern(node) {
+ if (node) {
+ var kind = node.kind;
+ return kind === 201 /* ArrayBindingPattern */
+ || kind === 200 /* ObjectBindingPattern */;
+ }
+ return false;
+ }
+ ts.isBindingPattern = isBindingPattern;
+ /* @internal */
+ function isAssignmentPattern(node) {
+ var kind = node.kind;
+ return kind === 203 /* ArrayLiteralExpression */
+ || kind === 204 /* ObjectLiteralExpression */;
+ }
+ ts.isAssignmentPattern = isAssignmentPattern;
+ /* @internal */
+ function isArrayBindingElement(node) {
+ var kind = node.kind;
+ return kind === 202 /* BindingElement */
+ || kind === 226 /* OmittedExpression */;
+ }
+ ts.isArrayBindingElement = isArrayBindingElement;
+ /**
+ * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
+ */
+ /* @internal */
+ function isDeclarationBindingElement(bindingElement) {
+ switch (bindingElement.kind) {
+ case 253 /* VariableDeclaration */:
+ case 163 /* Parameter */:
+ case 202 /* 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 200 /* ObjectBindingPattern */:
+ case 204 /* ObjectLiteralExpression */:
+ return true;
+ }
+ return false;
+ }
+ ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
+ /* @internal */
+ function isObjectBindingOrAssignmentElement(node) {
+ switch (node.kind) {
+ case 202 /* BindingElement */:
+ case 294 /* PropertyAssignment */: // AssignmentProperty
+ case 295 /* ShorthandPropertyAssignment */: // AssignmentProperty
+ case 296 /* SpreadAssignment */: // AssignmentRestProperty
+ return true;
+ }
+ return false;
+ }
+ ts.isObjectBindingOrAssignmentElement = isObjectBindingOrAssignmentElement;
+ /**
+ * Determines whether a node is an ArrayBindingOrAssignmentPattern
+ */
+ /* @internal */
+ function isArrayBindingOrAssignmentPattern(node) {
+ switch (node.kind) {
+ case 201 /* ArrayBindingPattern */:
+ case 203 /* ArrayLiteralExpression */:
+ return true;
+ }
+ return false;
+ }
+ ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
+ /* @internal */
+ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
+ var kind = node.kind;
+ return kind === 205 /* PropertyAccessExpression */
+ || kind === 160 /* QualifiedName */
+ || kind === 199 /* ImportType */;
+ }
+ ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
+ // Expression
+ function isPropertyAccessOrQualifiedName(node) {
+ var kind = node.kind;
+ return kind === 205 /* PropertyAccessExpression */
+ || kind === 160 /* QualifiedName */;
+ }
+ ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
+ function isCallLikeExpression(node) {
+ switch (node.kind) {
+ case 279 /* JsxOpeningElement */:
+ case 278 /* JsxSelfClosingElement */:
+ case 207 /* CallExpression */:
+ case 208 /* NewExpression */:
+ case 209 /* TaggedTemplateExpression */:
+ case 164 /* Decorator */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isCallLikeExpression = isCallLikeExpression;
+ function isCallOrNewExpression(node) {
+ return node.kind === 207 /* CallExpression */ || node.kind === 208 /* NewExpression */;
+ }
+ ts.isCallOrNewExpression = isCallOrNewExpression;
+ function isTemplateLiteral(node) {
+ var kind = node.kind;
+ return kind === 222 /* TemplateExpression */
+ || kind === 14 /* NoSubstitutionTemplateLiteral */;
+ }
+ ts.isTemplateLiteral = isTemplateLiteral;
+ /* @internal */
+ function isLeftHandSideExpression(node) {
+ return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
+ }
+ ts.isLeftHandSideExpression = isLeftHandSideExpression;
+ function isLeftHandSideExpressionKind(kind) {
+ switch (kind) {
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ case 208 /* NewExpression */:
+ case 207 /* CallExpression */:
+ case 277 /* JsxElement */:
+ case 278 /* JsxSelfClosingElement */:
+ case 281 /* JsxFragment */:
+ case 209 /* TaggedTemplateExpression */:
+ case 203 /* ArrayLiteralExpression */:
+ case 211 /* ParenthesizedExpression */:
+ case 204 /* ObjectLiteralExpression */:
+ case 225 /* ClassExpression */:
+ case 212 /* FunctionExpression */:
+ case 79 /* Identifier */:
+ case 80 /* PrivateIdentifier */: // technically this is only an Expression if it's in a `#field in expr` BinaryExpression
+ case 13 /* RegularExpressionLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 222 /* TemplateExpression */:
+ case 95 /* FalseKeyword */:
+ case 104 /* NullKeyword */:
+ case 108 /* ThisKeyword */:
+ case 110 /* TrueKeyword */:
+ case 106 /* SuperKeyword */:
+ case 229 /* NonNullExpression */:
+ case 230 /* MetaProperty */:
+ case 100 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
+ return true;
+ default:
+ return false;
+ }
+ }
+ /* @internal */
+ function isUnaryExpression(node) {
+ return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
+ }
+ ts.isUnaryExpression = isUnaryExpression;
+ function isUnaryExpressionKind(kind) {
+ switch (kind) {
+ case 218 /* PrefixUnaryExpression */:
+ case 219 /* PostfixUnaryExpression */:
+ case 214 /* DeleteExpression */:
+ case 215 /* TypeOfExpression */:
+ case 216 /* VoidExpression */:
+ case 217 /* AwaitExpression */:
+ case 210 /* TypeAssertionExpression */:
+ return true;
+ default:
+ return isLeftHandSideExpressionKind(kind);
+ }
+ }
+ /* @internal */
+ function isUnaryExpressionWithWrite(expr) {
+ switch (expr.kind) {
+ case 219 /* PostfixUnaryExpression */:
+ return true;
+ case 218 /* PrefixUnaryExpression */:
+ return expr.operator === 45 /* PlusPlusToken */ ||
+ expr.operator === 46 /* 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(skipPartiallyEmittedExpressions(node).kind);
+ }
+ ts.isExpression = isExpression;
+ function isExpressionKind(kind) {
+ switch (kind) {
+ case 221 /* ConditionalExpression */:
+ case 223 /* YieldExpression */:
+ case 213 /* ArrowFunction */:
+ case 220 /* BinaryExpression */:
+ case 224 /* SpreadElement */:
+ case 228 /* AsExpression */:
+ case 226 /* OmittedExpression */:
+ case 349 /* CommaListExpression */:
+ case 348 /* PartiallyEmittedExpression */:
+ return true;
+ default:
+ return isUnaryExpressionKind(kind);
+ }
+ }
+ function isAssertionExpression(node) {
+ var kind = node.kind;
+ return kind === 210 /* TypeAssertionExpression */
+ || kind === 228 /* AsExpression */;
+ }
+ ts.isAssertionExpression = isAssertionExpression;
+ /* @internal */
+ function isNotEmittedOrPartiallyEmittedNode(node) {
+ return ts.isNotEmittedStatement(node)
+ || ts.isPartiallyEmittedExpression(node);
+ }
+ ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
+ function isIterationStatement(node, lookInLabeledStatements) {
+ switch (node.kind) {
+ case 241 /* ForStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ case 239 /* DoStatement */:
+ case 240 /* WhileStatement */:
+ return true;
+ case 249 /* LabeledStatement */:
+ return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
+ }
+ return false;
+ }
+ ts.isIterationStatement = isIterationStatement;
+ /* @internal */
+ function isScopeMarker(node) {
+ return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
+ }
+ ts.isScopeMarker = isScopeMarker;
+ /* @internal */
+ function hasScopeMarker(statements) {
+ return ts.some(statements, isScopeMarker);
+ }
+ ts.hasScopeMarker = hasScopeMarker;
+ /* @internal */
+ function needsScopeMarker(result) {
+ return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasSyntacticModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
+ }
+ ts.needsScopeMarker = needsScopeMarker;
+ /* @internal */
+ function isExternalModuleIndicator(result) {
+ // Exported top-level member indicates moduleness
+ return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasSyntacticModifier(result, 1 /* Export */);
+ }
+ ts.isExternalModuleIndicator = isExternalModuleIndicator;
+ /* @internal */
+ function isForInOrOfStatement(node) {
+ return node.kind === 242 /* ForInStatement */ || node.kind === 243 /* 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 === 261 /* ModuleBlock */
+ || kind === 260 /* ModuleDeclaration */
+ || kind === 79 /* Identifier */;
+ }
+ ts.isModuleBody = isModuleBody;
+ /* @internal */
+ function isNamespaceBody(node) {
+ var kind = node.kind;
+ return kind === 261 /* ModuleBlock */
+ || kind === 260 /* ModuleDeclaration */;
+ }
+ ts.isNamespaceBody = isNamespaceBody;
+ /* @internal */
+ function isJSDocNamespaceBody(node) {
+ var kind = node.kind;
+ return kind === 79 /* Identifier */
+ || kind === 260 /* ModuleDeclaration */;
+ }
+ ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
+ /* @internal */
+ function isNamedImportBindings(node) {
+ var kind = node.kind;
+ return kind === 268 /* NamedImports */
+ || kind === 267 /* NamespaceImport */;
+ }
+ ts.isNamedImportBindings = isNamedImportBindings;
+ /* @internal */
+ function isModuleOrEnumDeclaration(node) {
+ return node.kind === 260 /* ModuleDeclaration */ || node.kind === 259 /* EnumDeclaration */;
+ }
+ ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
+ function isDeclarationKind(kind) {
+ return kind === 213 /* ArrowFunction */
+ || kind === 202 /* BindingElement */
+ || kind === 256 /* ClassDeclaration */
+ || kind === 225 /* ClassExpression */
+ || kind === 169 /* ClassStaticBlockDeclaration */
+ || kind === 170 /* Constructor */
+ || kind === 259 /* EnumDeclaration */
+ || kind === 297 /* EnumMember */
+ || kind === 274 /* ExportSpecifier */
+ || kind === 255 /* FunctionDeclaration */
+ || kind === 212 /* FunctionExpression */
+ || kind === 171 /* GetAccessor */
+ || kind === 266 /* ImportClause */
+ || kind === 264 /* ImportEqualsDeclaration */
+ || kind === 269 /* ImportSpecifier */
+ || kind === 257 /* InterfaceDeclaration */
+ || kind === 284 /* JsxAttribute */
+ || kind === 168 /* MethodDeclaration */
+ || kind === 167 /* MethodSignature */
+ || kind === 260 /* ModuleDeclaration */
+ || kind === 263 /* NamespaceExportDeclaration */
+ || kind === 267 /* NamespaceImport */
+ || kind === 273 /* NamespaceExport */
+ || kind === 163 /* Parameter */
+ || kind === 294 /* PropertyAssignment */
+ || kind === 166 /* PropertyDeclaration */
+ || kind === 165 /* PropertySignature */
+ || kind === 172 /* SetAccessor */
+ || kind === 295 /* ShorthandPropertyAssignment */
+ || kind === 258 /* TypeAliasDeclaration */
+ || kind === 162 /* TypeParameter */
+ || kind === 253 /* VariableDeclaration */
+ || kind === 343 /* JSDocTypedefTag */
+ || kind === 336 /* JSDocCallbackTag */
+ || kind === 345 /* JSDocPropertyTag */;
+ }
+ function isDeclarationStatementKind(kind) {
+ return kind === 255 /* FunctionDeclaration */
+ || kind === 275 /* MissingDeclaration */
+ || kind === 256 /* ClassDeclaration */
+ || kind === 257 /* InterfaceDeclaration */
+ || kind === 258 /* TypeAliasDeclaration */
+ || kind === 259 /* EnumDeclaration */
+ || kind === 260 /* ModuleDeclaration */
+ || kind === 265 /* ImportDeclaration */
+ || kind === 264 /* ImportEqualsDeclaration */
+ || kind === 271 /* ExportDeclaration */
+ || kind === 270 /* ExportAssignment */
+ || kind === 263 /* NamespaceExportDeclaration */;
+ }
+ function isStatementKindButNotDeclarationKind(kind) {
+ return kind === 245 /* BreakStatement */
+ || kind === 244 /* ContinueStatement */
+ || kind === 252 /* DebuggerStatement */
+ || kind === 239 /* DoStatement */
+ || kind === 237 /* ExpressionStatement */
+ || kind === 235 /* EmptyStatement */
+ || kind === 242 /* ForInStatement */
+ || kind === 243 /* ForOfStatement */
+ || kind === 241 /* ForStatement */
+ || kind === 238 /* IfStatement */
+ || kind === 249 /* LabeledStatement */
+ || kind === 246 /* ReturnStatement */
+ || kind === 248 /* SwitchStatement */
+ || kind === 250 /* ThrowStatement */
+ || kind === 251 /* TryStatement */
+ || kind === 236 /* VariableStatement */
+ || kind === 240 /* WhileStatement */
+ || kind === 247 /* WithStatement */
+ || kind === 347 /* NotEmittedStatement */
+ || kind === 351 /* EndOfDeclarationMarker */
+ || kind === 350 /* MergeDeclarationMarker */;
+ }
+ /* @internal */
+ function isDeclaration(node) {
+ if (node.kind === 162 /* TypeParameter */) {
+ return (node.parent && node.parent.kind !== 342 /* JSDocTemplateTag */) || ts.isInJSFile(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)
+ || isDeclarationStatementKind(kind)
+ || isBlockStatement(node);
+ }
+ ts.isStatement = isStatement;
+ function isBlockStatement(node) {
+ if (node.kind !== 234 /* Block */)
+ return false;
+ if (node.parent !== undefined) {
+ if (node.parent.kind === 251 /* TryStatement */ || node.parent.kind === 291 /* CatchClause */) {
+ return false;
}
}
- function checkNodePositions(node, aggressiveChecks) {
- if (aggressiveChecks) {
- var pos_2 = node.pos;
- var visitNode_1 = function (child) {
- ts.Debug.assert(child.pos >= pos_2);
- pos_2 = child.end;
- };
- if (ts.hasJSDocNodes(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var jsDocComment = _a[_i];
- visitNode_1(jsDocComment);
- }
- }
- forEachChild(node, visitNode_1);
- ts.Debug.assert(pos_2 <= node.end);
- }
+ return !ts.isFunctionBlock(node);
+ }
+ /**
+ * NOTE: This is similar to `isStatement` but does not access parent pointers.
+ */
+ /* @internal */
+ function isStatementOrBlock(node) {
+ var kind = node.kind;
+ return isStatementKindButNotDeclarationKind(kind)
+ || isDeclarationStatementKind(kind)
+ || kind === 234 /* Block */;
+ }
+ ts.isStatementOrBlock = isStatementOrBlock;
+ // Module references
+ /* @internal */
+ function isModuleReference(node) {
+ var kind = node.kind;
+ return kind === 276 /* ExternalModuleReference */
+ || kind === 160 /* QualifiedName */
+ || kind === 79 /* Identifier */;
+ }
+ ts.isModuleReference = isModuleReference;
+ // JSX
+ /* @internal */
+ function isJsxTagNameExpression(node) {
+ var kind = node.kind;
+ return kind === 108 /* ThisKeyword */
+ || kind === 79 /* Identifier */
+ || kind === 205 /* PropertyAccessExpression */;
+ }
+ ts.isJsxTagNameExpression = isJsxTagNameExpression;
+ /* @internal */
+ function isJsxChild(node) {
+ var kind = node.kind;
+ return kind === 277 /* JsxElement */
+ || kind === 287 /* JsxExpression */
+ || kind === 278 /* JsxSelfClosingElement */
+ || kind === 11 /* JsxText */
+ || kind === 281 /* JsxFragment */;
+ }
+ ts.isJsxChild = isJsxChild;
+ /* @internal */
+ function isJsxAttributeLike(node) {
+ var kind = node.kind;
+ return kind === 284 /* JsxAttribute */
+ || kind === 286 /* JsxSpreadAttribute */;
+ }
+ ts.isJsxAttributeLike = isJsxAttributeLike;
+ /* @internal */
+ function isStringLiteralOrJsxExpression(node) {
+ var kind = node.kind;
+ return kind === 10 /* StringLiteral */
+ || kind === 287 /* JsxExpression */;
+ }
+ ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
+ function isJsxOpeningLikeElement(node) {
+ var kind = node.kind;
+ return kind === 279 /* JsxOpeningElement */
+ || kind === 278 /* JsxSelfClosingElement */;
+ }
+ ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
+ // Clauses
+ function isCaseOrDefaultClause(node) {
+ var kind = node.kind;
+ return kind === 288 /* CaseClause */
+ || kind === 289 /* DefaultClause */;
+ }
+ ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
+ // JSDoc
+ /** True if node is of some JSDoc syntax kind. */
+ /* @internal */
+ function isJSDocNode(node) {
+ return node.kind >= 307 /* FirstJSDocNode */ && node.kind <= 345 /* LastJSDocNode */;
+ }
+ ts.isJSDocNode = isJSDocNode;
+ /** True if node is of a kind that may contain comment text. */
+ function isJSDocCommentContainingNode(node) {
+ return node.kind === 318 /* JSDocComment */
+ || node.kind === 317 /* JSDocNamepathType */
+ || node.kind === 319 /* JSDocText */
+ || isJSDocLinkLike(node)
+ || 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 >= 325 /* FirstJSDocTagNode */ && node.kind <= 345 /* LastJSDocTagNode */;
+ }
+ ts.isJSDocTag = isJSDocTag;
+ function isSetAccessor(node) {
+ return node.kind === 172 /* SetAccessor */;
+ }
+ ts.isSetAccessor = isSetAccessor;
+ function isGetAccessor(node) {
+ return node.kind === 171 /* 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 has initializer node attached to it. */
+ /* @internal */
+ function hasInitializer(node) {
+ return !!node.initializer;
+ }
+ ts.hasInitializer = hasInitializer;
+ /** True if has initializer node attached to it. */
+ function hasOnlyExpressionInitializer(node) {
+ switch (node.kind) {
+ case 253 /* VariableDeclaration */:
+ case 163 /* Parameter */:
+ case 202 /* BindingElement */:
+ case 165 /* PropertySignature */:
+ case 166 /* PropertyDeclaration */:
+ case 294 /* PropertyAssignment */:
+ case 297 /* EnumMember */:
+ return true;
+ default:
+ return false;
}
- function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
- visitNode(sourceFile);
- return;
- function visitNode(child) {
- ts.Debug.assert(child.pos <= child.end);
- if (child.pos > changeRangeOldEnd) {
- // 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)) {
- for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
- var jsDocComment = _a[_i];
- visitNode(jsDocComment);
- }
- }
- 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);
+ }
+ ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
+ function isObjectLiteralElement(node) {
+ return node.kind === 284 /* JsxAttribute */ || node.kind === 286 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
+ }
+ ts.isObjectLiteralElement = isObjectLiteralElement;
+ /* @internal */
+ function isTypeReferenceType(node) {
+ return node.kind === 177 /* TypeReference */ || node.kind === 227 /* 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++) {
+ var line = lines_1[_i];
+ if (!line.length) {
+ continue;
}
- function visitArray(array) {
- ts.Debug.assert(array.pos <= array.end);
- if (array.pos > changeRangeOldEnd) {
- // 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];
- visitNode(node);
- }
- return;
+ var i = 0;
+ for (; i < line.length && i < indentation; i++) {
+ if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
+ break;
}
- // 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);
- var position = nearestNode.pos;
- start = Math.max(0, position - 1);
}
- var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
- var finalLength = changeRange.newLength + (changeRange.span.start - start);
- return ts.createTextChangeRange(finalSpan, finalLength);
- }
- function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
- var bestResult = sourceFile;
- var lastNodeEntirelyBeforePosition;
- forEachChild(sourceFile, visit);
- if (lastNodeEntirelyBeforePosition) {
- var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
- if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
- bestResult = lastChildOfLastEntireNodeBeforePosition;
- }
+ if (i < indentation) {
+ indentation = i;
}
- return bestResult;
- function getLastDescendant(node) {
- while (true) {
- var lastChild = ts.getLastChild(node);
- if (lastChild) {
- node = lastChild;
- }
- else {
- return node;
- }
- }
+ if (indentation === 0) {
+ return 0;
}
- 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;
+ }
+ return indentation === MAX_SMI_X86 ? undefined : indentation;
+ }
+ ts.guessIndentation = guessIndentation;
+ function isStringLiteralLike(node) {
+ return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
+ }
+ ts.isStringLiteralLike = isStringLiteralLike;
+ function isJSDocLinkLike(node) {
+ return node.kind === 322 /* JSDocLink */ || node.kind === 323 /* JSDocLinkCode */ || node.kind === 324 /* JSDocLinkPlain */;
+ }
+ ts.isJSDocLinkLike = isJSDocLinkLike;
+ // #endregion
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ ts.resolvingEmptyArray = [];
+ ts.externalHelpersModuleNameText = "tslib";
+ ts.defaultMaximumTruncationLength = 160;
+ ts.noTruncationMaximumTruncationLength = 1000000;
+ function getDeclarationOfKind(symbol, kind) {
+ var declarations = symbol.declarations;
+ if (declarations) {
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
+ if (declaration.kind === kind) {
+ return declaration;
}
}
}
- function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
- var oldText = sourceFile.text;
- if (textChangeRange) {
- ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
- 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);
- var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
- var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
- ts.Debug.assert(oldTextSuffix === newTextSuffix);
- }
+ return undefined;
+ }
+ ts.getDeclarationOfKind = getDeclarationOfKind;
+ /**
+ * Create a new escaped identifier map.
+ * @deprecated Use `new Map<__String, T>()` instead.
+ */
+ function createUnderscoreEscapedMap() {
+ return new ts.Map();
+ }
+ ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
+ /**
+ * @deprecated Use `!!map?.size` instead
+ */
+ function hasEntries(map) {
+ return !!map && !!map.size;
+ }
+ ts.hasEntries = hasEntries;
+ function createSymbolTable(symbols) {
+ var result = new ts.Map();
+ if (symbols) {
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_i];
+ result.set(symbol.escapedName, symbol);
}
}
- function createSyntaxCursor(sourceFile) {
- var currentArray = sourceFile.statements;
- var currentArrayIndex = 0;
- ts.Debug.assert(currentArrayIndex < currentArray.length);
- var current = currentArray[currentArrayIndex];
- 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 /* 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;
- return true;
- }
- 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;
- }
- }
- }
- }
- }
- // position wasn't in this array, have to keep searching.
- return false;
- }
+ return result;
+ }
+ ts.createSymbolTable = createSymbolTable;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
+ ts.isTransientSymbol = isTransientSymbol;
+ var stringWriter = createSingleLineStringWriter();
+ function createSingleLineStringWriter() {
+ var str = "";
+ var writeText = function (text) { return str += text; };
+ return {
+ getText: function () { return str; },
+ write: writeText,
+ rawWrite: writeText,
+ writeKeyword: writeText,
+ writeOperator: writeText,
+ writePunctuation: writeText,
+ writeSpace: writeText,
+ writeStringLiteral: writeText,
+ writeLiteral: writeText,
+ writeParameter: writeText,
+ writeProperty: writeText,
+ writeSymbol: function (s, _) { return writeText(s); },
+ writeTrailingSemicolon: writeText,
+ writeComment: writeText,
+ getTextPos: function () { return str.length; },
+ getLine: function () { return 0; },
+ getColumn: function () { return 0; },
+ getIndent: function () { return 0; },
+ isAtStartOfLine: function () { return false; },
+ hasTrailingComment: function () { return false; },
+ hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
+ // Completely ignore indentation for string writers. And map newlines to
+ // a single space.
+ writeLine: function () { return str += " "; },
+ increaseIndent: ts.noop,
+ decreaseIndent: ts.noop,
+ clear: function () { return str = ""; },
+ trackSymbol: function () { return false; },
+ reportInaccessibleThisError: ts.noop,
+ reportInaccessibleUniqueSymbolError: ts.noop,
+ reportPrivateInBaseOfClassExpression: ts.noop,
+ };
+ }
+ function changesAffectModuleResolution(oldOptions, newOptions) {
+ return oldOptions.configFilePath !== newOptions.configFilePath ||
+ optionsHaveModuleResolutionChanges(oldOptions, newOptions);
+ }
+ ts.changesAffectModuleResolution = changesAffectModuleResolution;
+ function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
+ return optionsHaveChanges(oldOptions, newOptions, ts.moduleResolutionOptionDeclarations);
+ }
+ ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
+ function changesAffectingProgramStructure(oldOptions, newOptions) {
+ return optionsHaveChanges(oldOptions, newOptions, ts.optionsAffectingProgramStructure);
+ }
+ ts.changesAffectingProgramStructure = changesAffectingProgramStructure;
+ function optionsHaveChanges(oldOptions, newOptions, optionDeclarations) {
+ return oldOptions !== newOptions && optionDeclarations.some(function (o) {
+ return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
+ });
+ }
+ ts.optionsHaveChanges = optionsHaveChanges;
+ function forEachAncestor(node, callback) {
+ while (true) {
+ var res = callback(node);
+ if (res === "quit")
+ return undefined;
+ if (res !== undefined)
+ return res;
+ if (ts.isSourceFile(node))
+ return undefined;
+ node = node.parent;
+ }
+ }
+ ts.forEachAncestor = forEachAncestor;
+ /**
+ * Calls `callback` for each entry in the map, returning the first truthy result.
+ * Use `map.forEach` instead for normal iteration.
+ */
+ function forEachEntry(map, callback) {
+ var iterator = map.entries();
+ for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
+ var _a = iterResult.value, key = _a[0], value = _a[1];
+ var result = callback(value, key);
+ if (result) {
+ return result;
}
}
- var InvalidPosition;
- (function (InvalidPosition) {
- InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
- })(InvalidPosition || (InvalidPosition = {}));
- })(IncrementalParser || (IncrementalParser = {}));
- /** @internal */
- function isDeclarationFileName(fileName) {
- return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
+ return undefined;
}
- ts.isDeclarationFileName = isDeclarationFileName;
- /*@internal*/
- function processCommentPragmas(context, sourceText) {
- var pragmas = [];
- for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
- var range = _a[_i];
- var comment = sourceText.substring(range.pos, range.end);
- extractPragmas(pragmas, range, comment);
- }
- context.pragmas = ts.createMap();
- for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
- var pragma = pragmas_1[_b];
- if (context.pragmas.has(pragma.name)) {
- var currentValue = context.pragmas.get(pragma.name);
- if (currentValue instanceof Array) {
- currentValue.push(pragma.args);
- }
- else {
- context.pragmas.set(pragma.name, [currentValue, pragma.args]);
- }
- continue;
+ ts.forEachEntry = forEachEntry;
+ /** `forEachEntry` for just keys. */
+ function forEachKey(map, callback) {
+ var iterator = map.keys();
+ for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
+ var result = callback(iterResult.value);
+ if (result) {
+ return result;
}
- context.pragmas.set(pragma.name, pragma.args);
}
+ return undefined;
}
- ts.processCommentPragmas = processCommentPragmas;
- /*@internal*/
- function processPragmasIntoFields(context, reportDiagnostic) {
- context.checkJsDirective = undefined;
- context.referencedFiles = [];
- context.typeReferenceDirectives = [];
- context.libReferenceDirectives = [];
- 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) {
- var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
- if (arg.arguments["no-default-lib"]) {
- context.hasNoDefaultLib = true;
- }
- else if (types) {
- typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
- }
- else if (lib) {
- libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
- }
- else if (path) {
- referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
- }
- else {
- reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
- }
- });
- break;
- }
- case "amd-dependency": {
- context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
- break;
- }
- case "amd-module": {
- if (entryOrList instanceof Array) {
- 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;
- }
- }
- else {
- context.moduleName = entryOrList.arguments.name;
- }
- break;
- }
- 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) {
- context.checkJsDirective = {
- enabled: key === "ts-check",
- end: entry.range.end,
- pos: entry.range.pos
- };
- }
- });
- break;
- }
- case "jsx": return; // Accessed directly
- default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
- }
+ ts.forEachKey = forEachKey;
+ /** Copy entries from `source` to `target`. */
+ function copyEntries(source, target) {
+ source.forEach(function (value, key) {
+ target.set(key, value);
});
}
- ts.processPragmasIntoFields = processPragmasIntoFields;
- var namedArgRegExCache = ts.createMap();
- function getNamedArgRegEx(name) {
- if (namedArgRegExCache.has(name)) {
- return namedArgRegExCache.get(name);
+ ts.copyEntries = copyEntries;
+ function usingSingleLineStringWriter(action) {
+ var oldString = stringWriter.getText();
+ try {
+ action(stringWriter);
+ return stringWriter.getText();
+ }
+ finally {
+ stringWriter.clear();
+ stringWriter.writeKeyword(oldString);
}
- var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
- namedArgRegExCache.set(name, result);
- return result;
}
- var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
- var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
- function extractPragmas(pragmas, range, text) {
- var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
- if (tripleSlash) {
- 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 /* TripleSlashXML */)) {
- return;
- }
- if (pragma.args) {
- var argument = {};
- for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
- var arg = _a[_i];
- var matcher = getNamedArgRegEx(arg.name);
- var matchResult = matcher.exec(text);
- if (!matchResult && !arg.optional) {
- return; // Missing required argument, don't parse
- }
- else if (matchResult) {
- if (arg.captureSpan) {
- var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
- argument[arg.name] = {
- value: matchResult[3],
- pos: startPos,
- end: startPos + matchResult[3].length
- };
- }
- else {
- argument[arg.name] = matchResult[3];
- }
- }
- }
- pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
+ function getFullWidth(node) {
+ return node.end - node.pos;
+ }
+ ts.getFullWidth = getFullWidth;
+ function getResolvedModule(sourceFile, moduleNameText, mode) {
+ return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText, mode);
+ }
+ ts.getResolvedModule = getResolvedModule;
+ function setResolvedModule(sourceFile, moduleNameText, resolvedModule, mode) {
+ if (!sourceFile.resolvedModules) {
+ sourceFile.resolvedModules = ts.createModeAwareCache();
+ }
+ sourceFile.resolvedModules.set(moduleNameText, mode, resolvedModule);
+ }
+ ts.setResolvedModule = setResolvedModule;
+ function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
+ if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
+ sourceFile.resolvedTypeReferenceDirectiveNames = ts.createModeAwareCache();
+ }
+ sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, /*mode*/ undefined, resolvedTypeReferenceDirective);
+ }
+ ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
+ function projectReferenceIsEqualTo(oldRef, newRef) {
+ return oldRef.path === newRef.path &&
+ !oldRef.prepend === !newRef.prepend &&
+ !oldRef.circular === !newRef.circular;
+ }
+ ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
+ function moduleResolutionIsEqualTo(oldResolution, newResolution) {
+ return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
+ oldResolution.extension === newResolution.extension &&
+ oldResolution.resolvedFileName === newResolution.resolvedFileName &&
+ oldResolution.originalPath === newResolution.originalPath &&
+ packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
+ }
+ ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
+ function packageIdIsEqual(a, b) {
+ return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
+ }
+ function packageIdToString(_a) {
+ var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
+ var fullName = subModuleName ? "".concat(name, "/").concat(subModuleName) : name;
+ return "".concat(fullName, "@").concat(version);
+ }
+ ts.packageIdToString = packageIdToString;
+ function typeDirectiveIsEqualTo(oldResolution, newResolution) {
+ return oldResolution.resolvedFileName === newResolution.resolvedFileName
+ && oldResolution.primary === newResolution.primary
+ && oldResolution.originalPath === newResolution.originalPath;
+ }
+ ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
+ function hasChangesInResolutions(names, newResolutions, oldResolutions, oldSourceFile, comparer) {
+ ts.Debug.assert(names.length === newResolutions.length);
+ for (var i = 0; i < names.length; i++) {
+ var newResolution = newResolutions[i];
+ var oldResolution = oldResolutions && oldResolutions.get(names[i], oldSourceFile && ts.getModeForResolutionAtIndex(oldSourceFile, i));
+ var changed = oldResolution
+ ? !newResolution || !comparer(oldResolution, newResolution)
+ : newResolution;
+ if (changed) {
+ return true;
}
- else {
- pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ 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 & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
+ }
+ ts.containsParseError = containsParseError;
+ function aggregateChildData(node) {
+ if (!(node.flags & 524288 /* 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 & 65536 /* ThisNodeHasError */) !== 0) ||
+ ts.forEachChild(node, containsParseError);
+ // If so, mark ourselves accordingly.
+ if (thisNodeOrAnySubNodesHasError) {
+ node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
}
- return;
+ // 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 |= 524288 /* HasAggregatedChildData */;
}
- var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
- if (singleLine) {
- return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
+ }
+ function getSourceFileOfNode(node) {
+ while (node && node.kind !== 303 /* SourceFile */) {
+ node = node.parent;
}
- 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 /* MultiLine */, multiLineMatch);
+ return node;
+ }
+ ts.getSourceFileOfNode = getSourceFileOfNode;
+ function getSourceFileOfModule(module) {
+ return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module));
+ }
+ ts.getSourceFileOfModule = getSourceFileOfModule;
+ function isStatementWithLocals(node) {
+ switch (node.kind) {
+ case 234 /* Block */:
+ case 262 /* CaseBlock */:
+ case 241 /* ForStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ return true;
+ }
+ return false;
+ }
+ ts.isStatementWithLocals = isStatementWithLocals;
+ function getStartPositionOfLine(line, sourceFile) {
+ ts.Debug.assert(line >= 0);
+ 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);
+ return "".concat(file.fileName, "(").concat(loc.line + 1, ",").concat(loc.character + 1, ")");
+ }
+ ts.nodePosToString = nodePosToString;
+ function getEndLinePosition(line, sourceFile) {
+ ts.Debug.assert(line >= 0);
+ var lineStarts = ts.getLineStarts(sourceFile);
+ 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--;
}
+ return pos;
}
}
- function addPragmaForMatch(pragmas, range, kind, match) {
- if (!match)
- return;
- 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;
+ 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;
}
- var args = match[2]; // Split on spaces and match up positionally with definition
- var argument = getNamedPragmaArguments(pragma, args);
- if (argument === "fail")
- return; // Missing required argument, fail to parse it
- pragmas.push({ name: name, args: { arguments: argument, range: range } });
- return;
+ return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
}
- function getNamedPragmaArguments(pragma, text) {
- if (!text)
- return {};
- if (!pragma.args)
- return {};
- var args = text.split(/\s+/);
- var argMap = {};
- for (var i = 0; i < pragma.args.length; i++) {
- var argument = pragma.args[i];
- if (!args[i] && !argument.optional) {
- return "fail";
+ ts.nodeIsMissing = nodeIsMissing;
+ function nodeIsPresent(node) {
+ return !nodeIsMissing(node);
+ }
+ ts.nodeIsPresent = nodeIsPresent;
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
+ if (from === undefined || from.length === 0)
+ return to;
+ var statementIndex = 0;
+ // skip all prologue directives to insert at the correct position
+ for (; statementIndex < to.length; ++statementIndex) {
+ if (!isPrologueDirective(to[statementIndex])) {
+ break;
}
- if (argument.captureSpan) {
- return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ to.splice.apply(to, __spreadArray([statementIndex, 0], from, false));
+ return to;
+ }
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ var statementIndex = 0;
+ // skip all prologue directives to insert at the correct position
+ for (; statementIndex < to.length; ++statementIndex) {
+ if (!isPrologueDirective(to[statementIndex])) {
+ break;
}
- argMap[argument.name] = args[i];
}
- return argMap;
+ to.splice(statementIndex, 0, statement);
+ return to;
}
- /** @internal */
- function tagNamesAreEquivalent(lhs, rhs) {
- if (lhs.kind !== rhs.kind) {
- return false;
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
+ /**
+ * 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) {
+ // 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 /* slash */) {
+ var textSubStr = text.substring(commentPos, commentEnd);
+ return ts.fullTripleSlashReferencePathRegEx.test(textSubStr) ||
+ ts.fullTripleSlashAMDReferencePathRegEx.test(textSubStr) ||
+ fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) ||
+ defaultLibReferenceRegEx.test(textSubStr) ?
+ true : false;
}
- if (lhs.kind === 75 /* Identifier */) {
- return lhs.escapedText === rhs.escapedText;
+ return false;
+ }
+ ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
+ function isPinnedComment(text, start) {
+ return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
+ text.charCodeAt(start + 2) === 33 /* exclamation */;
+ }
+ ts.isPinnedComment = isPinnedComment;
+ function createCommentDirectivesMap(sourceFile, commentDirectives) {
+ var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([
+ "".concat(ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line),
+ commentDirective,
+ ]); }));
+ var usedLines = new ts.Map();
+ return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
+ function getUnusedExpectations() {
+ return ts.arrayFrom(directivesByLine.entries())
+ .filter(function (_a) {
+ var line = _a[0], directive = _a[1];
+ return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
+ })
+ .map(function (_a) {
+ var _ = _a[0], directive = _a[1];
+ return directive;
+ });
}
- if (lhs.kind === 104 /* ThisKeyword */) {
+ function markUsed(line) {
+ if (!directivesByLine.has("".concat(line))) {
+ return false;
+ }
+ usedLines.set("".concat(line), true);
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);
}
- ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
-})(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"],
- ["es7", "lib.es2016.d.ts"],
- ["es2016", "lib.es2016.d.ts"],
- ["es2017", "lib.es2017.d.ts"],
- ["es2018", "lib.es2018.d.ts"],
- ["es2019", "lib.es2019.d.ts"],
- ["es2020", "lib.es2020.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"],
- ["es2015.iterable", "lib.es2015.iterable.d.ts"],
- ["es2015.promise", "lib.es2015.promise.d.ts"],
- ["es2015.proxy", "lib.es2015.proxy.d.ts"],
- ["es2015.reflect", "lib.es2015.reflect.d.ts"],
- ["es2015.symbol", "lib.es2015.symbol.d.ts"],
- ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
- ["es2016.array.include", "lib.es2016.array.include.d.ts"],
- ["es2017.object", "lib.es2017.object.d.ts"],
- ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
- ["es2017.string", "lib.es2017.string.d.ts"],
- ["es2017.intl", "lib.es2017.intl.d.ts"],
- ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
- ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
- ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
- ["es2018.intl", "lib.es2018.intl.d.ts"],
- ["es2018.promise", "lib.es2018.promise.d.ts"],
- ["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["es2019.array", "lib.es2019.array.d.ts"],
- ["es2019.object", "lib.es2019.object.d.ts"],
- ["es2019.string", "lib.es2019.string.d.ts"],
- ["es2019.symbol", "lib.es2019.symbol.d.ts"],
- ["es2020.bigint", "lib.es2020.bigint.d.ts"],
- ["es2020.promise", "lib.es2020.promise.d.ts"],
- ["es2020.string", "lib.es2020.string.d.ts"],
- ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
- ["esnext.array", "lib.es2019.array.d.ts"],
- ["esnext.symbol", "lib.es2019.symbol.d.ts"],
- ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
- ["esnext.intl", "lib.esnext.intl.d.ts"],
- ["esnext.bigint", "lib.es2020.bigint.d.ts"],
- ["esnext.string", "lib.esnext.string.d.ts"],
- ["esnext.promise", "lib.esnext.promise.d.ts"]
- ];
+ ts.createCommentDirectivesMap = createCommentDirectivesMap;
+ 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) || node.kind === 11 /* JsxText */) {
+ // JsxText cannot actually contain comments, even though the scanner will think it sees comments
+ return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ }
+ if (includeJsDoc && ts.hasJSDocNodes(node)) {
+ return getTokenPosOfNode(node.jsDoc[0], sourceFile);
+ }
+ // 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 === 346 /* SyntaxList */ && node._children.length > 0) {
+ return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
+ }
+ return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos,
+ /*stopAfterLineBreak*/ false,
+ /*stopAtComments*/ false, isInJSDoc(node));
+ }
+ ts.getTokenPosOfNode = getTokenPosOfNode;
+ function getNonDecoratorTokenPosOfNode(node, sourceFile) {
+ if (nodeIsMissing(node) || !node.decorators) {
+ return getTokenPosOfNode(node, sourceFile);
+ }
+ return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
+ }
+ ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
+ function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
+ if (includeTrivia === void 0) { includeTrivia = false; }
+ return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
+ }
+ ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
+ function isJSDocTypeExpressionOrChild(node) {
+ return !!ts.findAncestor(node, ts.isJSDocTypeExpression);
+ }
+ function isExportNamespaceAsDefaultDeclaration(node) {
+ return !!(ts.isExportDeclaration(node) && node.exportClause && ts.isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default");
+ }
+ ts.isExportNamespaceAsDefaultDeclaration = isExportNamespaceAsDefaultDeclaration;
+ function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
+ if (includeTrivia === void 0) { includeTrivia = false; }
+ if (nodeIsMissing(node)) {
+ return "";
+ }
+ var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
+ if (isJSDocTypeExpressionOrChild(node)) {
+ // strip space + asterisk at line start
+ text = text.split(/\r\n|\n|\r/).map(function (line) { return ts.trimStringStart(line.replace(/^\s*\*/, "")); }).join("\n");
+ }
+ return text;
+ }
+ ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
+ function getTextOfNode(node, includeTrivia) {
+ if (includeTrivia === void 0) { includeTrivia = false; }
+ return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
+ }
+ ts.getTextOfNode = getTextOfNode;
+ function getPos(range) {
+ return range.pos;
+ }
/**
- * 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.
+ * 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.
*/
- /* @internal */
- ts.libs = libEntries.map(function (entry) { return entry[0]; });
+ function indexOfNode(nodeArray, node) {
+ return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
+ }
+ ts.indexOfNode = indexOfNode;
/**
- * 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.
+ * Gets flags that control emit behavior of a node.
*/
- /* @internal */
- ts.libMap = ts.createMapFromEntries(libEntries);
- // Watch related options
- /* @internal */
- ts.optionsForWatch = [
- {
- name: "watchFile",
- type: ts.createMapFromTemplate({
- fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
- prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
- dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
- usefsevents: ts.WatchFileKind.UseFsEvents,
- usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
- }),
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
- },
- {
- name: "watchDirectory",
- type: ts.createMapFromTemplate({
- usefsevents: ts.WatchDirectoryKind.UseFsEvents,
- fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
- dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
- }),
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
- },
- {
- name: "fallbackPolling",
- type: ts.createMapFromTemplate({
- fixedinterval: ts.PollingWatchKind.FixedInterval,
- priorityinterval: ts.PollingWatchKind.PriorityInterval,
- dynamicpriority: ts.PollingWatchKind.DynamicPriority,
- }),
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
- },
- {
- name: "synchronousWatchDirectory",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
- },
- ];
- /* @internal */
- ts.commonOptionsWithBuild = [
- {
- name: "help",
- shortName: "h",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Print_this_message,
- },
- {
- name: "help",
- shortName: "?",
- type: "boolean"
- },
- {
- name: "watch",
- shortName: "w",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Watch_input_files,
- },
- {
- name: "preserveWatchOutput",
- type: "boolean",
- showInSimplifiedHelpView: false,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
- },
- {
- name: "listFiles",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
- },
- {
- name: "listEmittedFiles",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
- },
- {
- name: "pretty",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
- },
- {
- name: "traceResolution",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
- },
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
- {
- name: "generateCpuProfile",
- type: "string",
- isFilePath: true,
- paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Generates_a_CPU_profile
- },
- {
- name: "incremental",
- shortName: "i",
- type: "boolean",
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Enable_incremental_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "assumeChangesOnlyAffectDirectDependencies",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
- },
- {
- name: "locale",
- type: "string",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
- },
- ];
- /* @internal */
- ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
- {
- name: "all",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Show_all_compiler_options,
- },
- {
- name: "version",
- shortName: "v",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Print_the_compiler_s_version,
- },
- {
- name: "init",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
- },
- {
- name: "project",
- shortName: "p",
- type: "string",
- isFilePath: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
- description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
- },
- {
- name: "build",
- type: "boolean",
- shortName: "b",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
- },
- {
- name: "showConfig",
- type: "boolean",
- category: ts.Diagnostics.Command_line_Options,
- isCommandLineOnly: true,
- description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
- },
- {
- name: "listFilesOnly",
- type: "boolean",
- category: ts.Diagnostics.Command_line_Options,
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- isCommandLineOnly: true,
- description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
- },
- // Basic
- {
- name: "target",
- shortName: "t",
- type: ts.createMapFromTemplate({
- es3: 0 /* ES3 */,
- es5: 1 /* ES5 */,
- es6: 2 /* ES2015 */,
- es2015: 2 /* ES2015 */,
- es2016: 3 /* ES2016 */,
- es2017: 4 /* ES2017 */,
- es2018: 5 /* ES2018 */,
- es2019: 6 /* ES2019 */,
- es2020: 7 /* ES2020 */,
- esnext: 99 /* ESNext */,
- }),
- affectsSourceFile: true,
- affectsModuleResolution: true,
- affectsEmit: true,
- paramType: ts.Diagnostics.VERSION,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
- },
- {
- name: "module",
- shortName: "m",
- type: ts.createMapFromTemplate({
- none: ts.ModuleKind.None,
- commonjs: ts.ModuleKind.CommonJS,
- amd: ts.ModuleKind.AMD,
- system: ts.ModuleKind.System,
- umd: ts.ModuleKind.UMD,
- es6: ts.ModuleKind.ES2015,
- es2015: ts.ModuleKind.ES2015,
- es2020: ts.ModuleKind.ES2020,
- esnext: ts.ModuleKind.ESNext
- }),
- affectsModuleResolution: true,
- affectsEmit: true,
- paramType: ts.Diagnostics.KIND,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
- },
- {
- name: "lib",
- type: "list",
- element: {
- name: "lib",
- type: ts.libMap
- },
- affectsModuleResolution: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "allowJs",
- type: "boolean",
- affectsModuleResolution: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
- },
- {
- name: "checkJs",
- type: "boolean",
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Report_errors_in_js_files
- },
- {
- name: "jsx",
- type: ts.createMapFromTemplate({
- "preserve": 1 /* Preserve */,
- "react-native": 3 /* ReactNative */,
- "react": 2 /* React */
- }),
- affectsSourceFile: true,
- paramType: ts.Diagnostics.KIND,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
- },
- {
- name: "declaration",
- shortName: "d",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Generates_corresponding_d_ts_file,
- transpileOptionValue: undefined
- },
- {
- name: "declarationMap",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
- transpileOptionValue: undefined
- },
- {
- name: "emitDeclarationOnly",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
- transpileOptionValue: undefined
- },
- {
- name: "sourceMap",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Generates_corresponding_map_file,
- },
- {
- name: "outFile",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.FILE,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
- transpileOptionValue: undefined
- },
- {
- name: "outDir",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.DIRECTORY,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
- },
- {
- name: "rootDir",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.LOCATION,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
- },
- {
- name: "composite",
- type: "boolean",
- affectsEmit: true,
- isTSConfigOnly: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Enable_project_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "tsBuildInfoFile",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.FILE,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
- transpileOptionValue: undefined
- },
- {
- name: "removeComments",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Do_not_emit_comments_to_output,
- },
- {
- name: "noEmit",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Do_not_emit_outputs,
- transpileOptionValue: undefined
- },
- {
- name: "importHelpers",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Import_emit_helpers_from_tslib
- },
- {
- name: "importsNotUsedAsValues",
- type: ts.createMapFromTemplate({
- remove: 0 /* Remove */,
- preserve: 1 /* Preserve */,
- error: 2 /* Error */
- }),
- affectsEmit: true,
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
- },
- {
- name: "downlevelIteration",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
- },
- {
- name: "isolatedModules",
- type: "boolean",
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
- transpileOptionValue: true
- },
- // Strict Type Checks
- {
- name: "strict",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_all_strict_type_checking_options
- },
- {
- name: "noImplicitAny",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
- },
- {
- name: "strictNullChecks",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_null_checks
- },
- {
- name: "strictFunctionTypes",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_checking_of_function_types
- },
- {
- name: "strictBindCallApply",
- type: "boolean",
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
- },
- {
- name: "strictPropertyInitialization",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
- },
- {
- name: "noImplicitThis",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
- },
- {
- name: "alwaysStrict",
- type: "boolean",
- affectsSourceFile: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- 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",
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_errors_on_unused_locals,
- },
- {
- name: "noUnusedParameters",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_errors_on_unused_parameters,
- },
- {
- name: "noImplicitReturns",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
- },
- {
- name: "noFallthroughCasesInSwitch",
- type: "boolean",
- affectsBindDiagnostics: true,
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
- },
- // Module Resolution
- {
- name: "moduleResolution",
- type: ts.createMapFromTemplate({
- node: ts.ModuleResolutionKind.NodeJs,
- classic: ts.ModuleResolutionKind.Classic,
- }),
- affectsModuleResolution: true,
- paramType: ts.Diagnostics.STRATEGY,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
- },
- {
- name: "baseUrl",
- type: "string",
- affectsModuleResolution: true,
- isFilePath: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- 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",
- affectsModuleResolution: true,
- isTSConfigOnly: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
- transpileOptionValue: undefined
- },
- {
- // this option can only be specified in tsconfig.json
- // use type = object to copy the value as-is
- name: "rootDirs",
- type: "list",
- isTSConfigOnly: true,
- element: {
- name: "rootDirs",
- type: "string",
- isFilePath: true
- },
- affectsModuleResolution: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
- transpileOptionValue: undefined
- },
- {
- name: "typeRoots",
- type: "list",
- element: {
- name: "typeRoots",
- type: "string",
- isFilePath: true
- },
- affectsModuleResolution: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
- },
- {
- name: "types",
- type: "list",
- element: {
- name: "types",
- type: "string"
+ function getEmitFlags(node) {
+ var emitNode = node.emitNode;
+ return emitNode && emitNode.flags || 0;
+ }
+ ts.getEmitFlags = getEmitFlags;
+ ;
+ function getScriptTargetFeatures() {
+ return {
+ es2015: {
+ Array: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"],
+ RegExp: ["flags", "sticky", "unicode"],
+ Reflect: ["apply", "construct", "defineProperty", "deleteProperty", "get", " getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"],
+ ArrayConstructor: ["from", "of"],
+ ObjectConstructor: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"],
+ NumberConstructor: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"],
+ Math: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"],
+ Map: ["entries", "keys", "values"],
+ Set: ["entries", "keys", "values"],
+ Promise: ts.emptyArray,
+ PromiseConstructor: ["all", "race", "reject", "resolve"],
+ Symbol: ["for", "keyFor"],
+ WeakMap: ["entries", "keys", "values"],
+ WeakSet: ["entries", "keys", "values"],
+ Iterator: ts.emptyArray,
+ AsyncIterator: ts.emptyArray,
+ String: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"],
+ StringConstructor: ["fromCodePoint", "raw"]
},
- affectsModuleResolution: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "allowSyntheticDefaultImports",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
- },
- {
- name: "esModuleInterop",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
- },
- {
- name: "preserveSymlinks",
- type: "boolean",
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
- },
- {
- name: "allowUmdGlobalAccess",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
- },
- // Source Maps
- {
- name: "sourceRoot",
- type: "string",
- affectsEmit: true,
- paramType: ts.Diagnostics.LOCATION,
- category: ts.Diagnostics.Source_Map_Options,
- description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
- },
- {
- name: "mapRoot",
- type: "string",
- affectsEmit: true,
- paramType: ts.Diagnostics.LOCATION,
- category: ts.Diagnostics.Source_Map_Options,
- description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
- },
- {
- name: "inlineSourceMap",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Source_Map_Options,
- description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
- },
- {
- name: "inlineSources",
- type: "boolean",
- affectsEmit: true,
- 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",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Experimental_Options,
- description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
- },
- {
- name: "emitDecoratorMetadata",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- category: ts.Diagnostics.Experimental_Options,
- description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
- },
- // Advanced
- {
- name: "jsxFactory",
- type: "string",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
- },
- {
- name: "resolveJsonModule",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Include_modules_imported_with_json_extension
- },
- {
- name: "out",
- type: "string",
- affectsEmit: true,
- 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,
- transpileOptionValue: undefined
- },
- {
- name: "reactNamespace",
- type: "string",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
- },
- {
- name: "skipDefaultLibCheck",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
- },
- {
- name: "charset",
- type: "string",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.The_character_set_of_the_input_files
- },
- {
- name: "emitBOM",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
- },
- {
- name: "newLine",
- type: ts.createMapFromTemplate({
- crlf: 0 /* CarriageReturnLineFeed */,
- lf: 1 /* LineFeed */
- }),
- affectsEmit: true,
- paramType: ts.Diagnostics.NEWLINE,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
- },
- {
- name: "noErrorTruncation",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_truncate_error_messages
- },
- {
- name: "noLib",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
- // We are not returning a sourceFile for lib file when asked by the program,
- // so pass --noLib to avoid reporting a file not found error.
- transpileOptionValue: true
- },
- {
- name: "noResolve",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
- // We are not doing a full typecheck, we are not resolving the whole context,
- // so pass --noResolve to avoid reporting missing file errors.
- transpileOptionValue: true
- },
- {
- name: "stripInternal",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
- },
- {
- name: "disableSizeLimit",
- type: "boolean",
- affectsSourceFile: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
- },
- {
- name: "disableSourceOfProjectReferenceRedirect",
- type: "boolean",
- isTSConfigOnly: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
- },
- {
- name: "disableSolutionSearching",
- type: "boolean",
- isTSConfigOnly: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_solution_searching_for_this_project
- },
- {
- name: "noImplicitUseStrict",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
- },
- {
- name: "noEmitHelpers",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
- },
- {
- name: "noEmitOnError",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
- transpileOptionValue: undefined
- },
- {
- name: "preserveConstEnums",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
- },
- {
- name: "declarationDir",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.DIRECTORY,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
- transpileOptionValue: undefined
- },
- {
- name: "skipLibCheck",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
- },
- {
- name: "allowUnusedLabels",
- type: "boolean",
- affectsBindDiagnostics: true,
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
- },
- {
- name: "allowUnreachableCode",
- type: "boolean",
- affectsBindDiagnostics: true,
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
- },
- {
- name: "suppressExcessPropertyErrors",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
- },
- {
- name: "suppressImplicitAnyIndexErrors",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
- },
- {
- name: "forceConsistentCasingInFileNames",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
- },
- {
- name: "maxNodeModuleJsDepth",
- type: "number",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
- },
- {
- name: "noStrictGenericChecks",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
- },
- {
- name: "useDefineForClassFields",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
- },
- {
- name: "keyofStringsOnly",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- 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,
- element: {
- name: "plugin",
- type: "object"
+ es2016: {
+ Array: ["includes"]
+ },
+ es2017: {
+ Atomics: ts.emptyArray,
+ SharedArrayBuffer: ts.emptyArray,
+ String: ["padStart", "padEnd"],
+ ObjectConstructor: ["values", "entries", "getOwnPropertyDescriptors"],
+ DateTimeFormat: ["formatToParts"]
+ },
+ es2018: {
+ Promise: ["finally"],
+ RegExpMatchArray: ["groups"],
+ RegExpExecArray: ["groups"],
+ RegExp: ["dotAll"],
+ Intl: ["PluralRules"],
+ AsyncIterable: ts.emptyArray,
+ AsyncIterableIterator: ts.emptyArray,
+ AsyncGenerator: ts.emptyArray,
+ AsyncGeneratorFunction: ts.emptyArray,
+ },
+ es2019: {
+ Array: ["flat", "flatMap"],
+ ObjectConstructor: ["fromEntries"],
+ String: ["trimStart", "trimEnd", "trimLeft", "trimRight"],
+ Symbol: ["description"]
+ },
+ es2020: {
+ BigInt: ts.emptyArray,
+ BigInt64Array: ts.emptyArray,
+ BigUint64Array: ts.emptyArray,
+ PromiseConstructor: ["allSettled"],
+ SymbolConstructor: ["matchAll"],
+ String: ["matchAll"],
+ DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"],
+ RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"]
+ },
+ es2021: {
+ PromiseConstructor: ["any"],
+ String: ["replaceAll"]
+ },
+ esnext: {
+ NumberFormat: ["formatToParts"]
+ }
+ };
+ }
+ ts.getScriptTargetFeatures = getScriptTargetFeatures;
+ var GetLiteralTextFlags;
+ (function (GetLiteralTextFlags) {
+ GetLiteralTextFlags[GetLiteralTextFlags["None"] = 0] = "None";
+ GetLiteralTextFlags[GetLiteralTextFlags["NeverAsciiEscape"] = 1] = "NeverAsciiEscape";
+ GetLiteralTextFlags[GetLiteralTextFlags["JsxAttributeEscape"] = 2] = "JsxAttributeEscape";
+ GetLiteralTextFlags[GetLiteralTextFlags["TerminateUnterminatedLiterals"] = 4] = "TerminateUnterminatedLiterals";
+ GetLiteralTextFlags[GetLiteralTextFlags["AllowNumericSeparator"] = 8] = "AllowNumericSeparator";
+ })(GetLiteralTextFlags = ts.GetLiteralTextFlags || (ts.GetLiteralTextFlags = {}));
+ function getLiteralText(node, sourceFile, flags) {
+ var _a;
+ // 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 (canUseOriginalText(node, flags)) {
+ return getSourceTextOfNodeFromSourceFile(sourceFile, node);
+ }
+ // 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 10 /* StringLiteral */: {
+ var escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString :
+ flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
+ escapeNonAsciiString;
+ if (node.singleQuote) {
+ return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
+ }
+ else {
+ return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
+ }
+ }
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 15 /* TemplateHead */:
+ case 16 /* TemplateMiddle */:
+ case 17 /* TemplateTail */: {
+ // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
+ // had to include a backslash: `not \${a} substitution`.
+ var escapeText = flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
+ escapeNonAsciiString;
+ var rawText = (_a = node.rawText) !== null && _a !== void 0 ? _a : escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
+ switch (node.kind) {
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ return "`" + rawText + "`";
+ case 15 /* TemplateHead */:
+ return "`" + rawText + "${";
+ case 16 /* TemplateMiddle */:
+ return "}" + rawText + "${";
+ case 17 /* TemplateTail */:
+ return "}" + rawText + "`";
+ }
+ break;
+ }
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ return node.text;
+ case 13 /* RegularExpressionLiteral */:
+ if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) {
+ return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/");
+ }
+ return node.text;
+ }
+ return ts.Debug.fail("Literal kind '".concat(node.kind, "' not accounted for."));
+ }
+ ts.getLiteralText = getLiteralText;
+ function canUseOriginalText(node, flags) {
+ if (nodeIsSynthesized(node) || !node.parent || (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated)) {
+ return false;
+ }
+ if (ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) {
+ return !!(flags & 8 /* AllowNumericSeparator */);
+ }
+ return !ts.isBigIntLiteral(node);
+ }
+ function getTextOfConstantValue(value) {
+ return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
+ }
+ ts.getTextOfConstantValue = getTextOfConstantValue;
+ // 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 /* BlockScoped */) !== 0 ||
+ isCatchClauseVariableDeclarationOrBindingElement(declaration);
+ }
+ ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
+ function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
+ var node = getRootDeclaration(declaration);
+ return node.kind === 253 /* VariableDeclaration */ && node.parent.kind === 291 /* CatchClause */;
+ }
+ ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
+ function isAmbientModule(node) {
+ return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
+ }
+ ts.isAmbientModule = isAmbientModule;
+ function isModuleWithStringLiteralName(node) {
+ return ts.isModuleDeclaration(node) && node.name.kind === 10 /* 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) {
+ // The only kind of module that can be missing a body is a shorthand ambient module.
+ return !!node && node.kind === 260 /* ModuleDeclaration */ && (!node.body);
+ }
+ function isBlockScopedContainerTopLevel(node) {
+ return node.kind === 303 /* SourceFile */ ||
+ node.kind === 260 /* ModuleDeclaration */ ||
+ ts.isFunctionLikeOrClassStaticBlockDeclaration(node);
+ }
+ ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
+ function isGlobalScopeAugmentation(module) {
+ return !!(module.flags & 1024 /* GlobalAugmentation */);
+ }
+ ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
+ function isExternalModuleAugmentation(node) {
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ 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 303 /* SourceFile */:
+ return ts.isExternalModule(node.parent);
+ case 261 /* ModuleBlock */:
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ }
+ return false;
+ }
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
+ function getNonAugmentationDeclaration(symbol) {
+ var _a;
+ return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
+ }
+ ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
+ function isCommonJSContainingModuleKind(kind) {
+ return kind === ts.ModuleKind.CommonJS || kind === ts.ModuleKind.Node12 || kind === ts.ModuleKind.NodeNext;
+ }
+ function isEffectiveExternalModule(node, compilerOptions) {
+ return ts.isExternalModule(node) || compilerOptions.isolatedModules || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator);
+ }
+ ts.isEffectiveExternalModule = isEffectiveExternalModule;
+ /**
+ * Returns whether the source file will be treated as if it were in strict mode at runtime.
+ */
+ function isEffectiveStrictModeSourceFile(node, compilerOptions) {
+ // We can only verify strict mode for JS/TS files
+ switch (node.scriptKind) {
+ case 1 /* JS */:
+ case 3 /* TS */:
+ case 2 /* JSX */:
+ case 4 /* TSX */:
+ break;
+ default:
+ return false;
+ }
+ // Strict mode does not matter for declaration files.
+ if (node.isDeclarationFile) {
+ return false;
+ }
+ // If `alwaysStrict` is set, then treat the file as strict.
+ if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
+ return true;
+ }
+ // Starting with a "use strict" directive indicates the file is strict.
+ if (ts.startsWithUseStrict(node.statements)) {
+ return true;
+ }
+ if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
+ // ECMAScript Modules are always strict.
+ if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
+ return true;
+ }
+ // Other modules are strict unless otherwise specified.
+ return !compilerOptions.noImplicitUseStrict;
+ }
+ return false;
+ }
+ ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
+ function isBlockScope(node, parentNode) {
+ switch (node.kind) {
+ case 303 /* SourceFile */:
+ case 262 /* CaseBlock */:
+ case 291 /* CatchClause */:
+ case 260 /* ModuleDeclaration */:
+ case 241 /* ForStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ case 170 /* Constructor */:
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ case 166 /* PropertyDeclaration */:
+ case 169 /* ClassStaticBlockDeclaration */:
+ return true;
+ case 234 /* Block */:
+ // function block is not considered block-scope container
+ // see comment in binder.ts: bind(...), case for SyntaxKind.Block
+ return !ts.isFunctionLikeOrClassStaticBlockDeclaration(parentNode);
+ }
+ return false;
+ }
+ ts.isBlockScope = isBlockScope;
+ function isDeclarationWithTypeParameters(node) {
+ switch (node.kind) {
+ case 336 /* JSDocCallbackTag */:
+ case 343 /* JSDocTypedefTag */:
+ case 321 /* JSDocSignature */:
+ return true;
+ default:
+ ts.assertType(node);
+ return isDeclarationWithTypeParameterChildren(node);
+ }
+ }
+ ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
+ function isDeclarationWithTypeParameterChildren(node) {
+ switch (node.kind) {
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 167 /* MethodSignature */:
+ case 175 /* IndexSignature */:
+ case 178 /* FunctionType */:
+ case 179 /* ConstructorType */:
+ case 315 /* JSDocFunctionType */:
+ case 256 /* ClassDeclaration */:
+ case 225 /* ClassExpression */:
+ case 257 /* InterfaceDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ case 342 /* JSDocTemplateTag */:
+ case 255 /* FunctionDeclaration */:
+ case 168 /* MethodDeclaration */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ return true;
+ default:
+ ts.assertType(node);
+ return false;
+ }
+ }
+ ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
+ function isAnyImportSyntax(node) {
+ switch (node.kind) {
+ case 265 /* ImportDeclaration */:
+ case 264 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isAnyImportSyntax = isAnyImportSyntax;
+ function isLateVisibilityPaintedStatement(node) {
+ switch (node.kind) {
+ case 265 /* ImportDeclaration */:
+ case 264 /* ImportEqualsDeclaration */:
+ case 236 /* VariableStatement */:
+ case 256 /* ClassDeclaration */:
+ case 255 /* FunctionDeclaration */:
+ case 260 /* ModuleDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ case 257 /* InterfaceDeclaration */:
+ case 259 /* EnumDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
+ function hasPossibleExternalModuleReference(node) {
+ return isAnyImportOrReExport(node) || ts.isModuleDeclaration(node) || ts.isImportTypeNode(node) || isImportCall(node);
+ }
+ ts.hasPossibleExternalModuleReference = hasPossibleExternalModuleReference;
+ function isAnyImportOrReExport(node) {
+ 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 ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
+ }
+ ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
+ function forEachEnclosingBlockScopeContainer(node, cb) {
+ var container = getEnclosingBlockScopeContainer(node);
+ while (container) {
+ cb(container);
+ container = getEnclosingBlockScopeContainer(container);
+ }
+ }
+ ts.forEachEnclosingBlockScopeContainer = forEachEnclosingBlockScopeContainer;
+ // 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 !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
+ }
+ ts.declarationNameToString = declarationNameToString;
+ function getNameFromIndexInfo(info) {
+ return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
+ }
+ ts.getNameFromIndexInfo = getNameFromIndexInfo;
+ function isComputedNonLiteralName(name) {
+ return name.kind === 161 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
+ }
+ ts.isComputedNonLiteralName = isComputedNonLiteralName;
+ function getTextOfPropertyName(name) {
+ switch (name.kind) {
+ case 79 /* Identifier */:
+ case 80 /* PrivateIdentifier */:
+ return name.escapedText;
+ case 10 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ return ts.escapeLeadingUnderscores(name.text);
+ case 161 /* ComputedPropertyName */:
+ if (isStringOrNumericLiteralLike(name.expression))
+ return ts.escapeLeadingUnderscores(name.expression.text);
+ return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
+ default:
+ return ts.Debug.assertNever(name);
+ }
+ }
+ ts.getTextOfPropertyName = getTextOfPropertyName;
+ function entityNameToString(name) {
+ switch (name.kind) {
+ case 108 /* ThisKeyword */:
+ return "this";
+ case 80 /* PrivateIdentifier */:
+ case 79 /* Identifier */:
+ return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
+ case 160 /* QualifiedName */:
+ return entityNameToString(name.left) + "." + entityNameToString(name.right);
+ case 205 /* PropertyAccessExpression */:
+ if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
+ return entityNameToString(name.expression) + "." + entityNameToString(name.name);
+ }
+ else {
+ return ts.Debug.assertNever(name.name);
+ }
+ case 309 /* JSDocMemberName */:
+ return entityNameToString(name.left) + entityNameToString(name.right);
+ default:
+ return ts.Debug.assertNever(name);
+ }
+ }
+ ts.entityNameToString = entityNameToString;
+ function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
+ var sourceFile = getSourceFileOfNode(node);
+ return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
+ }
+ ts.createDiagnosticForNode = createDiagnosticForNode;
+ function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
+ var start = ts.skipTrivia(sourceFile.text, nodes.pos);
+ return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
+ }
+ ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
+ function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
+ var span = getErrorSpanForNode(sourceFile, node);
+ return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
+ }
+ ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
+ function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
+ var sourceFile = getSourceFileOfNode(node);
+ var span = getErrorSpanForNode(sourceFile, node);
+ return createFileDiagnosticFromMessageChain(sourceFile, span.start, span.length, messageChain, relatedInformation);
+ }
+ ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
+ function assertDiagnosticLocation(file, start, length) {
+ ts.Debug.assertGreaterThanOrEqual(start, 0);
+ ts.Debug.assertGreaterThanOrEqual(length, 0);
+ if (file) {
+ ts.Debug.assertLessThanOrEqual(start, file.text.length);
+ ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
+ }
+ }
+ function createFileDiagnosticFromMessageChain(file, start, length, messageChain, relatedInformation) {
+ assertDiagnosticLocation(file, start, length);
+ return {
+ file: file,
+ start: start,
+ length: length,
+ code: messageChain.code,
+ category: messageChain.category,
+ messageText: messageChain.next ? messageChain : messageChain.messageText,
+ relatedInformation: relatedInformation
+ };
+ }
+ ts.createFileDiagnosticFromMessageChain = createFileDiagnosticFromMessageChain;
+ function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) {
+ return {
+ file: sourceFile,
+ start: 0,
+ length: 0,
+ code: messageChain.code,
+ category: messageChain.category,
+ messageText: messageChain.next ? messageChain : messageChain.messageText,
+ relatedInformation: relatedInformation
+ };
+ }
+ ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain;
+ function createDiagnosticForRange(sourceFile, range, message) {
+ return {
+ file: sourceFile,
+ start: range.pos,
+ length: range.end - range.pos,
+ code: message.code,
+ category: message.category,
+ messageText: message.message,
+ };
+ }
+ ts.createDiagnosticForRange = createDiagnosticForRange;
+ function getSpanOfTokenAtPosition(sourceFile, 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());
+ }
+ ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
+ function getErrorSpanForArrowFunction(sourceFile, node) {
+ var pos = ts.skipTrivia(sourceFile.text, node.pos);
+ if (node.body && node.body.kind === 234 /* 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);
+ }
+ }
+ return ts.createTextSpanFromBounds(pos, node.end);
+ }
+ function getErrorSpanForNode(sourceFile, node) {
+ var errorNode = node;
+ switch (node.kind) {
+ case 303 /* 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);
+ // This list is a work in progress. Add missing node kinds to improve their error
+ // spans.
+ case 253 /* VariableDeclaration */:
+ case 202 /* BindingElement */:
+ case 256 /* ClassDeclaration */:
+ case 225 /* ClassExpression */:
+ case 257 /* InterfaceDeclaration */:
+ case 260 /* ModuleDeclaration */:
+ case 259 /* EnumDeclaration */:
+ case 297 /* EnumMember */:
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 258 /* TypeAliasDeclaration */:
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 267 /* NamespaceImport */:
+ errorNode = node.name;
+ break;
+ case 213 /* ArrowFunction */:
+ return getErrorSpanForArrowFunction(sourceFile, node);
+ case 288 /* CaseClause */:
+ case 289 /* DefaultClause */:
+ var start = ts.skipTrivia(sourceFile.text, node.pos);
+ var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
+ return ts.createTextSpanFromBounds(start, end);
+ }
+ 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);
+ }
+ ts.Debug.assert(!ts.isJSDoc(errorNode));
+ var isMissing = nodeIsMissing(errorNode);
+ var pos = isMissing || ts.isJsxText(node)
+ ? 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");
+ }
+ else {
+ 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");
+ }
+ return ts.createTextSpanFromBounds(pos, errorNode.end);
+ }
+ ts.getErrorSpanForNode = getErrorSpanForNode;
+ function isExternalOrCommonJsModule(file) {
+ return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
+ }
+ ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6 /* JSON */;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
+ function isEnumConst(node) {
+ return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
+ }
+ ts.isEnumConst = isEnumConst;
+ function isDeclarationReadonly(declaration) {
+ return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
+ }
+ ts.isDeclarationReadonly = isDeclarationReadonly;
+ function isVarConst(node) {
+ return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
+ }
+ ts.isVarConst = isVarConst;
+ function isLet(node) {
+ return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
+ }
+ ts.isLet = isLet;
+ function isSuperCall(n) {
+ return n.kind === 207 /* CallExpression */ && n.expression.kind === 106 /* SuperKeyword */;
+ }
+ ts.isSuperCall = isSuperCall;
+ function isImportCall(n) {
+ return n.kind === 207 /* CallExpression */ && n.expression.kind === 100 /* ImportKeyword */;
+ }
+ ts.isImportCall = isImportCall;
+ function isImportMeta(n) {
+ return ts.isMetaProperty(n)
+ && n.keywordToken === 100 /* ImportKeyword */
+ && n.name.escapedText === "meta";
+ }
+ ts.isImportMeta = isImportMeta;
+ function isLiteralImportTypeNode(n) {
+ return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
+ }
+ ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
+ function isPrologueDirective(node) {
+ return node.kind === 237 /* ExpressionStatement */
+ && node.expression.kind === 10 /* StringLiteral */;
+ }
+ ts.isPrologueDirective = isPrologueDirective;
+ function isCustomPrologue(node) {
+ return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ ts.isCustomPrologue = isCustomPrologue;
+ function isHoistedFunction(node) {
+ return isCustomPrologue(node)
+ && ts.isFunctionDeclaration(node);
+ }
+ ts.isHoistedFunction = isHoistedFunction;
+ function isHoistedVariable(node) {
+ return ts.isIdentifier(node.name)
+ && !node.initializer;
+ }
+ function isHoistedVariableStatement(node) {
+ return isCustomPrologue(node)
+ && ts.isVariableStatement(node)
+ && ts.every(node.declarationList.declarations, isHoistedVariable);
+ }
+ ts.isHoistedVariableStatement = isHoistedVariableStatement;
+ function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
+ return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
+ }
+ ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
+ function getJSDocCommentRanges(node, text) {
+ var commentRanges = (node.kind === 163 /* Parameter */ ||
+ node.kind === 162 /* TypeParameter */ ||
+ node.kind === 212 /* FunctionExpression */ ||
+ node.kind === 213 /* ArrowFunction */ ||
+ node.kind === 211 /* ParenthesizedExpression */ ||
+ node.kind === 253 /* VariableDeclaration */) ?
+ 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 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
+ text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
+ });
+ }
+ ts.getJSDocCommentRanges = getJSDocCommentRanges;
+ ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/;
+ var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/;
+ ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/;
+ var defaultLibReferenceRegEx = /^(\/\/\/\s*/;
+ function isPartOfTypeNode(node) {
+ if (176 /* FirstTypeNode */ <= node.kind && node.kind <= 199 /* LastTypeNode */) {
+ return true;
+ }
+ switch (node.kind) {
+ case 130 /* AnyKeyword */:
+ case 154 /* UnknownKeyword */:
+ case 146 /* NumberKeyword */:
+ case 157 /* BigIntKeyword */:
+ case 149 /* StringKeyword */:
+ case 133 /* BooleanKeyword */:
+ case 150 /* SymbolKeyword */:
+ case 147 /* ObjectKeyword */:
+ case 152 /* UndefinedKeyword */:
+ case 143 /* NeverKeyword */:
+ return true;
+ case 114 /* VoidKeyword */:
+ return node.parent.kind !== 216 /* VoidExpression */;
+ case 227 /* ExpressionWithTypeArguments */:
+ return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
+ case 162 /* TypeParameter */:
+ return node.parent.kind === 194 /* MappedType */ || node.parent.kind === 189 /* InferType */;
+ // Identifiers and qualified names may be type nodes, depending on their context. Climb
+ // above them to find the lowest container
+ case 79 /* Identifier */:
+ // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
+ if (node.parent.kind === 160 /* QualifiedName */ && node.parent.right === node) {
+ node = node.parent;
+ }
+ else if (node.parent.kind === 205 /* PropertyAccessExpression */ && node.parent.name === node) {
+ node = node.parent;
+ }
+ // At this point, node is either a qualified name or an identifier
+ ts.Debug.assert(node.kind === 79 /* Identifier */ || node.kind === 160 /* QualifiedName */ || node.kind === 205 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
+ // falls through
+ case 160 /* QualifiedName */:
+ case 205 /* PropertyAccessExpression */:
+ case 108 /* ThisKeyword */: {
+ var parent = node.parent;
+ if (parent.kind === 180 /* TypeQuery */) {
+ return false;
+ }
+ if (parent.kind === 199 /* ImportType */) {
+ return !parent.isTypeOf;
+ }
+ // 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 (176 /* FirstTypeNode */ <= parent.kind && parent.kind <= 199 /* LastTypeNode */) {
+ return true;
+ }
+ switch (parent.kind) {
+ case 227 /* ExpressionWithTypeArguments */:
+ return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
+ case 162 /* TypeParameter */:
+ return node === parent.constraint;
+ case 342 /* JSDocTemplateTag */:
+ return node === parent.constraint;
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 163 /* Parameter */:
+ case 253 /* VariableDeclaration */:
+ return node === parent.type;
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ case 170 /* Constructor */:
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ return node === parent.type;
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 175 /* IndexSignature */:
+ return node === parent.type;
+ case 210 /* TypeAssertionExpression */:
+ return node === parent.type;
+ case 207 /* CallExpression */:
+ case 208 /* NewExpression */:
+ return ts.contains(parent.typeArguments, node);
+ case 209 /* TaggedTemplateExpression */:
+ // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
+ return false;
+ }
+ }
+ }
+ return false;
+ }
+ ts.isPartOfTypeNode = isPartOfTypeNode;
+ function isChildOfNodeWithKind(node, kind) {
+ while (node) {
+ if (node.kind === kind) {
+ return true;
+ }
+ node = node.parent;
+ }
+ 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 246 /* ReturnStatement */:
+ return visitor(node);
+ case 262 /* CaseBlock */:
+ case 234 /* Block */:
+ case 238 /* IfStatement */:
+ case 239 /* DoStatement */:
+ case 240 /* WhileStatement */:
+ case 241 /* ForStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ case 247 /* WithStatement */:
+ case 248 /* SwitchStatement */:
+ case 288 /* CaseClause */:
+ case 289 /* DefaultClause */:
+ case 249 /* LabeledStatement */:
+ case 251 /* TryStatement */:
+ case 291 /* CatchClause */:
+ return ts.forEachChild(node, traverse);
+ }
+ }
+ }
+ ts.forEachReturnStatement = forEachReturnStatement;
+ function forEachYieldExpression(body, visitor) {
+ return traverse(body);
+ function traverse(node) {
+ switch (node.kind) {
+ case 223 /* YieldExpression */:
+ visitor(node);
+ var operand = node.expression;
+ if (operand) {
+ traverse(operand);
+ }
+ return;
+ case 259 /* EnumDeclaration */:
+ case 257 /* InterfaceDeclaration */:
+ case 260 /* ModuleDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ // These are not allowed inside a generator now, but eventually they may be allowed
+ // as local types. Regardless, skip them to avoid the work.
+ return;
+ default:
+ if (ts.isFunctionLike(node)) {
+ if (node.name && node.name.kind === 161 /* 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 === 182 /* ArrayType */) {
+ return node.elementType;
+ }
+ else if (node && node.kind === 177 /* TypeReference */) {
+ return ts.singleOrUndefined(node.typeArguments);
+ }
+ else {
+ return undefined;
+ }
+ }
+ ts.getRestParameterElementType = getRestParameterElementType;
+ function getMembersOfDeclaration(node) {
+ switch (node.kind) {
+ case 257 /* InterfaceDeclaration */:
+ case 256 /* ClassDeclaration */:
+ case 225 /* ClassExpression */:
+ case 181 /* TypeLiteral */:
+ return node.members;
+ case 204 /* ObjectLiteralExpression */:
+ return node.properties;
+ }
+ }
+ ts.getMembersOfDeclaration = getMembersOfDeclaration;
+ function isVariableLike(node) {
+ if (node) {
+ switch (node.kind) {
+ case 202 /* BindingElement */:
+ case 297 /* EnumMember */:
+ case 163 /* Parameter */:
+ case 294 /* PropertyAssignment */:
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 295 /* ShorthandPropertyAssignment */:
+ case 253 /* VariableDeclaration */:
+ return true;
+ }
+ }
+ return false;
+ }
+ ts.isVariableLike = isVariableLike;
+ function isVariableLikeOrAccessor(node) {
+ return isVariableLike(node) || ts.isAccessor(node);
+ }
+ ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
+ function isVariableDeclarationInVariableStatement(node) {
+ return node.parent.kind === 254 /* VariableDeclarationList */
+ && node.parent.parent.kind === 236 /* VariableStatement */;
+ }
+ ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
+ function isValidESSymbolDeclaration(node) {
+ return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
+ ts.isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) :
+ ts.isPropertySignature(node) && hasEffectiveReadonlyModifier(node);
+ }
+ ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
+ function introducesArgumentsExoticObject(node) {
+ switch (node.kind) {
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ return true;
+ }
+ return false;
+ }
+ ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
+ function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
+ while (true) {
+ if (beforeUnwrapLabelCallback) {
+ beforeUnwrapLabelCallback(node);
+ }
+ if (node.statement.kind !== 249 /* LabeledStatement */) {
+ return node.statement;
+ }
+ node = node.statement;
+ }
+ }
+ ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
+ function isFunctionBlock(node) {
+ return node && node.kind === 234 /* Block */ && ts.isFunctionLike(node.parent);
+ }
+ ts.isFunctionBlock = isFunctionBlock;
+ function isObjectLiteralMethod(node) {
+ return node && node.kind === 168 /* MethodDeclaration */ && node.parent.kind === 204 /* ObjectLiteralExpression */;
+ }
+ ts.isObjectLiteralMethod = isObjectLiteralMethod;
+ function isObjectLiteralOrClassExpressionMethodOrAccessor(node) {
+ return (node.kind === 168 /* MethodDeclaration */ || node.kind === 171 /* GetAccessor */ || node.kind === 172 /* SetAccessor */) &&
+ (node.parent.kind === 204 /* ObjectLiteralExpression */ ||
+ node.parent.kind === 225 /* ClassExpression */);
+ }
+ ts.isObjectLiteralOrClassExpressionMethodOrAccessor = isObjectLiteralOrClassExpressionMethodOrAccessor;
+ function isIdentifierTypePredicate(predicate) {
+ return predicate && predicate.kind === 1 /* Identifier */;
+ }
+ ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
+ function isThisTypePredicate(predicate) {
+ return predicate && predicate.kind === 0 /* This */;
+ }
+ ts.isThisTypePredicate = isThisTypePredicate;
+ function getPropertyAssignment(objectLiteral, key, key2) {
+ return objectLiteral.properties.filter(function (property) {
+ if (property.kind === 294 /* PropertyAssignment */) {
+ var propName = getTextOfPropertyName(property.name);
+ return key === propName || (!!key2 && key2 === propName);
+ }
+ return false;
+ });
+ }
+ ts.getPropertyAssignment = getPropertyAssignment;
+ function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) {
+ return ts.firstDefined(getPropertyAssignment(objectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getPropertyArrayElementValue = getPropertyArrayElementValue;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.tryCast(expression, ts.isObjectLiteralExpression);
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
+ function getTsConfigPropArray(tsConfigSourceFile, propKey) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
+ }
+ ts.getTsConfigPropArray = getTsConfigPropArray;
+ function getContainingFunction(node) {
+ return ts.findAncestor(node.parent, ts.isFunctionLike);
+ }
+ ts.getContainingFunction = getContainingFunction;
+ function getContainingFunctionDeclaration(node) {
+ return ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
+ }
+ ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
+ function getContainingClass(node) {
+ return ts.findAncestor(node.parent, ts.isClassLike);
+ }
+ ts.getContainingClass = getContainingClass;
+ function getContainingClassStaticBlock(node) {
+ return ts.findAncestor(node.parent, function (n) {
+ if (ts.isClassLike(n) || ts.isFunctionLike(n)) {
+ return "quit";
+ }
+ return ts.isClassStaticBlockDeclaration(n);
+ });
+ }
+ ts.getContainingClassStaticBlock = getContainingClassStaticBlock;
+ function getContainingFunctionOrClassStaticBlock(node) {
+ return ts.findAncestor(node.parent, ts.isFunctionLikeOrClassStaticBlockDeclaration);
+ }
+ ts.getContainingFunctionOrClassStaticBlock = getContainingFunctionOrClassStaticBlock;
+ function getThisContainer(node, includeArrowFunctions) {
+ ts.Debug.assert(node.kind !== 303 /* SourceFile */);
+ while (true) {
+ node = node.parent;
+ if (!node) {
+ 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 161 /* 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 164 /* Decorator */:
+ // Decorators are always applied outside of the body of a class or method.
+ if (node.parent.kind === 163 /* 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 213 /* ArrowFunction */:
+ if (!includeArrowFunctions) {
+ continue;
+ }
+ // falls through
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 260 /* ModuleDeclaration */:
+ case 169 /* ClassStaticBlockDeclaration */:
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 175 /* IndexSignature */:
+ case 259 /* EnumDeclaration */:
+ case 303 /* SourceFile */:
+ return node;
+ }
+ }
+ }
+ ts.getThisContainer = getThisContainer;
+ function isInTopLevelContext(node) {
+ // The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
+ if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) {
+ node = node.parent;
+ }
+ var container = getThisContainer(node, /*includeArrowFunctions*/ true);
+ return ts.isSourceFile(container);
+ }
+ ts.isInTopLevelContext = isInTopLevelContext;
+ function getNewTargetContainer(node) {
+ var container = getThisContainer(node, /*includeArrowFunctions*/ false);
+ if (container) {
+ switch (container.kind) {
+ case 170 /* Constructor */:
+ case 255 /* FunctionDeclaration */:
+ case 212 /* 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;
+ if (!node) {
+ return node;
+ }
+ switch (node.kind) {
+ case 161 /* ComputedPropertyName */:
+ node = node.parent;
+ break;
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ if (!stopOnFunctions) {
+ continue;
+ }
+ // falls through
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 169 /* ClassStaticBlockDeclaration */:
+ return node;
+ case 164 /* Decorator */:
+ // Decorators are always applied outside of the body of a class or method.
+ if (node.parent.kind === 163 /* 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;
+ }
+ }
+ }
+ ts.getSuperContainer = getSuperContainer;
+ function getImmediatelyInvokedFunctionExpression(func) {
+ if (func.kind === 212 /* FunctionExpression */ || func.kind === 213 /* ArrowFunction */) {
+ var prev = func;
+ var parent = func.parent;
+ while (parent.kind === 211 /* ParenthesizedExpression */) {
+ prev = parent;
+ parent = parent.parent;
+ }
+ if (parent.kind === 207 /* CallExpression */ && parent.expression === prev) {
+ return parent;
+ }
+ }
+ }
+ ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 106 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
+ /**
+ * Determines whether a node is a property or element access expression for `super`.
+ */
+ function isSuperProperty(node) {
+ var kind = node.kind;
+ return (kind === 205 /* PropertyAccessExpression */ || kind === 206 /* ElementAccessExpression */)
+ && node.expression.kind === 106 /* 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 === 205 /* PropertyAccessExpression */ || kind === 206 /* ElementAccessExpression */)
+ && node.expression.kind === 108 /* ThisKeyword */;
+ }
+ ts.isThisProperty = isThisProperty;
+ function isThisInitializedDeclaration(node) {
+ var _a;
+ return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 108 /* ThisKeyword */;
+ }
+ ts.isThisInitializedDeclaration = isThisInitializedDeclaration;
+ function isThisInitializedObjectBindingExpression(node) {
+ return !!node
+ && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node))
+ && ts.isBinaryExpression(node.parent.parent)
+ && node.parent.parent.operatorToken.kind === 63 /* EqualsToken */
+ && node.parent.parent.right.kind === 108 /* ThisKeyword */;
+ }
+ ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression;
+ function getEntityNameFromTypeNode(node) {
+ switch (node.kind) {
+ case 177 /* TypeReference */:
+ return node.typeName;
+ case 227 /* ExpressionWithTypeArguments */:
+ return isEntityNameExpression(node.expression)
+ ? node.expression
+ : undefined;
+ // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
+ case 79 /* Identifier */:
+ case 160 /* QualifiedName */:
+ return node;
+ }
+ return undefined;
+ }
+ ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
+ function getInvokedExpression(node) {
+ switch (node.kind) {
+ case 209 /* TaggedTemplateExpression */:
+ return node.tag;
+ case 279 /* JsxOpeningElement */:
+ case 278 /* JsxSelfClosingElement */:
+ return node.tagName;
+ default:
+ return node.expression;
+ }
+ }
+ ts.getInvokedExpression = getInvokedExpression;
+ function nodeCanBeDecorated(node, parent, grandparent) {
+ // private names cannot be used with decorators yet
+ if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
+ return false;
+ }
+ switch (node.kind) {
+ case 256 /* ClassDeclaration */:
+ // classes are valid targets
+ return true;
+ case 166 /* PropertyDeclaration */:
+ // property declarations are valid if their parent is a class declaration.
+ return parent.kind === 256 /* ClassDeclaration */;
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 168 /* 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 === 256 /* ClassDeclaration */;
+ case 163 /* 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 === 170 /* Constructor */
+ || parent.kind === 168 /* MethodDeclaration */
+ || parent.kind === 172 /* SetAccessor */)
+ && grandparent.kind === 256 /* ClassDeclaration */;
+ }
+ return false;
+ }
+ ts.nodeCanBeDecorated = nodeCanBeDecorated;
+ function nodeIsDecorated(node, parent, grandparent) {
+ return node.decorators !== undefined
+ && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
+ }
+ ts.nodeIsDecorated = nodeIsDecorated;
+ function nodeOrChildIsDecorated(node, parent, grandparent) {
+ return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
+ }
+ ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
+ function childIsDecorated(node, parent) {
+ switch (node.kind) {
+ case 256 /* ClassDeclaration */:
+ return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
+ case 168 /* MethodDeclaration */:
+ case 172 /* SetAccessor */:
+ case 170 /* Constructor */:
+ return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
+ default:
+ return false;
+ }
+ }
+ ts.childIsDecorated = childIsDecorated;
+ function classOrConstructorParameterIsDecorated(node) {
+ if (nodeIsDecorated(node))
+ return true;
+ var constructor = getFirstConstructorWithBody(node);
+ return !!constructor && childIsDecorated(constructor, node);
+ }
+ ts.classOrConstructorParameterIsDecorated = classOrConstructorParameterIsDecorated;
+ function isJSXTagName(node) {
+ var parent = node.parent;
+ if (parent.kind === 279 /* JsxOpeningElement */ ||
+ parent.kind === 278 /* JsxSelfClosingElement */ ||
+ parent.kind === 280 /* JsxClosingElement */) {
+ return parent.tagName === node;
+ }
+ return false;
+ }
+ ts.isJSXTagName = isJSXTagName;
+ function isExpressionNode(node) {
+ switch (node.kind) {
+ case 106 /* SuperKeyword */:
+ case 104 /* NullKeyword */:
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ case 13 /* RegularExpressionLiteral */:
+ case 203 /* ArrayLiteralExpression */:
+ case 204 /* ObjectLiteralExpression */:
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ case 207 /* CallExpression */:
+ case 208 /* NewExpression */:
+ case 209 /* TaggedTemplateExpression */:
+ case 228 /* AsExpression */:
+ case 210 /* TypeAssertionExpression */:
+ case 229 /* NonNullExpression */:
+ case 211 /* ParenthesizedExpression */:
+ case 212 /* FunctionExpression */:
+ case 225 /* ClassExpression */:
+ case 213 /* ArrowFunction */:
+ case 216 /* VoidExpression */:
+ case 214 /* DeleteExpression */:
+ case 215 /* TypeOfExpression */:
+ case 218 /* PrefixUnaryExpression */:
+ case 219 /* PostfixUnaryExpression */:
+ case 220 /* BinaryExpression */:
+ case 221 /* ConditionalExpression */:
+ case 224 /* SpreadElement */:
+ case 222 /* TemplateExpression */:
+ case 226 /* OmittedExpression */:
+ case 277 /* JsxElement */:
+ case 278 /* JsxSelfClosingElement */:
+ case 281 /* JsxFragment */:
+ case 223 /* YieldExpression */:
+ case 217 /* AwaitExpression */:
+ case 230 /* MetaProperty */:
+ return true;
+ case 160 /* QualifiedName */:
+ while (node.parent.kind === 160 /* QualifiedName */) {
+ node = node.parent;
+ }
+ return node.parent.kind === 180 /* TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node);
+ case 309 /* JSDocMemberName */:
+ while (ts.isJSDocMemberName(node.parent)) {
+ node = node.parent;
+ }
+ return node.parent.kind === 180 /* TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node);
+ case 80 /* PrivateIdentifier */:
+ return ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 101 /* InKeyword */;
+ case 79 /* Identifier */:
+ if (node.parent.kind === 180 /* TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node)) {
+ return true;
+ }
+ // falls through
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 108 /* ThisKeyword */:
+ return isInExpressionContext(node);
+ default:
+ return false;
+ }
+ }
+ ts.isExpressionNode = isExpressionNode;
+ function isInExpressionContext(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 253 /* VariableDeclaration */:
+ case 163 /* Parameter */:
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 297 /* EnumMember */:
+ case 294 /* PropertyAssignment */:
+ case 202 /* BindingElement */:
+ return parent.initializer === node;
+ case 237 /* ExpressionStatement */:
+ case 238 /* IfStatement */:
+ case 239 /* DoStatement */:
+ case 240 /* WhileStatement */:
+ case 246 /* ReturnStatement */:
+ case 247 /* WithStatement */:
+ case 248 /* SwitchStatement */:
+ case 288 /* CaseClause */:
+ case 250 /* ThrowStatement */:
+ return parent.expression === node;
+ case 241 /* ForStatement */:
+ var forStatement = parent;
+ return (forStatement.initializer === node && forStatement.initializer.kind !== 254 /* VariableDeclarationList */) ||
+ forStatement.condition === node ||
+ forStatement.incrementor === node;
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ var forInStatement = parent;
+ return (forInStatement.initializer === node && forInStatement.initializer.kind !== 254 /* VariableDeclarationList */) ||
+ forInStatement.expression === node;
+ case 210 /* TypeAssertionExpression */:
+ case 228 /* AsExpression */:
+ return node === parent.expression;
+ case 232 /* TemplateSpan */:
+ return node === parent.expression;
+ case 161 /* ComputedPropertyName */:
+ return node === parent.expression;
+ case 164 /* Decorator */:
+ case 287 /* JsxExpression */:
+ case 286 /* JsxSpreadAttribute */:
+ case 296 /* SpreadAssignment */:
+ return true;
+ case 227 /* ExpressionWithTypeArguments */:
+ return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
+ case 295 /* ShorthandPropertyAssignment */:
+ return parent.objectAssignmentInitializer === node;
+ default:
+ return isExpressionNode(parent);
+ }
+ }
+ ts.isInExpressionContext = isInExpressionContext;
+ function isPartOfTypeQuery(node) {
+ while (node.kind === 160 /* QualifiedName */ || node.kind === 79 /* Identifier */) {
+ node = node.parent;
+ }
+ return node.kind === 180 /* TypeQuery */;
+ }
+ ts.isPartOfTypeQuery = isPartOfTypeQuery;
+ function isNamespaceReexportDeclaration(node) {
+ return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier;
+ }
+ ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration;
+ function isExternalModuleImportEqualsDeclaration(node) {
+ return node.kind === 264 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 276 /* ExternalModuleReference */;
+ }
+ ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
+ function getExternalModuleImportEqualsDeclarationExpression(node) {
+ ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
+ return node.moduleReference.expression;
+ }
+ ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
+ function getExternalModuleRequireArgument(node) {
+ return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0];
+ }
+ ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument;
+ function isInternalModuleImportEqualsDeclaration(node) {
+ return node.kind === 264 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 276 /* ExternalModuleReference */;
+ }
+ ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
+ function isSourceFileJS(file) {
+ return isInJSFile(file);
+ }
+ ts.isSourceFileJS = isSourceFileJS;
+ function isSourceFileNotJS(file) {
+ return !isInJSFile(file);
+ }
+ ts.isSourceFileNotJS = isSourceFileNotJS;
+ function isInJSFile(node) {
+ return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
+ }
+ ts.isInJSFile = isInJSFile;
+ function isInJsonFile(node) {
+ return !!node && !!(node.flags & 33554432 /* JsonFile */);
+ }
+ ts.isInJsonFile = isInJsonFile;
+ function isSourceFileNotJson(file) {
+ return !isJsonSourceFile(file);
+ }
+ ts.isSourceFileNotJson = isSourceFileNotJson;
+ function isInJSDoc(node) {
+ return !!node && !!(node.flags & 4194304 /* JSDoc */);
+ }
+ ts.isInJSDoc = isInJSDoc;
+ function isJSDocIndexSignature(node) {
+ return ts.isTypeReferenceNode(node) &&
+ ts.isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "Object" &&
+ node.typeArguments && node.typeArguments.length === 2 &&
+ (node.typeArguments[0].kind === 149 /* StringKeyword */ || node.typeArguments[0].kind === 146 /* NumberKeyword */);
+ }
+ ts.isJSDocIndexSignature = isJSDocIndexSignature;
+ function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
+ if (callExpression.kind !== 207 /* CallExpression */) {
+ return false;
+ }
+ var _a = callExpression, expression = _a.expression, args = _a.arguments;
+ if (expression.kind !== 79 /* Identifier */ || expression.escapedText !== "require") {
+ return false;
+ }
+ if (args.length !== 1) {
+ return false;
+ }
+ var arg = args[0];
+ return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
+ }
+ ts.isRequireCall = isRequireCall;
+ /**
+ * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`).
+ * This function does not test if the node is in a JavaScript file or not.
+ */
+ function isRequireVariableDeclaration(node) {
+ if (node.kind === 202 /* BindingElement */) {
+ node = node.parent.parent;
+ }
+ return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true);
+ }
+ ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
+ function isRequireVariableStatement(node) {
+ return ts.isVariableStatement(node)
+ && node.declarationList.declarations.length > 0
+ && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); });
+ }
+ ts.isRequireVariableStatement = isRequireVariableStatement;
+ function isSingleOrDoubleQuote(charCode) {
+ return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
+ }
+ ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
+ function isStringDoubleQuoted(str, sourceFile) {
+ return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
+ }
+ ts.isStringDoubleQuoted = isStringDoubleQuoted;
+ function isAssignmentDeclaration(decl) {
+ return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
+ }
+ ts.isAssignmentDeclaration = isAssignmentDeclaration;
+ /** Get the initializer, taking into account defaulted Javascript initializers */
+ function getEffectiveInitializer(node) {
+ if (isInJSFile(node) && node.initializer &&
+ ts.isBinaryExpression(node.initializer) &&
+ (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
+ 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 getExpandoInitializer). */
+ function getDeclaredExpandoInitializer(node) {
+ var init = getEffectiveInitializer(node);
+ return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
+ }
+ ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
+ function hasExpandoValueProperty(node, isPrototypeAssignment) {
+ return ts.forEach(node.properties, function (p) {
+ return ts.isPropertyAssignment(p) &&
+ ts.isIdentifier(p.name) &&
+ p.name.escapedText === "value" &&
+ p.initializer &&
+ getExpandoInitializer(p.initializer, isPrototypeAssignment);
+ });
+ }
+ /**
+ * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
+ * We treat the right hand side of assignments with container-like initializers as declarations.
+ */
+ function getAssignedExpandoInitializer(node) {
+ if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 63 /* EqualsToken */) {
+ var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
+ return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
+ getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
+ }
+ if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
+ var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
+ if (result) {
+ return result;
+ }
+ }
+ }
+ ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
+ /**
+ * Recognized expando 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 getExpandoInitializer(initializer, isPrototypeAssignment) {
+ if (ts.isCallExpression(initializer)) {
+ var e = skipParentheses(initializer.expression);
+ return e.kind === 212 /* FunctionExpression */ || e.kind === 213 /* ArrowFunction */ ? initializer : undefined;
+ }
+ if (initializer.kind === 212 /* FunctionExpression */ ||
+ initializer.kind === 225 /* ClassExpression */ ||
+ initializer.kind === 213 /* ArrowFunction */) {
+ return initializer;
+ }
+ if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
+ return initializer;
+ }
+ }
+ ts.getExpandoInitializer = getExpandoInitializer;
+ /**
+ * A defaulted expando initializer matches the pattern
+ * `Lhs = Lhs || ExpandoInitializer`
+ * or `var Lhs = Lhs || ExpandoInitializer`
+ *
+ * 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 getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
+ var e = ts.isBinaryExpression(initializer)
+ && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
+ && getExpandoInitializer(initializer.right, isPrototypeAssignment);
+ if (e && isSameEntityName(name, initializer.left)) {
+ return e;
+ }
+ }
+ function isDefaultedExpandoInitializer(node) {
+ var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
+ ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 63 /* EqualsToken */ ? node.parent.left :
+ undefined;
+ return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
+ }
+ ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
+ /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
+ function getNameOfExpando(node) {
+ if (ts.isBinaryExpression(node.parent)) {
+ var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
+ if (parent.operatorToken.kind === 63 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
+ return parent.left;
+ }
+ }
+ else if (ts.isVariableDeclaration(node.parent)) {
+ return node.parent.name;
+ }
+ }
+ ts.getNameOfExpando = getNameOfExpando;
+ /**
+ * 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 (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
+ return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer);
+ }
+ if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
+ (initializer.expression.kind === 108 /* ThisKeyword */ ||
+ ts.isIdentifier(initializer.expression) &&
+ (initializer.expression.escapedText === "window" ||
+ initializer.expression.escapedText === "self" ||
+ initializer.expression.escapedText === "global"))) {
+ var nameOrArgument = getNameOrArgument(initializer);
+ if (ts.isPrivateIdentifier(nameOrArgument)) {
+ ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
+ }
+ return isSameEntityName(name, nameOrArgument);
+ }
+ if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
+ return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
+ && isSameEntityName(name.expression, initializer.expression);
+ }
+ return false;
+ }
+ ts.isSameEntityName = isSameEntityName;
+ function getRightMostAssignedExpression(node) {
+ while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
+ node = node.right;
+ }
+ return node;
+ }
+ ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
+ function isExportsIdentifier(node) {
+ return ts.isIdentifier(node) && node.escapedText === "exports";
+ }
+ ts.isExportsIdentifier = isExportsIdentifier;
+ function isModuleIdentifier(node) {
+ return ts.isIdentifier(node) && node.escapedText === "module";
+ }
+ ts.isModuleIdentifier = isModuleIdentifier;
+ function isModuleExportsAccessExpression(node) {
+ return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
+ && isModuleIdentifier(node.expression)
+ && getElementOrPropertyAccessName(node) === "exports";
+ }
+ ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
+ /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
+ /// assignments we treat as special in the binder
+ function getAssignmentDeclarationKind(expr) {
+ var special = getAssignmentDeclarationKindWorker(expr);
+ return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
+ }
+ ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
+ function isBindableObjectDefinePropertyCall(expr) {
+ return ts.length(expr.arguments) === 3 &&
+ ts.isPropertyAccessExpression(expr.expression) &&
+ ts.isIdentifier(expr.expression.expression) &&
+ ts.idText(expr.expression.expression) === "Object" &&
+ ts.idText(expr.expression.name) === "defineProperty" &&
+ isStringOrNumericLiteralLike(expr.arguments[1]) &&
+ isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
+ }
+ ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
+ /** x.y OR x[0] */
+ function isLiteralLikeAccess(node) {
+ return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
+ }
+ ts.isLiteralLikeAccess = isLiteralLikeAccess;
+ /** x[0] OR x['a'] OR x[Symbol.y] */
+ function isLiteralLikeElementAccess(node) {
+ return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression);
+ }
+ ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
+ /** Any series of property and element accesses. */
+ function isBindableStaticAccessExpression(node, excludeThisKeyword) {
+ return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 108 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
+ || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
+ }
+ ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
+ /** Any series of property and element accesses, ending in a literal element access */
+ function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
+ return isLiteralLikeElementAccess(node)
+ && ((!excludeThisKeyword && node.expression.kind === 108 /* ThisKeyword */) ||
+ isEntityNameExpression(node.expression) ||
+ isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
+ }
+ ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
+ function isBindableStaticNameExpression(node, excludeThisKeyword) {
+ return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
+ }
+ ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
+ function getNameOrArgument(expr) {
+ if (ts.isPropertyAccessExpression(expr)) {
+ return expr.name;
+ }
+ return expr.argumentExpression;
+ }
+ ts.getNameOrArgument = getNameOrArgument;
+ function getAssignmentDeclarationKindWorker(expr) {
+ if (ts.isCallExpression(expr)) {
+ if (!isBindableObjectDefinePropertyCall(expr)) {
+ return 0 /* None */;
+ }
+ var entityName = expr.arguments[0];
+ if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
+ return 8 /* ObjectDefinePropertyExports */;
+ }
+ if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
+ return 9 /* ObjectDefinePrototypeProperty */;
+ }
+ return 7 /* ObjectDefinePropertyValue */;
+ }
+ if (expr.operatorToken.kind !== 63 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) {
+ return 0 /* None */;
+ }
+ if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
+ // F.prototype = { ... }
+ return 6 /* Prototype */;
+ }
+ return getAssignmentDeclarationPropertyAccessKind(expr.left);
+ }
+ function isVoidZero(node) {
+ return ts.isVoidExpression(node) && ts.isNumericLiteral(node.expression) && node.expression.text === "0";
+ }
+ /**
+ * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
+ * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
+ */
+ /* @internal */
+ function getElementOrPropertyAccessArgumentExpressionOrName(node) {
+ if (ts.isPropertyAccessExpression(node)) {
+ return node.name;
+ }
+ var arg = skipParentheses(node.argumentExpression);
+ if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
+ return arg;
+ }
+ return node;
+ }
+ ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
+ function getElementOrPropertyAccessName(node) {
+ var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
+ if (name) {
+ if (ts.isIdentifier(name)) {
+ return name.escapedText;
+ }
+ if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
+ return ts.escapeLeadingUnderscores(name.text);
+ }
+ }
+ return undefined;
+ }
+ ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
+ function getAssignmentDeclarationPropertyAccessKind(lhs) {
+ if (lhs.expression.kind === 108 /* ThisKeyword */) {
+ return 4 /* ThisProperty */;
+ }
+ else if (isModuleExportsAccessExpression(lhs)) {
+ // module.exports = expr
+ return 2 /* ModuleExports */;
+ }
+ else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
+ if (isPrototypeAccess(lhs.expression)) {
+ // F.G....prototype.x = expr
+ return 3 /* PrototypeProperty */;
+ }
+ var nextToLast = lhs;
+ while (!ts.isIdentifier(nextToLast.expression)) {
+ nextToLast = nextToLast.expression;
+ }
+ var id = nextToLast.expression;
+ if ((id.escapedText === "exports" ||
+ id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
+ // ExportsProperty does not support binding with computed names
+ isBindableStaticAccessExpression(lhs)) {
+ // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
+ return 1 /* ExportsProperty */;
+ }
+ if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
+ // F.G...x = expr
+ return 5 /* Property */;
+ }
+ }
+ return 0 /* None */;
+ }
+ ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
+ function getInitializerOfBinaryExpression(expr) {
+ while (ts.isBinaryExpression(expr.right)) {
+ expr = expr.right;
+ }
+ return expr.right;
+ }
+ ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
+ function isPrototypePropertyAssignment(node) {
+ return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
+ }
+ ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
+ function isSpecialPropertyDeclaration(expr) {
+ return isInJSFile(expr) &&
+ expr.parent && expr.parent.kind === 237 /* ExpressionStatement */ &&
+ (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
+ !!ts.getJSDocTypeTag(expr.parent);
+ }
+ ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
+ function setValueDeclaration(symbol, node) {
+ var valueDeclaration = symbol.valueDeclaration;
+ if (!valueDeclaration ||
+ !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
+ (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
+ (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
+ // other kinds of value declarations take precedence over modules and assignment declarations
+ symbol.valueDeclaration = node;
+ }
+ }
+ ts.setValueDeclaration = setValueDeclaration;
+ function isFunctionSymbol(symbol) {
+ if (!symbol || !symbol.valueDeclaration) {
+ return false;
+ }
+ var decl = symbol.valueDeclaration;
+ return decl.kind === 255 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
+ }
+ ts.isFunctionSymbol = isFunctionSymbol;
+ function tryGetModuleSpecifierFromDeclaration(node) {
+ var _a, _b, _c;
+ switch (node.kind) {
+ case 253 /* VariableDeclaration */:
+ return node.initializer.arguments[0].text;
+ case 265 /* ImportDeclaration */:
+ return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text;
+ case 264 /* ImportEqualsDeclaration */:
+ return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text;
+ default:
+ ts.Debug.assertNever(node);
+ }
+ }
+ ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration;
+ function importFromModuleSpecifier(node) {
+ return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
+ }
+ ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ function tryGetImportFromModuleSpecifier(node) {
+ switch (node.parent.kind) {
+ case 265 /* ImportDeclaration */:
+ case 271 /* ExportDeclaration */:
+ return node.parent;
+ case 276 /* ExternalModuleReference */:
+ return node.parent.parent;
+ case 207 /* CallExpression */:
+ return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
+ case 195 /* LiteralType */:
+ ts.Debug.assert(ts.isStringLiteral(node));
+ return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
+ default:
+ return undefined;
+ }
+ }
+ ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
+ function getExternalModuleName(node) {
+ switch (node.kind) {
+ case 265 /* ImportDeclaration */:
+ case 271 /* ExportDeclaration */:
+ return node.moduleSpecifier;
+ case 264 /* ImportEqualsDeclaration */:
+ return node.moduleReference.kind === 276 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
+ case 199 /* ImportType */:
+ return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
+ case 207 /* CallExpression */:
+ return node.arguments[0];
+ case 260 /* ModuleDeclaration */:
+ return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined;
+ default:
+ return ts.Debug.assertNever(node);
+ }
+ }
+ ts.getExternalModuleName = getExternalModuleName;
+ function getNamespaceDeclarationNode(node) {
+ switch (node.kind) {
+ case 265 /* ImportDeclaration */:
+ return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
+ case 264 /* ImportEqualsDeclaration */:
+ return node;
+ case 271 /* ExportDeclaration */:
+ return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
+ default:
+ return ts.Debug.assertNever(node);
+ }
+ }
+ ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
+ function isDefaultImport(node) {
+ return node.kind === 265 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
+ }
+ ts.isDefaultImport = isDefaultImport;
+ function forEachImportClauseDeclaration(node, action) {
+ if (node.name) {
+ var result = action(node);
+ if (result)
+ return result;
+ }
+ if (node.namedBindings) {
+ var result = ts.isNamespaceImport(node.namedBindings)
+ ? action(node.namedBindings)
+ : ts.forEach(node.namedBindings.elements, action);
+ if (result)
+ return result;
+ }
+ }
+ ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
+ function hasQuestionToken(node) {
+ if (node) {
+ switch (node.kind) {
+ case 163 /* Parameter */:
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 295 /* ShorthandPropertyAssignment */:
+ case 294 /* PropertyAssignment */:
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ return node.questionToken !== undefined;
+ }
+ }
+ return false;
+ }
+ ts.hasQuestionToken = hasQuestionToken;
+ function isJSDocConstructSignature(node) {
+ var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
+ var name = ts.tryCast(param && param.name, ts.isIdentifier);
+ return !!name && name.escapedText === "new";
+ }
+ ts.isJSDocConstructSignature = isJSDocConstructSignature;
+ function isJSDocTypeAlias(node) {
+ return node.kind === 343 /* JSDocTypedefTag */ || node.kind === 336 /* JSDocCallbackTag */ || node.kind === 337 /* JSDocEnumTag */;
+ }
+ ts.isJSDocTypeAlias = isJSDocTypeAlias;
+ function isTypeAlias(node) {
+ return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
+ }
+ ts.isTypeAlias = isTypeAlias;
+ function getSourceOfAssignment(node) {
+ return ts.isExpressionStatement(node) &&
+ ts.isBinaryExpression(node.expression) &&
+ node.expression.operatorToken.kind === 63 /* EqualsToken */
+ ? getRightMostAssignedExpression(node.expression)
+ : undefined;
+ }
+ function getSourceOfDefaultedAssignment(node) {
+ return ts.isExpressionStatement(node) &&
+ ts.isBinaryExpression(node.expression) &&
+ getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
+ ts.isBinaryExpression(node.expression.right) &&
+ (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
+ ? node.expression.right.right
+ : undefined;
+ }
+ function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
+ switch (node.kind) {
+ case 236 /* VariableStatement */:
+ var v = getSingleVariableOfVariableStatement(node);
+ return v && v.initializer;
+ case 166 /* PropertyDeclaration */:
+ return node.initializer;
+ case 294 /* PropertyAssignment */:
+ return node.initializer;
+ }
+ }
+ ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
+ function getSingleVariableOfVariableStatement(node) {
+ return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
+ }
+ ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement;
+ function getNestedModuleDeclaration(node) {
+ return ts.isModuleDeclaration(node) &&
+ node.body &&
+ node.body.kind === 260 /* ModuleDeclaration */
+ ? node.body
+ : undefined;
+ }
+ function getJSDocCommentsAndTags(hostNode, noCache) {
+ var result;
+ // Pull parameter comments from declaring function as well
+ if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
+ result = ts.addRange(result, filterOwnedJSDocTags(hostNode, ts.last(hostNode.initializer.jsDoc)));
+ }
+ var node = hostNode;
+ while (node && node.parent) {
+ if (ts.hasJSDocNodes(node)) {
+ result = ts.addRange(result, filterOwnedJSDocTags(hostNode, ts.last(node.jsDoc)));
+ }
+ if (node.kind === 163 /* Parameter */) {
+ result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node));
+ break;
+ }
+ if (node.kind === 162 /* TypeParameter */) {
+ result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node));
+ break;
+ }
+ node = getNextJSDocCommentLocation(node);
+ }
+ return result || ts.emptyArray;
+ }
+ ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
+ function filterOwnedJSDocTags(hostNode, jsDoc) {
+ if (ts.isJSDoc(jsDoc)) {
+ var ownedTags = ts.filter(jsDoc.tags, function (tag) { return ownsJSDocTag(hostNode, tag); });
+ return jsDoc.tags === ownedTags ? [jsDoc] : ownedTags;
+ }
+ return ownsJSDocTag(hostNode, jsDoc) ? [jsDoc] : undefined;
+ }
+ /**
+ * Determines whether a host node owns a jsDoc tag. A `@type` tag attached to a
+ * a ParenthesizedExpression belongs only to the ParenthesizedExpression.
+ */
+ function ownsJSDocTag(hostNode, tag) {
+ return !ts.isJSDocTypeTag(tag)
+ || !tag.parent
+ || !ts.isJSDoc(tag.parent)
+ || !ts.isParenthesizedExpression(tag.parent.parent)
+ || tag.parent.parent === hostNode;
+ }
+ function getNextJSDocCommentLocation(node) {
+ var parent = node.parent;
+ if (parent.kind === 294 /* PropertyAssignment */ ||
+ parent.kind === 270 /* ExportAssignment */ ||
+ parent.kind === 166 /* PropertyDeclaration */ ||
+ parent.kind === 237 /* ExpressionStatement */ && node.kind === 205 /* PropertyAccessExpression */ ||
+ parent.kind === 246 /* ReturnStatement */ ||
+ getNestedModuleDeclaration(parent) ||
+ ts.isBinaryExpression(node) && node.operatorToken.kind === 63 /* EqualsToken */) {
+ return 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; }
+ else if (parent.parent &&
+ (getSingleVariableOfVariableStatement(parent.parent) === node ||
+ ts.isBinaryExpression(parent) && parent.operatorToken.kind === 63 /* EqualsToken */)) {
+ return parent.parent;
+ }
+ else if (parent.parent && parent.parent.parent &&
+ (getSingleVariableOfVariableStatement(parent.parent.parent) ||
+ getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
+ getSourceOfDefaultedAssignment(parent.parent.parent))) {
+ return parent.parent.parent;
+ }
+ }
+ ts.getNextJSDocCommentLocation = getNextJSDocCommentLocation;
+ /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
+ function getParameterSymbolFromJSDoc(node) {
+ if (node.symbol) {
+ return node.symbol;
+ }
+ if (!ts.isIdentifier(node.name)) {
+ return undefined;
+ }
+ var name = node.name.escapedText;
+ var decl = getHostSignatureFromJSDoc(node);
+ if (!decl) {
+ return undefined;
+ }
+ var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 79 /* Identifier */ && p.name.escapedText === name; });
+ return parameter && parameter.symbol;
+ }
+ ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
+ function getEffectiveContainerForJSDocTemplateTag(node) {
+ if (ts.isJSDoc(node.parent) && node.parent.tags) {
+ // A @template tag belongs to any @typedef, @callback, or @enum tags in the same comment block, if they exist.
+ var typeAlias = ts.find(node.parent.tags, isJSDocTypeAlias);
+ if (typeAlias) {
+ return typeAlias;
+ }
+ }
+ // otherwise it belongs to the host it annotates
+ return getHostSignatureFromJSDoc(node);
+ }
+ ts.getEffectiveContainerForJSDocTemplateTag = getEffectiveContainerForJSDocTemplateTag;
+ function getHostSignatureFromJSDoc(node) {
+ var host = getEffectiveJSDocHost(node);
+ return host && ts.isFunctionLike(host) ? host : undefined;
+ }
+ ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ function getEffectiveJSDocHost(node) {
+ var host = getJSDocHost(node);
+ if (host) {
+ return getSourceOfDefaultedAssignment(host)
+ || getSourceOfAssignment(host)
+ || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host)
+ || getSingleVariableOfVariableStatement(host)
+ || getNestedModuleDeclaration(host)
+ || host;
+ }
+ }
+ ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
+ /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
+ function getJSDocHost(node) {
+ var jsDoc = getJSDocRoot(node);
+ if (!jsDoc) {
+ return undefined;
+ }
+ var host = jsDoc.parent;
+ if (host && host.jsDoc && jsDoc === ts.lastOrUndefined(host.jsDoc)) {
+ return host;
+ }
+ }
+ ts.getJSDocHost = getJSDocHost;
+ function getJSDocRoot(node) {
+ return ts.findAncestor(node.parent, ts.isJSDoc);
+ }
+ ts.getJSDocRoot = getJSDocRoot;
+ function getTypeParameterFromJsDoc(node) {
+ var name = node.name.escapedText;
+ var typeParameters = node.parent.parent.parent.typeParameters;
+ return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
+ }
+ ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
+ function hasRestParameter(s) {
+ var last = ts.lastOrUndefined(s.parameters);
+ return !!last && isRestParameter(last);
+ }
+ 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 === 316 /* JSDocVariadicType */;
+ }
+ ts.isRestParameter = isRestParameter;
+ function hasTypeArguments(node) {
+ return !!node.typeArguments;
+ }
+ ts.hasTypeArguments = hasTypeArguments;
+ var AssignmentKind;
+ (function (AssignmentKind) {
+ AssignmentKind[AssignmentKind["None"] = 0] = "None";
+ AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
+ AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
+ })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
+ function getAssignmentTargetKind(node) {
+ var parent = node.parent;
+ while (true) {
+ switch (parent.kind) {
+ case 220 /* BinaryExpression */:
+ var binaryOperator = parent.operatorToken.kind;
+ return isAssignmentOperator(binaryOperator) && parent.left === node ?
+ binaryOperator === 63 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ :
+ 0 /* None */;
+ case 218 /* PrefixUnaryExpression */:
+ case 219 /* PostfixUnaryExpression */:
+ var unaryOperator = parent.operator;
+ return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
+ case 211 /* ParenthesizedExpression */:
+ case 203 /* ArrayLiteralExpression */:
+ case 224 /* SpreadElement */:
+ case 229 /* NonNullExpression */:
+ node = parent;
+ break;
+ case 296 /* SpreadAssignment */:
+ node = parent.parent;
+ break;
+ case 295 /* ShorthandPropertyAssignment */:
+ if (parent.name !== node) {
+ return 0 /* None */;
+ }
+ node = parent.parent;
+ break;
+ case 294 /* PropertyAssignment */:
+ if (parent.name === node) {
+ return 0 /* None */;
+ }
+ node = parent.parent;
+ break;
+ default:
+ 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 /* 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 234 /* Block */:
+ case 236 /* VariableStatement */:
+ case 247 /* WithStatement */:
+ case 238 /* IfStatement */:
+ case 248 /* SwitchStatement */:
+ case 262 /* CaseBlock */:
+ case 288 /* CaseClause */:
+ case 289 /* DefaultClause */:
+ case 249 /* LabeledStatement */:
+ case 241 /* ForStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ case 239 /* DoStatement */:
+ case 240 /* WhileStatement */:
+ case 251 /* TryStatement */:
+ case 291 /* CatchClause */:
+ return true;
+ }
+ return false;
+ }
+ ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
+ function isValueSignatureDeclaration(node) {
+ return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
+ }
+ ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
+ function walkUp(node, kind) {
+ while (node && node.kind === kind) {
+ node = node.parent;
+ }
+ return node;
+ }
+ function walkUpParenthesizedTypes(node) {
+ return walkUp(node, 190 /* ParenthesizedType */);
+ }
+ ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
+ function walkUpParenthesizedExpressions(node) {
+ return walkUp(node, 211 /* ParenthesizedExpression */);
+ }
+ ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
+ /**
+ * Walks up parenthesized types.
+ * It returns both the outermost parenthesized type and its parent.
+ * If given node is not a parenthesiezd type, undefined is return as the former.
+ */
+ function walkUpParenthesizedTypesAndGetParentAndChild(node) {
+ var child;
+ while (node && node.kind === 190 /* ParenthesizedType */) {
+ child = node;
+ node = node.parent;
+ }
+ return [child, node];
+ }
+ ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild;
+ function skipParentheses(node, excludeJSDocTypeAssertions) {
+ var flags = excludeJSDocTypeAssertions ?
+ 1 /* Parentheses */ | 16 /* ExcludeJSDocTypeAssertion */ :
+ 1 /* Parentheses */;
+ return ts.skipOuterExpressions(node, flags);
+ }
+ ts.skipParentheses = skipParentheses;
+ // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
+ function isDeleteTarget(node) {
+ if (node.kind !== 205 /* PropertyAccessExpression */ && node.kind !== 206 /* ElementAccessExpression */) {
+ return false;
+ }
+ node = walkUpParenthesizedExpressions(node.parent);
+ return node && node.kind === 214 /* DeleteExpression */;
+ }
+ ts.isDeleteTarget = isDeleteTarget;
+ function isNodeDescendantOf(node, ancestor) {
+ while (node) {
+ if (node === ancestor)
+ return true;
+ node = node.parent;
+ }
+ 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 getDeclarationFromName(name) {
+ var parent = name.parent;
+ switch (name.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ if (ts.isComputedPropertyName(parent))
+ return parent.parent;
+ // falls through
+ case 79 /* Identifier */:
+ if (ts.isDeclaration(parent)) {
+ return parent.name === name ? parent : undefined;
+ }
+ else if (ts.isQualifiedName(parent)) {
+ var tag = parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
+ }
+ else {
+ var binExp = parent.parent;
+ return ts.isBinaryExpression(binExp) &&
+ getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
+ (binExp.left.symbol || binExp.symbol) &&
+ ts.getNameOfDeclaration(binExp) === name
+ ? binExp
+ : undefined;
+ }
+ case 80 /* PrivateIdentifier */:
+ return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
+ default:
+ return undefined;
+ }
+ }
+ ts.getDeclarationFromName = getDeclarationFromName;
+ function isLiteralComputedPropertyDeclarationName(node) {
+ return isStringOrNumericLiteralLike(node) &&
+ node.parent.kind === 161 /* 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 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 297 /* EnumMember */:
+ case 294 /* PropertyAssignment */:
+ case 205 /* PropertyAccessExpression */:
+ // Name in member declaration or property name in property access
+ return parent.name === node;
+ case 160 /* QualifiedName */:
+ // Name on right hand side of dot in a type query or type reference
+ return parent.right === node;
+ case 202 /* BindingElement */:
+ case 269 /* ImportSpecifier */:
+ // Property name in binding element or import specifier
+ return parent.propertyName === node;
+ case 274 /* ExportSpecifier */:
+ case 284 /* 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 * as ns from ...
+ // export =
+ // export default
+ // module.exports =
+ // {}
+ // {name: }
+ function isAliasSymbolDeclaration(node) {
+ return node.kind === 264 /* ImportEqualsDeclaration */ ||
+ node.kind === 263 /* NamespaceExportDeclaration */ ||
+ node.kind === 266 /* ImportClause */ && !!node.name ||
+ node.kind === 267 /* NamespaceImport */ ||
+ node.kind === 273 /* NamespaceExport */ ||
+ node.kind === 269 /* ImportSpecifier */ ||
+ node.kind === 274 /* ExportSpecifier */ ||
+ node.kind === 270 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
+ ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
+ ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
+ node.kind === 295 /* ShorthandPropertyAssignment */ ||
+ node.kind === 294 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
+ }
+ ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
+ function getAliasDeclarationFromName(node) {
+ switch (node.parent.kind) {
+ case 266 /* ImportClause */:
+ case 269 /* ImportSpecifier */:
+ case 267 /* NamespaceImport */:
+ case 274 /* ExportSpecifier */:
+ case 270 /* ExportAssignment */:
+ case 264 /* ImportEqualsDeclaration */:
+ return node.parent;
+ case 160 /* QualifiedName */:
+ do {
+ node = node.parent;
+ } while (node.parent.kind === 160 /* QualifiedName */);
+ return getAliasDeclarationFromName(node);
+ }
+ }
+ ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
+ function isAliasableExpression(e) {
+ return isEntityNameExpression(e) || ts.isClassExpression(e);
+ }
+ ts.isAliasableExpression = isAliasableExpression;
+ function exportAssignmentIsAlias(node) {
+ var e = getExportAssignmentExpression(node);
+ return isAliasableExpression(e);
+ }
+ ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
+ function getExportAssignmentExpression(node) {
+ return ts.isExportAssignment(node) ? node.expression : node.right;
+ }
+ ts.getExportAssignmentExpression = getExportAssignmentExpression;
+ function getPropertyAssignmentAliasLikeExpression(node) {
+ return node.kind === 295 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 294 /* PropertyAssignment */ ? node.initializer :
+ node.parent.right;
+ }
+ ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
+ function getEffectiveBaseTypeNode(node) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
+ // Prefer an @augments tag because it may have type parameters.
+ var tag = ts.getJSDocAugmentsTag(node);
+ if (tag) {
+ return tag.class;
+ }
+ }
+ return baseType;
+ }
+ ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
+ function getClassExtendsHeritageElement(node) {
+ var heritageClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */);
+ return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
+ }
+ ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
+ function getEffectiveImplementsTypeNodes(node) {
+ if (isInJSFile(node)) {
+ return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
+ }
+ else {
+ var heritageClause = getHeritageClause(node.heritageClauses, 117 /* ImplementsKeyword */);
+ return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
+ }
+ }
+ ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
+ /** 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(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
+ ts.emptyArray;
+ }
+ ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
+ function getInterfaceBaseTypeNodes(node) {
+ var heritageClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */);
+ return heritageClause ? heritageClause.types : undefined;
+ }
+ ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
+ function getHeritageClause(clauses, kind) {
+ if (clauses) {
+ for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
+ var clause = clauses_1[_i];
+ if (clause.token === kind) {
+ return clause;
+ }
+ }
+ }
+ return undefined;
+ }
+ ts.getHeritageClause = getHeritageClause;
+ function getAncestor(node, kind) {
+ while (node) {
+ if (node.kind === kind) {
+ return node;
+ }
+ node = node.parent;
+ }
+ return undefined;
+ }
+ ts.getAncestor = getAncestor;
+ function isKeyword(token) {
+ return 81 /* FirstKeyword */ <= token && token <= 159 /* LastKeyword */;
+ }
+ ts.isKeyword = isKeyword;
+ function isContextualKeyword(token) {
+ return 126 /* FirstContextualKeyword */ <= token && token <= 159 /* LastContextualKeyword */;
+ }
+ ts.isContextualKeyword = isContextualKeyword;
+ function isNonContextualKeyword(token) {
+ return isKeyword(token) && !isContextualKeyword(token);
+ }
+ ts.isNonContextualKeyword = isNonContextualKeyword;
+ function isFutureReservedKeyword(token) {
+ return 117 /* FirstFutureReservedWord */ <= token && token <= 125 /* LastFutureReservedWord */;
+ }
+ ts.isFutureReservedKeyword = isFutureReservedKeyword;
+ function isStringANonContextualKeyword(name) {
+ var token = ts.stringToToken(name);
+ return token !== undefined && isNonContextualKeyword(token);
+ }
+ ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
+ function isStringAKeyword(name) {
+ var token = ts.stringToToken(name);
+ return token !== undefined && isKeyword(token);
+ }
+ ts.isStringAKeyword = isStringAKeyword;
+ function isIdentifierANonContextualKeyword(_a) {
+ var originalKeywordKind = _a.originalKeywordKind;
+ return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
+ }
+ ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
+ function isTrivia(token) {
+ return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
+ }
+ ts.isTrivia = isTrivia;
+ var FunctionFlags;
+ (function (FunctionFlags) {
+ FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
+ FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
+ FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
+ FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
+ FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
+ })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
+ function getFunctionFlags(node) {
+ if (!node) {
+ return 4 /* Invalid */;
+ }
+ var flags = 0 /* Normal */;
+ switch (node.kind) {
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 168 /* MethodDeclaration */:
+ if (node.asteriskToken) {
+ flags |= 1 /* Generator */;
+ }
+ // falls through
+ case 213 /* ArrowFunction */:
+ if (hasSyntacticModifier(node, 256 /* Async */)) {
+ flags |= 2 /* Async */;
+ }
+ break;
+ }
+ if (!node.body) {
+ flags |= 4 /* Invalid */;
+ }
+ return flags;
+ }
+ ts.getFunctionFlags = getFunctionFlags;
+ function isAsyncFunction(node) {
+ switch (node.kind) {
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ case 168 /* MethodDeclaration */:
+ return node.body !== undefined
+ && node.asteriskToken === undefined
+ && hasSyntacticModifier(node, 256 /* Async */);
+ }
+ return false;
+ }
+ ts.isAsyncFunction = isAsyncFunction;
+ function isStringOrNumericLiteralLike(node) {
+ return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
+ }
+ ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
+ function isSignedNumericLiteral(node) {
+ return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
+ }
+ ts.isSignedNumericLiteral = isSignedNumericLiteral;
+ /**
+ * A declaration has a dynamic name if all of the following are true:
+ * 1. The declaration has a computed property name.
+ * 2. The computed name is *not* expressed as a StringLiteral.
+ * 3. The computed name is *not* expressed as a NumericLiteral.
+ * 4. The computed name is *not* expressed as a PlusToken or MinusToken
+ * immediately followed by a NumericLiteral.
+ */
+ function hasDynamicName(declaration) {
+ var name = ts.getNameOfDeclaration(declaration);
+ return !!name && isDynamicName(name);
+ }
+ ts.hasDynamicName = hasDynamicName;
+ function isDynamicName(name) {
+ if (!(name.kind === 161 /* ComputedPropertyName */ || name.kind === 206 /* ElementAccessExpression */)) {
+ return false;
+ }
+ var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
+ return !isStringOrNumericLiteralLike(expr) &&
+ !isSignedNumericLiteral(expr);
+ }
+ ts.isDynamicName = isDynamicName;
+ function getPropertyNameForPropertyNameNode(name) {
+ switch (name.kind) {
+ case 79 /* Identifier */:
+ case 80 /* PrivateIdentifier */:
+ return name.escapedText;
+ case 10 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ return ts.escapeLeadingUnderscores(name.text);
+ case 161 /* ComputedPropertyName */:
+ var nameExpression = name.expression;
+ if (isStringOrNumericLiteralLike(nameExpression)) {
+ return ts.escapeLeadingUnderscores(nameExpression.text);
+ }
+ else if (isSignedNumericLiteral(nameExpression)) {
+ if (nameExpression.operator === 40 /* MinusToken */) {
+ return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
+ }
+ return nameExpression.operand.text;
+ }
+ return undefined;
+ default:
+ return ts.Debug.assertNever(name);
+ }
+ }
+ ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
+ function isPropertyNameLiteral(node) {
+ switch (node.kind) {
+ case 79 /* Identifier */:
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isPropertyNameLiteral = isPropertyNameLiteral;
+ function getTextOfIdentifierOrLiteral(node) {
+ return ts.isMemberName(node) ? ts.idText(node) : node.text;
+ }
+ ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
+ function getEscapedTextOfIdentifierOrLiteral(node) {
+ return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
+ }
+ ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
+ function getPropertyNameForUniqueESSymbol(symbol) {
+ return "__@".concat(ts.getSymbolId(symbol), "@").concat(symbol.escapedName);
+ }
+ ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
+ function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
+ return "__#".concat(ts.getSymbolId(containingClassSymbol), "@").concat(description);
+ }
+ ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
+ function isKnownSymbol(symbol) {
+ return ts.startsWith(symbol.escapedName, "__@");
+ }
+ ts.isKnownSymbol = isKnownSymbol;
+ function isPrivateIdentifierSymbol(symbol) {
+ return ts.startsWith(symbol.escapedName, "__#");
+ }
+ ts.isPrivateIdentifierSymbol = isPrivateIdentifierSymbol;
+ /**
+ * Includes the word "Symbol" with unicode escapes
+ */
+ function isESSymbolIdentifier(node) {
+ return node.kind === 79 /* Identifier */ && node.escapedText === "Symbol";
+ }
+ ts.isESSymbolIdentifier = isESSymbolIdentifier;
+ function isPushOrUnshiftIdentifier(node) {
+ return node.escapedText === "push" || node.escapedText === "unshift";
+ }
+ ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
+ function isParameterDeclaration(node) {
+ var root = getRootDeclaration(node);
+ return root.kind === 163 /* Parameter */;
+ }
+ ts.isParameterDeclaration = isParameterDeclaration;
+ function getRootDeclaration(node) {
+ while (node.kind === 202 /* BindingElement */) {
+ node = node.parent.parent;
+ }
+ return node;
+ }
+ ts.getRootDeclaration = getRootDeclaration;
+ function nodeStartsNewLexicalEnvironment(node) {
+ var kind = node.kind;
+ return kind === 170 /* Constructor */
+ || kind === 212 /* FunctionExpression */
+ || kind === 255 /* FunctionDeclaration */
+ || kind === 213 /* ArrowFunction */
+ || kind === 168 /* MethodDeclaration */
+ || kind === 171 /* GetAccessor */
+ || kind === 172 /* SetAccessor */
+ || kind === 260 /* ModuleDeclaration */
+ || kind === 303 /* SourceFile */;
+ }
+ ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
+ function nodeIsSynthesized(range) {
+ return positionIsSynthesized(range.pos)
+ || positionIsSynthesized(range.end);
+ }
+ ts.nodeIsSynthesized = nodeIsSynthesized;
+ function getOriginalSourceFile(sourceFile) {
+ return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
+ }
+ ts.getOriginalSourceFile = getOriginalSourceFile;
+ var Associativity;
+ (function (Associativity) {
+ Associativity[Associativity["Left"] = 0] = "Left";
+ Associativity[Associativity["Right"] = 1] = "Right";
+ })(Associativity = ts.Associativity || (ts.Associativity = {}));
+ function getExpressionAssociativity(expression) {
+ var operator = getOperator(expression);
+ var hasArguments = expression.kind === 208 /* NewExpression */ && expression.arguments !== undefined;
+ return getOperatorAssociativity(expression.kind, operator, hasArguments);
+ }
+ ts.getExpressionAssociativity = getExpressionAssociativity;
+ function getOperatorAssociativity(kind, operator, hasArguments) {
+ switch (kind) {
+ case 208 /* NewExpression */:
+ return hasArguments ? 0 /* Left */ : 1 /* Right */;
+ case 218 /* PrefixUnaryExpression */:
+ case 215 /* TypeOfExpression */:
+ case 216 /* VoidExpression */:
+ case 214 /* DeleteExpression */:
+ case 217 /* AwaitExpression */:
+ case 221 /* ConditionalExpression */:
+ case 223 /* YieldExpression */:
+ return 1 /* Right */;
+ case 220 /* BinaryExpression */:
+ switch (operator) {
+ case 42 /* AsteriskAsteriskToken */:
+ case 63 /* EqualsToken */:
+ case 64 /* PlusEqualsToken */:
+ case 65 /* MinusEqualsToken */:
+ case 67 /* AsteriskAsteriskEqualsToken */:
+ case 66 /* AsteriskEqualsToken */:
+ case 68 /* SlashEqualsToken */:
+ case 69 /* PercentEqualsToken */:
+ case 70 /* LessThanLessThanEqualsToken */:
+ case 71 /* GreaterThanGreaterThanEqualsToken */:
+ case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
+ case 73 /* AmpersandEqualsToken */:
+ case 78 /* CaretEqualsToken */:
+ case 74 /* BarEqualsToken */:
+ case 75 /* BarBarEqualsToken */:
+ case 76 /* AmpersandAmpersandEqualsToken */:
+ case 77 /* QuestionQuestionEqualsToken */:
+ return 1 /* Right */;
+ }
+ }
+ return 0 /* Left */;
+ }
+ ts.getOperatorAssociativity = getOperatorAssociativity;
+ function getExpressionPrecedence(expression) {
+ var operator = getOperator(expression);
+ var hasArguments = expression.kind === 208 /* NewExpression */ && expression.arguments !== undefined;
+ return getOperatorPrecedence(expression.kind, operator, hasArguments);
+ }
+ ts.getExpressionPrecedence = getExpressionPrecedence;
+ function getOperator(expression) {
+ if (expression.kind === 220 /* BinaryExpression */) {
+ return expression.operatorToken.kind;
+ }
+ else if (expression.kind === 218 /* PrefixUnaryExpression */ || expression.kind === 219 /* PostfixUnaryExpression */) {
+ return expression.operator;
+ }
+ else {
+ return expression.kind;
+ }
+ }
+ ts.getOperator = getOperator;
+ var OperatorPrecedence;
+ (function (OperatorPrecedence) {
+ // Expression:
+ // AssignmentExpression
+ // Expression `,` AssignmentExpression
+ OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
+ // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
+ // SpreadElement:
+ // `...` AssignmentExpression
+ OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
+ // AssignmentExpression:
+ // ConditionalExpression
+ // YieldExpression
+ // ArrowFunction
+ // AsyncArrowFunction
+ // LeftHandSideExpression `=` AssignmentExpression
+ // LeftHandSideExpression AssignmentOperator AssignmentExpression
+ //
+ // NOTE: AssignmentExpression is broken down into several precedences due to the requirements
+ // of the parenthesizer rules.
+ // AssignmentExpression: YieldExpression
+ // YieldExpression:
+ // `yield`
+ // `yield` AssignmentExpression
+ // `yield` `*` AssignmentExpression
+ OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
+ // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
+ // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
+ // AssignmentOperator: one of
+ // `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
+ OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
+ // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
+ // the same precedence.
+ // AssignmentExpression: ConditionalExpression
+ // ConditionalExpression:
+ // ShortCircuitExpression
+ // ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
+ // ShortCircuitExpression:
+ // LogicalORExpression
+ // CoalesceExpression
+ OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
+ // CoalesceExpression:
+ // CoalesceExpressionHead `??` BitwiseORExpression
+ // CoalesceExpressionHead:
+ // CoalesceExpression
+ // BitwiseORExpression
+ OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
+ // LogicalORExpression:
+ // LogicalANDExpression
+ // LogicalORExpression `||` LogicalANDExpression
+ OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
+ // LogicalANDExpression:
+ // BitwiseORExpression
+ // LogicalANDExprerssion `&&` BitwiseORExpression
+ OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
+ // BitwiseORExpression:
+ // BitwiseXORExpression
+ // BitwiseORExpression `^` BitwiseXORExpression
+ OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
+ // BitwiseXORExpression:
+ // BitwiseANDExpression
+ // BitwiseXORExpression `^` BitwiseANDExpression
+ OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
+ // BitwiseANDExpression:
+ // EqualityExpression
+ // BitwiseANDExpression `^` EqualityExpression
+ OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
+ // EqualityExpression:
+ // RelationalExpression
+ // EqualityExpression `==` RelationalExpression
+ // EqualityExpression `!=` RelationalExpression
+ // EqualityExpression `===` RelationalExpression
+ // EqualityExpression `!==` RelationalExpression
+ OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
+ // RelationalExpression:
+ // ShiftExpression
+ // RelationalExpression `<` ShiftExpression
+ // RelationalExpression `>` ShiftExpression
+ // RelationalExpression `<=` ShiftExpression
+ // RelationalExpression `>=` ShiftExpression
+ // RelationalExpression `instanceof` ShiftExpression
+ // RelationalExpression `in` ShiftExpression
+ // [+TypeScript] RelationalExpression `as` Type
+ OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
+ // ShiftExpression:
+ // AdditiveExpression
+ // ShiftExpression `<<` AdditiveExpression
+ // ShiftExpression `>>` AdditiveExpression
+ // ShiftExpression `>>>` AdditiveExpression
+ OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
+ // AdditiveExpression:
+ // MultiplicativeExpression
+ // AdditiveExpression `+` MultiplicativeExpression
+ // AdditiveExpression `-` MultiplicativeExpression
+ OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
+ // MultiplicativeExpression:
+ // ExponentiationExpression
+ // MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
+ // MultiplicativeOperator: one of `*`, `/`, `%`
+ OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
+ // ExponentiationExpression:
+ // UnaryExpression
+ // UpdateExpression `**` ExponentiationExpression
+ OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
+ // UnaryExpression:
+ // UpdateExpression
+ // `delete` UnaryExpression
+ // `void` UnaryExpression
+ // `typeof` UnaryExpression
+ // `+` UnaryExpression
+ // `-` UnaryExpression
+ // `~` UnaryExpression
+ // `!` UnaryExpression
+ // AwaitExpression
+ // UpdateExpression: // TODO: Do we need to investigate the precedence here?
+ // `++` UnaryExpression
+ // `--` UnaryExpression
+ OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
+ // UpdateExpression:
+ // LeftHandSideExpression
+ // LeftHandSideExpression `++`
+ // LeftHandSideExpression `--`
+ OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
+ // LeftHandSideExpression:
+ // NewExpression
+ // CallExpression
+ // NewExpression:
+ // MemberExpression
+ // `new` NewExpression
+ OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
+ // CallExpression:
+ // CoverCallExpressionAndAsyncArrowHead
+ // SuperCall
+ // ImportCall
+ // CallExpression Arguments
+ // CallExpression `[` Expression `]`
+ // CallExpression `.` IdentifierName
+ // CallExpression TemplateLiteral
+ // MemberExpression:
+ // PrimaryExpression
+ // MemberExpression `[` Expression `]`
+ // MemberExpression `.` IdentifierName
+ // MemberExpression TemplateLiteral
+ // SuperProperty
+ // MetaProperty
+ // `new` MemberExpression Arguments
+ OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
+ // TODO: JSXElement?
+ // PrimaryExpression:
+ // `this`
+ // IdentifierReference
+ // Literal
+ // ArrayLiteral
+ // ObjectLiteral
+ // FunctionExpression
+ // ClassExpression
+ // GeneratorExpression
+ // AsyncFunctionExpression
+ // AsyncGeneratorExpression
+ // RegularExpressionLiteral
+ // TemplateLiteral
+ // CoverParenthesizedExpressionAndArrowParameterList
+ OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
+ OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
+ OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
+ // -1 is lower than all other precedences. Returning it will cause binary expression
+ // parsing to stop.
+ OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
+ })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {}));
+ function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
+ switch (nodeKind) {
+ case 349 /* CommaListExpression */:
+ return 0 /* Comma */;
+ case 224 /* SpreadElement */:
+ return 1 /* Spread */;
+ case 223 /* YieldExpression */:
+ return 2 /* Yield */;
+ case 221 /* ConditionalExpression */:
+ return 4 /* Conditional */;
+ case 220 /* BinaryExpression */:
+ switch (operatorKind) {
+ case 27 /* CommaToken */:
+ return 0 /* Comma */;
+ case 63 /* EqualsToken */:
+ case 64 /* PlusEqualsToken */:
+ case 65 /* MinusEqualsToken */:
+ case 67 /* AsteriskAsteriskEqualsToken */:
+ case 66 /* AsteriskEqualsToken */:
+ case 68 /* SlashEqualsToken */:
+ case 69 /* PercentEqualsToken */:
+ case 70 /* LessThanLessThanEqualsToken */:
+ case 71 /* GreaterThanGreaterThanEqualsToken */:
+ case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
+ case 73 /* AmpersandEqualsToken */:
+ case 78 /* CaretEqualsToken */:
+ case 74 /* BarEqualsToken */:
+ case 75 /* BarBarEqualsToken */:
+ case 76 /* AmpersandAmpersandEqualsToken */:
+ case 77 /* QuestionQuestionEqualsToken */:
+ return 3 /* Assignment */;
+ default:
+ return getBinaryOperatorPrecedence(operatorKind);
+ }
+ // TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
+ case 210 /* TypeAssertionExpression */:
+ case 229 /* NonNullExpression */:
+ case 218 /* PrefixUnaryExpression */:
+ case 215 /* TypeOfExpression */:
+ case 216 /* VoidExpression */:
+ case 214 /* DeleteExpression */:
+ case 217 /* AwaitExpression */:
+ return 16 /* Unary */;
+ case 219 /* PostfixUnaryExpression */:
+ return 17 /* Update */;
+ case 207 /* CallExpression */:
+ return 18 /* LeftHandSide */;
+ case 208 /* NewExpression */:
+ return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */;
+ case 209 /* TaggedTemplateExpression */:
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ case 230 /* MetaProperty */:
+ return 19 /* Member */;
+ case 228 /* AsExpression */:
+ return 11 /* Relational */;
+ case 108 /* ThisKeyword */:
+ case 106 /* SuperKeyword */:
+ case 79 /* Identifier */:
+ case 80 /* PrivateIdentifier */:
+ case 104 /* NullKeyword */:
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 10 /* StringLiteral */:
+ case 203 /* ArrayLiteralExpression */:
+ case 204 /* ObjectLiteralExpression */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ case 225 /* ClassExpression */:
+ case 13 /* RegularExpressionLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 222 /* TemplateExpression */:
+ case 211 /* ParenthesizedExpression */:
+ case 226 /* OmittedExpression */:
+ case 277 /* JsxElement */:
+ case 278 /* JsxSelfClosingElement */:
+ case 281 /* JsxFragment */:
+ return 20 /* Primary */;
+ default:
+ return -1 /* Invalid */;
+ }
+ }
+ ts.getOperatorPrecedence = getOperatorPrecedence;
+ function getBinaryOperatorPrecedence(kind) {
+ switch (kind) {
+ case 60 /* QuestionQuestionToken */:
+ return 4 /* Coalesce */;
+ case 56 /* BarBarToken */:
+ return 5 /* LogicalOR */;
+ case 55 /* AmpersandAmpersandToken */:
+ return 6 /* LogicalAND */;
+ case 51 /* BarToken */:
+ return 7 /* BitwiseOR */;
+ case 52 /* CaretToken */:
+ return 8 /* BitwiseXOR */;
+ case 50 /* AmpersandToken */:
+ return 9 /* BitwiseAND */;
+ case 34 /* EqualsEqualsToken */:
+ case 35 /* ExclamationEqualsToken */:
+ case 36 /* EqualsEqualsEqualsToken */:
+ case 37 /* ExclamationEqualsEqualsToken */:
+ return 10 /* Equality */;
+ case 29 /* LessThanToken */:
+ case 31 /* GreaterThanToken */:
+ case 32 /* LessThanEqualsToken */:
+ case 33 /* GreaterThanEqualsToken */:
+ case 102 /* InstanceOfKeyword */:
+ case 101 /* InKeyword */:
+ case 127 /* AsKeyword */:
+ return 11 /* Relational */;
+ case 47 /* LessThanLessThanToken */:
+ case 48 /* GreaterThanGreaterThanToken */:
+ case 49 /* GreaterThanGreaterThanGreaterThanToken */:
+ return 12 /* Shift */;
+ case 39 /* PlusToken */:
+ case 40 /* MinusToken */:
+ return 13 /* Additive */;
+ case 41 /* AsteriskToken */:
+ case 43 /* SlashToken */:
+ case 44 /* PercentToken */:
+ return 14 /* Multiplicative */;
+ case 42 /* AsteriskAsteriskToken */:
+ return 15 /* Exponentiation */;
+ }
+ // -1 is lower than all other precedences. Returning it will cause binary expression
+ // parsing to stop.
+ return -1;
+ }
+ ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
+ function getSemanticJsxChildren(children) {
+ return ts.filter(children, function (i) {
+ switch (i.kind) {
+ case 287 /* JsxExpression */:
+ return !!i.expression;
+ case 11 /* JsxText */:
+ return !i.containsOnlyTriviaWhiteSpaces;
+ default:
+ return true;
+ }
+ });
+ }
+ ts.getSemanticJsxChildren = getSemanticJsxChildren;
+ function createDiagnosticCollection() {
+ var nonFileDiagnostics = []; // See GH#19873
+ var filesWithDiagnostics = [];
+ var fileDiagnostics = new ts.Map();
+ var hasReadNonFileDiagnostics = false;
+ return {
+ add: add,
+ lookup: lookup,
+ getGlobalDiagnostics: getGlobalDiagnostics,
+ getDiagnostics: getDiagnostics,
+ };
+ function lookup(diagnostic) {
+ var diagnostics;
+ if (diagnostic.file) {
+ diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
+ }
+ else {
+ diagnostics = nonFileDiagnostics;
+ }
+ if (!diagnostics) {
+ return undefined;
+ }
+ var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
+ if (result >= 0) {
+ return diagnostics[result];
+ }
+ return undefined;
+ }
+ function add(diagnostic) {
+ var diagnostics;
+ if (diagnostic.file) {
+ diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
+ if (!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();
+ }
+ diagnostics = nonFileDiagnostics;
+ }
+ ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
+ }
+ function getGlobalDiagnostics() {
+ hasReadNonFileDiagnostics = true;
+ return nonFileDiagnostics;
+ }
+ function getDiagnostics(fileName) {
+ if (fileName) {
+ return fileDiagnostics.get(fileName) || [];
+ }
+ var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
+ if (!nonFileDiagnostics.length) {
+ return fileDiags;
+ }
+ fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
+ return fileDiags;
+ }
+ }
+ ts.createDiagnosticCollection = createDiagnosticCollection;
+ var templateSubstitutionRegExp = /\$\{/g;
+ function escapeTemplateSubstitution(str) {
+ return str.replace(templateSubstitutionRegExp, "\\${");
+ }
+ /** @internal */
+ function hasInvalidEscape(template) {
+ return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
+ ? template.templateFlags
+ : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
+ }
+ ts.hasInvalidEscape = hasInvalidEscape;
+ // 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;
+ // Template strings preserve simple LF newlines, still encode CRLF (or CR)
+ var backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g;
+ var escapedCharsMap = new ts.Map(ts.getEntries({
+ "\t": "\\t",
+ "\v": "\\v",
+ "\f": "\\f",
+ "\b": "\\b",
+ "\r": "\\r",
+ "\n": "\\n",
+ "\\": "\\\\",
+ "\"": "\\\"",
+ "\'": "\\\'",
+ "\`": "\\\`",
+ "\u2028": "\\u2028",
+ "\u2029": "\\u2029",
+ "\u0085": "\\u0085",
+ "\r\n": "\\r\\n", // special case for CRLFs in backticks
+ }));
+ function encodeUtf16EscapeSequence(charCode) {
+ var hexCharCode = charCode.toString(16).toUpperCase();
+ var paddedHexCode = ("0000" + hexCharCode).slice(-4);
+ return "\\u" + paddedHexCode;
+ }
+ function getReplacement(c, offset, input) {
+ if (c.charCodeAt(0) === 0 /* nullCharacter */) {
+ var lookAhead = input.charCodeAt(offset + c.length);
+ 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) || encodeUtf16EscapeSequence(c.charCodeAt(0));
+ }
+ /**
+ * 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 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
+ quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
+ doubleQuoteEscapedCharsRegExp;
+ return s.replace(escapedCharsRegExp, getReplacement);
+ }
+ ts.escapeString = escapeString;
+ 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 encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
+ s;
+ }
+ ts.escapeNonAsciiString = escapeNonAsciiString;
+ // This consists of the first 19 unprintable ASCII characters, JSX 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.
+ var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
+ var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
+ var jsxEscapedCharsMap = new ts.Map(ts.getEntries({
+ "\"": """,
+ "\'": "'"
+ }));
+ function encodeJsxCharacterEntity(charCode) {
+ var hexCharCode = charCode.toString(16).toUpperCase();
+ return "" + hexCharCode + ";";
+ }
+ function getJsxAttributeStringReplacement(c) {
+ if (c.charCodeAt(0) === 0 /* nullCharacter */) {
+ return "";
+ }
+ return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
+ }
+ function escapeJsxAttributeString(s, quoteChar) {
+ var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
+ jsxDoubleQuoteEscapedCharsRegExp;
+ return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
+ }
+ ts.escapeJsxAttributeString = escapeJsxAttributeString;
+ /**
+ * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
+ *
+ * @return non-quoted string
+ */
+ function stripQuotes(name) {
+ var length = name.length;
+ if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
+ return name.substring(1, length - 1);
+ }
+ return name;
+ }
+ ts.stripQuotes = stripQuotes;
+ function isQuoteOrBacktick(charCode) {
+ return charCode === 39 /* singleQuote */ ||
+ charCode === 34 /* doubleQuote */ ||
+ charCode === 96 /* backtick */;
+ }
+ function isIntrinsicJsxName(name) {
+ var ch = name.charCodeAt(0);
+ return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-") || ts.stringContains(name, ":");
+ }
+ ts.isIntrinsicJsxName = isIntrinsicJsxName;
+ var indentStrings = ["", " "];
+ function getIndentString(level) {
+ // prepopulate cache
+ var singleLevel = indentStrings[1];
+ for (var current = indentStrings.length; current <= level; current++) {
+ indentStrings.push(indentStrings[current - 1] + singleLevel);
+ }
+ return indentStrings[level];
+ }
+ ts.getIndentString = getIndentString;
+ function getIndentSize() {
+ return indentStrings[1].length;
+ }
+ ts.getIndentSize = getIndentSize;
+ function createTextWriter(newLine) {
+ var output;
+ var indent;
+ var lineStart;
+ var lineCount;
+ var linePos;
+ var hasTrailingComment = false;
+ function updateLineCountAndPosFor(s) {
+ var lineStartsOfS = ts.computeLineStarts(s);
+ if (lineStartsOfS.length > 1) {
+ lineCount = lineCount + lineStartsOfS.length - 1;
+ linePos = output.length - s.length + ts.last(lineStartsOfS);
+ lineStart = (linePos - output.length) === 0;
+ }
+ else {
+ lineStart = false;
+ }
+ }
+ function writeText(s) {
+ if (s && s.length) {
+ if (lineStart) {
+ s = getIndentString(indent) + s;
+ lineStart = false;
+ }
+ output += s;
+ updateLineCountAndPosFor(s);
+ }
+ }
+ function write(s) {
+ if (s)
+ hasTrailingComment = false;
+ writeText(s);
+ }
+ function writeComment(s) {
+ if (s)
+ hasTrailingComment = true;
+ writeText(s);
+ }
+ function reset() {
+ output = "";
+ indent = 0;
+ lineStart = true;
+ lineCount = 0;
+ linePos = 0;
+ hasTrailingComment = false;
+ }
+ function rawWrite(s) {
+ if (s !== undefined) {
+ output += s;
+ updateLineCountAndPosFor(s);
+ hasTrailingComment = false;
+ }
+ }
+ function writeLiteral(s) {
+ if (s && s.length) {
+ write(s);
+ }
+ }
+ function writeLine(force) {
+ if (!lineStart || force) {
+ output += newLine;
+ lineCount++;
+ linePos = output.length;
+ lineStart = true;
+ hasTrailingComment = false;
+ }
+ }
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
+ reset();
+ return {
+ write: write,
+ rawWrite: rawWrite,
+ writeLiteral: writeLiteral,
+ writeLine: writeLine,
+ increaseIndent: function () { indent++; },
+ decreaseIndent: function () { indent--; },
+ getIndent: function () { return indent; },
+ getTextPos: function () { return output.length; },
+ getLine: function () { return lineCount; },
+ getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
+ getText: function () { return output; },
+ isAtStartOfLine: function () { return lineStart; },
+ hasTrailingComment: function () { return hasTrailingComment; },
+ hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
+ clear: reset,
+ reportInaccessibleThisError: ts.noop,
+ reportPrivateInBaseOfClassExpression: ts.noop,
+ reportInaccessibleUniqueSymbolError: ts.noop,
+ trackSymbol: function () { return false; },
+ writeKeyword: write,
+ writeOperator: write,
+ writeParameter: write,
+ writeProperty: write,
+ writePunctuation: write,
+ writeSpace: write,
+ writeStringLiteral: write,
+ writeSymbol: function (s, _) { return write(s); },
+ writeTrailingSemicolon: write,
+ writeComment: writeComment,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
+ };
+ }
+ ts.createTextWriter = createTextWriter;
+ function getTrailingSemicolonDeferringWriter(writer) {
+ var pendingTrailingSemicolon = false;
+ function commitPendingTrailingSemicolon() {
+ if (pendingTrailingSemicolon) {
+ writer.writeTrailingSemicolon(";");
+ pendingTrailingSemicolon = false;
+ }
+ }
+ return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
+ pendingTrailingSemicolon = true;
+ }, writeLiteral: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeLiteral(s);
+ }, writeStringLiteral: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeStringLiteral(s);
+ }, writeSymbol: function (s, sym) {
+ commitPendingTrailingSemicolon();
+ writer.writeSymbol(s, sym);
+ }, writePunctuation: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writePunctuation(s);
+ }, writeKeyword: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeKeyword(s);
+ }, writeOperator: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeOperator(s);
+ }, writeParameter: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeParameter(s);
+ }, writeSpace: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeSpace(s);
+ }, writeProperty: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeProperty(s);
+ }, writeComment: function (s) {
+ commitPendingTrailingSemicolon();
+ writer.writeComment(s);
+ }, writeLine: function () {
+ commitPendingTrailingSemicolon();
+ writer.writeLine();
+ }, increaseIndent: function () {
+ commitPendingTrailingSemicolon();
+ writer.increaseIndent();
+ }, decreaseIndent: function () {
+ commitPendingTrailingSemicolon();
+ writer.decreaseIndent();
+ } });
+ }
+ ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
+ function hostUsesCaseSensitiveFileNames(host) {
+ return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
+ }
+ ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
+ function hostGetCanonicalFileName(host) {
+ return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
+ }
+ ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
+ function getResolvedExternalModuleName(host, file, referenceFile) {
+ return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
+ }
+ ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
+ function getCanonicalAbsolutePath(host, path) {
+ return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory()));
+ }
+ function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
+ var file = resolver.getExternalModuleFileFromDeclaration(declaration);
+ if (!file || file.isDeclarationFile) {
+ return undefined;
+ }
+ // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it
+ var specifier = getExternalModuleName(declaration);
+ if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) &&
+ getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) {
+ return undefined;
+ }
+ 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 = ts.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, /*isAbsolutePathAnUrl*/ false);
+ var extensionless = removeFileExtension(relativePath);
+ return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
+ }
+ ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
+ function getOwnEmitOutputFilePath(fileName, host, extension) {
+ var compilerOptions = host.getCompilerOptions();
+ var emitOutputFilePathWithoutExtension;
+ if (compilerOptions.outDir) {
+ emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
+ }
+ else {
+ emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
+ }
+ return emitOutputFilePathWithoutExtension + extension;
+ }
+ ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
+ function getDeclarationEmitOutputFilePath(fileName, host) {
+ return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
+ }
+ ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
+ function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
+ var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
+ var path = outputDir
+ ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
+ : fileName;
+ var declarationExtension = getDeclarationEmitExtensionForPath(path);
+ return removeFileExtension(path) + declarationExtension;
+ }
+ ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
+ function getDeclarationEmitExtensionForPath(path) {
+ return ts.fileExtensionIsOneOf(path, [".mjs" /* Mjs */, ".mts" /* Mts */]) ? ".d.mts" /* Dmts */ :
+ ts.fileExtensionIsOneOf(path, [".cjs" /* Cjs */, ".cts" /* Cts */]) ? ".d.cts" /* Dcts */ :
+ ts.fileExtensionIsOneOf(path, [".json" /* Json */]) ? ".json.d.ts" : // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well
+ ".d.ts" /* Dts */;
+ }
+ ts.getDeclarationEmitExtensionForPath = getDeclarationEmitExtensionForPath;
+ function outFile(options) {
+ return options.outFile || options.out;
+ }
+ ts.outFile = outFile;
+ /** Returns 'undefined' if and only if 'options.paths' is undefined. */
+ function getPathsBasePath(options, host) {
+ var _a, _b;
+ if (!options.paths)
+ return undefined;
+ return (_a = options.baseUrl) !== null && _a !== void 0 ? _a : ts.Debug.checkDefined(options.pathsBasePath || ((_b = host.getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'.");
+ }
+ ts.getPathsBasePath = getPathsBasePath;
+ /**
+ * 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, forceDtsEmit) {
+ var options = host.getCompilerOptions();
+ if (outFile(options)) {
+ var moduleKind = getEmitModuleKind(options);
+ var moduleEmitEnabled_1 = options.emitDeclarationOnly || 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, host, forceDtsEmit);
+ });
+ }
+ else {
+ var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
+ }
+ }
+ ts.getSourceFilesToEmit = getSourceFilesToEmit;
+ /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
+ function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
+ var options = host.getCompilerOptions();
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !host.isSourceFileFromExternalLibrary(sourceFile) &&
+ (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
+ !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)));
+ }
+ ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
+ function getSourceFilePathInNewDir(fileName, host, newDirPath) {
+ return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
+ }
+ ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
+ function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
+ var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
+ var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
+ sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
+ return ts.combinePaths(newDirPath, sourceFilePath);
+ }
+ ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
+ function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
+ host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
+ diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
+ }, sourceFiles);
+ }
+ ts.writeFile = writeFile;
+ function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
+ if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
+ var parentDirectory = ts.getDirectoryPath(directoryPath);
+ ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
+ createDirectory(directoryPath);
+ }
+ }
+ function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
+ // PERF: Checking for directory existence is expensive. Instead, assume the directory exists
+ // and fall back to creating it if the file write fails.
+ try {
+ writeFile(path, data, writeByteOrderMark);
+ }
+ catch (_a) {
+ ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
+ writeFile(path, data, writeByteOrderMark);
+ }
+ }
+ ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
+ function getLineOfLocalPosition(sourceFile, pos) {
+ var lineStarts = ts.getLineStarts(sourceFile);
+ return ts.computeLineOfPosition(lineStarts, pos);
+ }
+ ts.getLineOfLocalPosition = getLineOfLocalPosition;
+ function getLineOfLocalPositionFromLineMap(lineMap, pos) {
+ return ts.computeLineOfPosition(lineMap, pos);
+ }
+ ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
+ function getFirstConstructorWithBody(node) {
+ return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
+ }
+ ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
+ function getSetAccessorValueParameter(accessor) {
+ if (accessor && accessor.parameters.length > 0) {
+ var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
+ return accessor.parameters[hasThis ? 1 : 0];
+ }
+ }
+ ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
+ /** 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)) {
+ return thisParameter;
+ }
+ }
+ }
+ ts.getThisParameter = getThisParameter;
+ function parameterIsThisKeyword(parameter) {
+ return isThisIdentifier(parameter.name);
+ }
+ ts.parameterIsThisKeyword = parameterIsThisKeyword;
+ function isThisIdentifier(node) {
+ return !!node && node.kind === 79 /* Identifier */ && identifierIsThisKeyword(node);
+ }
+ ts.isThisIdentifier = isThisIdentifier;
+ function isThisInTypeQuery(node) {
+ if (!isThisIdentifier(node)) {
+ return false;
+ }
+ while (ts.isQualifiedName(node.parent) && node.parent.left === node) {
+ node = node.parent;
+ }
+ return node.parent.kind === 180 /* TypeQuery */;
+ }
+ ts.isThisInTypeQuery = isThisInTypeQuery;
+ function identifierIsThisKeyword(id) {
+ return id.originalKeywordKind === 108 /* 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 === 171 /* GetAccessor */) {
+ getAccessor = accessor;
+ }
+ else if (accessor.kind === 172 /* SetAccessor */) {
+ setAccessor = accessor;
+ }
+ else {
+ ts.Debug.fail("Accessor has wrong kind");
+ }
+ }
+ else {
+ ts.forEach(declarations, function (member) {
+ if (ts.isAccessor(member)
+ && isStatic(member) === isStatic(accessor)) {
+ var memberName = getPropertyNameForPropertyNameNode(member.name);
+ var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
+ if (memberName === accessorName) {
+ if (!firstAccessor) {
+ firstAccessor = member;
+ }
+ else if (!secondAccessor) {
+ secondAccessor = member;
+ }
+ if (member.kind === 171 /* GetAccessor */ && !getAccessor) {
+ getAccessor = member;
+ }
+ if (member.kind === 172 /* SetAccessor */ && !setAccessor) {
+ setAccessor = member;
+ }
+ }
+ }
+ });
+ }
+ return {
+ firstAccessor: firstAccessor,
+ secondAccessor: secondAccessor,
+ getAccessor: getAccessor,
+ setAccessor: setAccessor
+ };
+ }
+ 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. Also gets the type of
+ * functions only the JSDoc case.
+ */
+ function getEffectiveTypeAnnotationNode(node) {
+ if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
+ return undefined;
+ var type = node.type;
+ if (type || !isInJSFile(node))
+ return type;
+ return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
+ }
+ ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
+ function getTypeAnnotationNode(node) {
+ 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) {
+ return ts.isJSDocSignature(node) ?
+ node.type && node.type.typeExpression && node.type.typeExpression.type :
+ node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
+ }
+ ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
+ function getJSDocTypeParameterDeclarations(node) {
+ 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 === 318 /* 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);
+ }
+ ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
+ function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
+ emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
+ }
+ 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();
+ }
+ }
+ 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();
+ }
+ }
+ ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
+ function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
+ if (comments && comments.length > 0) {
+ if (leadingSeparator) {
+ writer.writeSpace(" ");
+ }
+ var emitInterveningSeparator = false;
+ for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
+ var comment = comments_1[_i];
+ if (emitInterveningSeparator) {
+ writer.writeSpace(" ");
+ emitInterveningSeparator = false;
+ }
+ writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
+ if (comment.hasTrailingNewLine) {
+ writer.writeLine();
+ }
+ else {
+ emitInterveningSeparator = true;
+ }
+ }
+ if (emitInterveningSeparator && trailingSeparator) {
+ writer.writeSpace(" ");
+ }
+ }
+ }
+ 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) {
+ var detachedComments = [];
+ var lastComment = void 0;
+ for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
+ var comment = leadingComments_1[_i];
+ if (lastComment) {
+ 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;
+ }
+ }
+ detachedComments.push(comment);
+ 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, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
+ currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
+ }
+ }
+ }
+ return currentDetachedCommentInfo;
+ function isPinnedCommentLocal(comment) {
+ return isPinnedComment(text, comment.pos);
+ }
+ }
+ ts.emitDetachedComments = emitDetachedComments;
+ function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
+ if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
+ var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
+ var lineCount = lineMap.length;
+ var firstCommentLineIndent = void 0;
+ for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
+ var nextLineStart = (currentLine + 1) === lineCount
+ ? 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.writeComment(text.substring(commentPos, commentEnd));
+ }
+ }
+ ts.writeCommentRange = writeCommentRange;
+ function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
+ var end = Math.min(commentEnd, nextLineStart - 1);
+ var currentLineText = ts.trimString(text.substring(pos, end));
+ if (currentLineText) {
+ // trimmed forward and ending spaces text
+ writer.writeComment(currentLineText);
+ if (end !== commentEnd) {
+ writer.writeLine();
+ }
+ }
+ else {
+ // Empty string - make sure we write empty line
+ writer.rawWrite(newLine);
+ }
+ }
+ function calculateIndent(text, pos, end) {
+ var currentLineIndent = 0;
+ for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
+ if (text.charCodeAt(pos) === 9 /* tab */) {
+ // Tabs = TabSize = indent size and go to next tabStop
+ currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
+ }
+ else {
+ // Single space
+ currentLineIndent++;
+ }
+ }
+ return currentLineIndent;
+ }
+ function hasEffectiveModifiers(node) {
+ return getEffectiveModifierFlags(node) !== 0 /* None */;
+ }
+ ts.hasEffectiveModifiers = hasEffectiveModifiers;
+ function hasSyntacticModifiers(node) {
+ return getSyntacticModifierFlags(node) !== 0 /* None */;
+ }
+ ts.hasSyntacticModifiers = hasSyntacticModifiers;
+ function hasEffectiveModifier(node, flags) {
+ return !!getSelectedEffectiveModifierFlags(node, flags);
+ }
+ ts.hasEffectiveModifier = hasEffectiveModifier;
+ function hasSyntacticModifier(node, flags) {
+ return !!getSelectedSyntacticModifierFlags(node, flags);
+ }
+ ts.hasSyntacticModifier = hasSyntacticModifier;
+ function isStatic(node) {
+ // https://tc39.es/ecma262/#sec-static-semantics-isstatic
+ return ts.isClassElement(node) && hasStaticModifier(node) || ts.isClassStaticBlockDeclaration(node);
+ }
+ ts.isStatic = isStatic;
+ function hasStaticModifier(node) {
+ return hasSyntacticModifier(node, 32 /* Static */);
+ }
+ ts.hasStaticModifier = hasStaticModifier;
+ function hasOverrideModifier(node) {
+ return hasEffectiveModifier(node, 16384 /* Override */);
+ }
+ ts.hasOverrideModifier = hasOverrideModifier;
+ function hasAbstractModifier(node) {
+ return hasSyntacticModifier(node, 128 /* Abstract */);
+ }
+ ts.hasAbstractModifier = hasAbstractModifier;
+ function hasAmbientModifier(node) {
+ return hasSyntacticModifier(node, 2 /* Ambient */);
+ }
+ ts.hasAmbientModifier = hasAmbientModifier;
+ function hasEffectiveReadonlyModifier(node) {
+ return hasEffectiveModifier(node, 64 /* Readonly */);
+ }
+ ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier;
+ function getSelectedEffectiveModifierFlags(node, flags) {
+ return getEffectiveModifierFlags(node) & flags;
+ }
+ ts.getSelectedEffectiveModifierFlags = getSelectedEffectiveModifierFlags;
+ function getSelectedSyntacticModifierFlags(node, flags) {
+ return getSyntacticModifierFlags(node) & flags;
+ }
+ ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags;
+ function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) {
+ if (node.kind >= 0 /* FirstToken */ && node.kind <= 159 /* LastToken */) {
+ return 0 /* None */;
+ }
+ if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) {
+ node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */;
+ }
+ if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) {
+ node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */;
+ }
+ return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */);
+ }
+ /**
+ * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance.
+ *
+ * NOTE: This function may use `parent` pointers.
+ */
+ function getEffectiveModifierFlags(node) {
+ return getModifierFlagsWorker(node, /*includeJSDoc*/ true);
+ }
+ ts.getEffectiveModifierFlags = getEffectiveModifierFlags;
+ function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) {
+ return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true);
+ }
+ ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc = getEffectiveModifierFlagsAlwaysIncludeJSDoc;
+ /**
+ * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance.
+ *
+ * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
+ */
+ function getSyntacticModifierFlags(node) {
+ return getModifierFlagsWorker(node, /*includeJSDoc*/ false);
+ }
+ ts.getSyntacticModifierFlags = getSyntacticModifierFlags;
+ function getJSDocModifierFlagsNoCache(node) {
+ var flags = 0 /* None */;
+ if (!!node.parent && !ts.isParameter(node)) {
+ if (isInJSFile(node)) {
+ if (ts.getJSDocPublicTagNoCache(node))
+ flags |= 4 /* Public */;
+ if (ts.getJSDocPrivateTagNoCache(node))
+ flags |= 8 /* Private */;
+ if (ts.getJSDocProtectedTagNoCache(node))
+ flags |= 16 /* Protected */;
+ if (ts.getJSDocReadonlyTagNoCache(node))
+ flags |= 64 /* Readonly */;
+ if (ts.getJSDocOverrideTagNoCache(node))
+ flags |= 16384 /* Override */;
+ }
+ if (ts.getJSDocDeprecatedTagNoCache(node))
+ flags |= 8192 /* Deprecated */;
+ }
+ return flags;
+ }
+ /**
+ * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored.
+ *
+ * NOTE: This function may use `parent` pointers.
+ */
+ function getEffectiveModifierFlagsNoCache(node) {
+ return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node);
+ }
+ ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache;
+ /**
+ * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored.
+ *
+ * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
+ */
+ function getSyntacticModifierFlagsNoCache(node) {
+ var flags = modifiersToFlags(node.modifiers);
+ if (node.flags & 4 /* NestedNamespace */ || (node.kind === 79 /* Identifier */ && node.isInJSDocNamespace)) {
+ flags |= 1 /* Export */;
+ }
+ return flags;
+ }
+ ts.getSyntacticModifierFlagsNoCache = getSyntacticModifierFlagsNoCache;
+ function modifiersToFlags(modifiers) {
+ var flags = 0 /* None */;
+ if (modifiers) {
+ for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
+ var modifier = modifiers_1[_i];
+ flags |= modifierToFlag(modifier.kind);
+ }
+ }
+ return flags;
+ }
+ ts.modifiersToFlags = modifiersToFlags;
+ function modifierToFlag(token) {
+ switch (token) {
+ case 124 /* StaticKeyword */: return 32 /* Static */;
+ case 123 /* PublicKeyword */: return 4 /* Public */;
+ case 122 /* ProtectedKeyword */: return 16 /* Protected */;
+ case 121 /* PrivateKeyword */: return 8 /* Private */;
+ case 126 /* AbstractKeyword */: return 128 /* Abstract */;
+ case 93 /* ExportKeyword */: return 1 /* Export */;
+ case 135 /* DeclareKeyword */: return 2 /* Ambient */;
+ case 85 /* ConstKeyword */: return 2048 /* Const */;
+ case 88 /* DefaultKeyword */: return 512 /* Default */;
+ case 131 /* AsyncKeyword */: return 256 /* Async */;
+ case 144 /* ReadonlyKeyword */: return 64 /* Readonly */;
+ case 158 /* OverrideKeyword */: return 16384 /* Override */;
+ }
+ return 0 /* None */;
+ }
+ ts.modifierToFlag = modifierToFlag;
+ function createModifiers(modifierFlags) {
+ return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined;
+ }
+ ts.createModifiers = createModifiers;
+ function isLogicalOperator(token) {
+ return token === 56 /* BarBarToken */
+ || token === 55 /* AmpersandAmpersandToken */
+ || token === 53 /* ExclamationToken */;
+ }
+ ts.isLogicalOperator = isLogicalOperator;
+ function isLogicalOrCoalescingAssignmentOperator(token) {
+ return token === 75 /* BarBarEqualsToken */
+ || token === 76 /* AmpersandAmpersandEqualsToken */
+ || token === 77 /* QuestionQuestionEqualsToken */;
+ }
+ ts.isLogicalOrCoalescingAssignmentOperator = isLogicalOrCoalescingAssignmentOperator;
+ function isLogicalOrCoalescingAssignmentExpression(expr) {
+ return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind);
+ }
+ ts.isLogicalOrCoalescingAssignmentExpression = isLogicalOrCoalescingAssignmentExpression;
+ function isAssignmentOperator(token) {
+ return token >= 63 /* FirstAssignment */ && token <= 78 /* 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) {
+ var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
+ return cls && !cls.isImplements ? cls.class : undefined;
+ }
+ ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
+ function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
+ return ts.isExpressionWithTypeArguments(node)
+ && ts.isHeritageClause(node.parent)
+ && ts.isClassLike(node.parent.parent)
+ ? { class: node.parent.parent, isImplements: node.parent.token === 117 /* ImplementsKeyword */ }
+ : undefined;
+ }
+ ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
+ function isAssignmentExpression(node, excludeCompoundAssignment) {
+ return ts.isBinaryExpression(node)
+ && (excludeCompoundAssignment
+ ? node.operatorToken.kind === 63 /* EqualsToken */
+ : isAssignmentOperator(node.operatorToken.kind))
+ && ts.isLeftHandSideExpression(node.left);
+ }
+ ts.isAssignmentExpression = isAssignmentExpression;
+ function isLeftHandSideOfAssignment(node) {
+ return isAssignmentExpression(node.parent) && node.parent.left === node;
+ }
+ ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment;
+ function isDestructuringAssignment(node) {
+ if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
+ var kind = node.left.kind;
+ return kind === 204 /* ObjectLiteralExpression */
+ || kind === 203 /* ArrayLiteralExpression */;
+ }
+ return false;
+ }
+ ts.isDestructuringAssignment = isDestructuringAssignment;
+ function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
+ return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
+ }
+ ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
+ function isEntityNameExpression(node) {
+ return node.kind === 79 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
+ }
+ ts.isEntityNameExpression = isEntityNameExpression;
+ function getFirstIdentifier(node) {
+ switch (node.kind) {
+ case 79 /* Identifier */:
+ return node;
+ case 160 /* QualifiedName */:
+ do {
+ node = node.left;
+ } while (node.kind !== 79 /* Identifier */);
+ return node;
+ case 205 /* PropertyAccessExpression */:
+ do {
+ node = node.expression;
+ } while (node.kind !== 79 /* Identifier */);
+ return node;
+ }
+ }
+ ts.getFirstIdentifier = getFirstIdentifier;
+ function isDottedName(node) {
+ return node.kind === 79 /* Identifier */
+ || node.kind === 108 /* ThisKeyword */
+ || node.kind === 106 /* SuperKeyword */
+ || node.kind === 230 /* MetaProperty */
+ || node.kind === 205 /* PropertyAccessExpression */ && isDottedName(node.expression)
+ || node.kind === 211 /* ParenthesizedExpression */ && isDottedName(node.expression);
+ }
+ ts.isDottedName = isDottedName;
+ function isPropertyAccessEntityNameExpression(node) {
+ return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
+ }
+ ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
+ function tryGetPropertyAccessOrIdentifierToString(expr) {
+ if (ts.isPropertyAccessExpression(expr)) {
+ var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
+ if (baseStr !== undefined) {
+ return baseStr + "." + entityNameToString(expr.name);
+ }
+ }
+ else if (ts.isElementAccessExpression(expr)) {
+ var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
+ if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) {
+ return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression);
+ }
+ }
+ else if (ts.isIdentifier(expr)) {
+ return ts.unescapeLeadingUnderscores(expr.escapedText);
+ }
+ return undefined;
+ }
+ ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
+ function isPrototypeAccess(node) {
+ return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
+ }
+ ts.isPrototypeAccess = isPrototypeAccess;
+ function isRightSideOfQualifiedNameOrPropertyAccess(node) {
+ return (node.parent.kind === 160 /* QualifiedName */ && node.parent.right === node) ||
+ (node.parent.kind === 205 /* PropertyAccessExpression */ && node.parent.name === node);
+ }
+ ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
+ function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node) {
+ return ts.isQualifiedName(node.parent) && node.parent.right === node
+ || ts.isPropertyAccessExpression(node.parent) && node.parent.name === node
+ || ts.isJSDocMemberName(node.parent) && node.parent.right === node;
+ }
+ ts.isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName = isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName;
+ function isEmptyObjectLiteral(expression) {
+ return expression.kind === 204 /* ObjectLiteralExpression */ &&
+ expression.properties.length === 0;
+ }
+ ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
+ function isEmptyArrayLiteral(expression) {
+ return expression.kind === 203 /* ArrayLiteralExpression */ &&
+ expression.elements.length === 0;
+ }
+ ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
+ function getLocalSymbolForExportDefault(symbol) {
+ if (!isExportDefaultSymbol(symbol) || !symbol.declarations)
+ return undefined;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.localSymbol)
+ return decl.localSymbol;
+ }
+ return undefined;
+ }
+ ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function isExportDefaultSymbol(symbol) {
+ return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* Default */);
+ }
+ /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
+ function tryExtractTSExtension(fileName) {
+ return ts.find(supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.tryExtractTSExtension = tryExtractTSExtension;
+ /**
+ * 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);
+ }
+ else if (charCode < 0x800) {
+ output.push((charCode >> 6) | 192);
+ output.push((charCode & 63) | 128);
+ }
+ else if (charCode < 0x10000) {
+ output.push((charCode >> 12) | 224);
+ output.push(((charCode >> 6) & 63) | 128);
+ output.push((charCode & 63) | 128);
+ }
+ else if (charCode < 0x20000) {
+ output.push((charCode >> 18) | 240);
+ output.push(((charCode >> 12) & 63) | 128);
+ output.push(((charCode >> 6) & 63) | 128);
+ output.push((charCode & 63) | 128);
+ }
+ else {
+ ts.Debug.assert(false, "Unexpected code point");
+ }
+ }
+ return output;
+ }
+ var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+ /**
+ * Converts a string to a base-64 encoded ASCII string.
+ */
+ function convertToBase64(input) {
+ var result = "";
+ var charCodes = getExpandedCharCodes(input);
+ var i = 0;
+ 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;
+ }
+ return result;
+ }
+ ts.convertToBase64 = convertToBase64;
+ function getStringFromExpandedCharCodes(codes) {
+ var output = "";
+ var i = 0;
+ var length = codes.length;
+ while (i < length) {
+ var charCode = codes[i];
+ if (charCode < 0x80) {
+ output += String.fromCharCode(charCode);
+ i++;
+ }
+ else if ((charCode & 192) === 192) {
+ var value = charCode & 63;
+ i++;
+ var nextCode = codes[i];
+ while ((nextCode & 192) === 128) {
+ value = (value << 6) | (nextCode & 63);
+ 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++;
+ }
+ }
+ return output;
+ }
+ function base64encode(host, input) {
+ if (host && host.base64encode) {
+ return host.base64encode(input);
+ }
+ return convertToBase64(input);
+ }
+ ts.base64encode = base64encode;
+ function base64decode(host, input) {
+ if (host && host.base64decode) {
+ return host.base64decode(input);
+ }
+ var length = input.length;
+ 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]);
+ var ch4 = base64Digits.indexOf(input[i + 3]);
+ 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) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
+ expandedCharCodes.push(code1);
+ }
+ else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
+ expandedCharCodes.push(code1, code2);
+ }
+ else {
+ expandedCharCodes.push(code1, code2, code3);
+ }
+ i += 4;
+ }
+ return getStringFromExpandedCharCodes(expandedCharCodes);
+ }
+ ts.base64decode = base64decode;
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
+ }
+ catch (e) {
+ // gracefully handle if readFile fails or returns not JSON
+ return {};
+ }
+ }
+ ts.readJson = readJson;
+ function directoryProbablyExists(directoryName, host) {
+ // if host does not support 'directoryExists' assume that directory will exist
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
+ var carriageReturnLineFeed = "\r\n";
+ var lineFeed = "\n";
+ function getNewLineCharacter(options, getNewLine) {
+ switch (options.newLine) {
+ case 0 /* CarriageReturnLineFeed */:
+ return carriageReturnLineFeed;
+ case 1 /* LineFeed */:
+ return lineFeed;
+ }
+ return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
+ }
+ ts.getNewLineCharacter = getNewLineCharacter;
+ /**
+ * Creates a new TextRange from the provided pos and end.
+ *
+ * @param pos The start position.
+ * @param end The end position.
+ */
+ function createRange(pos, end) {
+ if (end === void 0) { end = pos; }
+ ts.Debug.assert(end >= pos || end === -1);
+ 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);
+ }
+ ts.createTokenRange = createTokenRange;
+ function rangeIsOnSingleLine(range, sourceFile) {
+ return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
+ }
+ ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
+ function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
+ return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
+ }
+ ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
+ function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
+ return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
+ }
+ ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
+ function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
+ return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
+ }
+ ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
+ function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
+ return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
+ }
+ ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
+ function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
+ var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
+ return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
+ }
+ ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
+ function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
+ return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
+ }
+ ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
+ function isNodeArrayMultiLine(list, sourceFile) {
+ return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
+ }
+ ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
+ function positionsAreOnSameLine(pos1, pos2, sourceFile) {
+ return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
+ }
+ ts.positionsAreOnSameLine = positionsAreOnSameLine;
+ function getStartPositionOfRange(range, sourceFile, includeComments) {
+ return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
+ }
+ ts.getStartPositionOfRange = getStartPositionOfRange;
+ function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
+ var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
+ var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
+ return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
+ }
+ ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
+ function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
+ var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
+ return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
+ }
+ ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
+ function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
+ if (stopPos === void 0) { stopPos = 0; }
+ while (pos-- > stopPos) {
+ if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
+ return pos;
+ }
+ }
+ }
+ /**
+ * 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 259 /* EnumDeclaration */:
+ case 260 /* ModuleDeclaration */:
+ return parseNode === parseNode.parent.name;
+ }
+ }
+ return false;
+ }
+ ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
+ function getInitializedVariables(node) {
+ return ts.filter(node.declarations, isInitializedVariable);
+ }
+ ts.getInitializedVariables = getInitializedVariables;
+ function isInitializedVariable(node) {
+ return node.initializer !== undefined;
+ }
+ function isWatchSet(options) {
+ // Firefox has Object.prototype.watch
+ return options.watch && options.hasOwnProperty("watch");
+ }
+ ts.isWatchSet = isWatchSet;
+ function closeFileWatcher(watcher) {
+ watcher.close();
+ }
+ ts.closeFileWatcher = closeFileWatcher;
+ function getCheckFlags(symbol) {
+ return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
+ }
+ ts.getCheckFlags = getCheckFlags;
+ function getDeclarationModifierFlagsFromSymbol(s, isWrite) {
+ if (isWrite === void 0) { isWrite = false; }
+ if (s.valueDeclaration) {
+ var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 172 /* SetAccessor */; })) || s.valueDeclaration;
+ var flags = ts.getCombinedModifierFlags(declaration);
+ return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
+ }
+ if (getCheckFlags(s) & 6 /* Synthetic */) {
+ var checkFlags = s.checkFlags;
+ var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
+ checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
+ 16 /* Protected */;
+ var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
+ return accessModifier | staticModifier;
+ }
+ if (s.flags & 4194304 /* Prototype */) {
+ return 4 /* Public */ | 32 /* Static */;
+ }
+ return 0;
+ }
+ ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
+ function skipAlias(symbol, checker) {
+ 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 /* Write */;
+ }
+ ts.isWriteOnlyAccess = isWriteOnlyAccess;
+ function isWriteAccess(node) {
+ 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 /* Read */;
+ switch (parent.kind) {
+ case 211 /* ParenthesizedExpression */:
+ return accessKind(parent);
+ case 219 /* PostfixUnaryExpression */:
+ case 218 /* PrefixUnaryExpression */:
+ var operator = parent.operator;
+ return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
+ case 220 /* BinaryExpression */:
+ var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
+ return left === node && isAssignmentOperator(operatorToken.kind) ?
+ operatorToken.kind === 63 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
+ : 0 /* Read */;
+ case 205 /* PropertyAccessExpression */:
+ return parent.name !== node ? 0 /* Read */ : accessKind(parent);
+ case 294 /* PropertyAssignment */: {
+ var parentAccess = accessKind(parent.parent);
+ // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
+ return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
+ }
+ case 295 /* ShorthandPropertyAssignment */:
+ // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
+ return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
+ case 203 /* ArrayLiteralExpression */:
+ return accessKind(parent);
+ default:
+ return 0 /* Read */;
+ }
+ function writeOrReadWrite() {
+ // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
+ return parent.parent && walkUpParenthesizedExpressions(parent.parent).kind === 237 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
+ }
+ }
+ function reverseAccessKind(a) {
+ switch (a) {
+ case 0 /* Read */:
+ return 1 /* Write */;
+ case 1 /* Write */:
+ return 0 /* Read */;
+ case 2 /* ReadWrite */:
+ return 2 /* ReadWrite */;
+ default:
+ return ts.Debug.assertNever(a);
+ }
+ }
+ function compareDataObjects(dst, src) {
+ if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
+ return false;
+ }
+ for (var e in dst) {
+ if (typeof dst[e] === "object") {
+ if (!compareDataObjects(dst[e], src[e])) {
+ return false;
+ }
+ }
+ else if (typeof dst[e] !== "function") {
+ if (dst[e] !== src[e]) {
+ return false;
+ }
+ }
+ }
+ 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 mutateMapSkippingNewValues(map, newMap, options) {
+ var 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);
+ }
+ });
+ }
+ ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
+ /**
+ * Mutates the map with newMap such that keys in map will be same as newMap.
+ */
+ function mutateMap(map, newMap, options) {
+ // Needs update
+ mutateMapSkippingNewValues(map, newMap, options);
+ var createNewValue = options.createNewValue;
+ // 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;
+ function isAbstractConstructorSymbol(symbol) {
+ if (symbol.flags & 32 /* Class */) {
+ var declaration = getClassLikeDeclarationOfSymbol(symbol);
+ return !!declaration && hasSyntacticModifier(declaration, 128 /* Abstract */);
+ }
+ return false;
+ }
+ ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
+ function getClassLikeDeclarationOfSymbol(symbol) {
+ var _a;
+ return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike);
+ }
+ ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
+ function getObjectFlags(type) {
+ return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
+ }
+ ts.getObjectFlags = getObjectFlags;
+ function typeHasCallOrConstructSignatures(type, checker) {
+ return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
+ }
+ ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
+ function forSomeAncestorDirectory(directory, callback) {
+ return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
+ }
+ ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
+ function isUMDExportSymbol(symbol) {
+ return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
+ }
+ ts.isUMDExportSymbol = isUMDExportSymbol;
+ function showModuleSpecifier(_a) {
+ var moduleSpecifier = _a.moduleSpecifier;
+ return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
+ }
+ ts.showModuleSpecifier = showModuleSpecifier;
+ function getLastChild(node) {
+ var lastChild;
+ ts.forEachChild(node, function (child) {
+ 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];
+ break;
+ }
+ }
+ });
+ return lastChild;
+ }
+ ts.getLastChild = getLastChild;
+ function addToSeen(seen, key, value) {
+ if (value === void 0) { value = true; }
+ if (seen.has(key)) {
+ return false;
+ }
+ seen.set(key, value);
+ return true;
+ }
+ ts.addToSeen = addToSeen;
+ function isObjectTypeDeclaration(node) {
+ return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
+ }
+ ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 176 /* FirstTypeNode */ && kind <= 199 /* LastTypeNode */)
+ || kind === 130 /* AnyKeyword */
+ || kind === 154 /* UnknownKeyword */
+ || kind === 146 /* NumberKeyword */
+ || kind === 157 /* BigIntKeyword */
+ || kind === 147 /* ObjectKeyword */
+ || kind === 133 /* BooleanKeyword */
+ || kind === 149 /* StringKeyword */
+ || kind === 150 /* SymbolKeyword */
+ || kind === 114 /* VoidKeyword */
+ || kind === 152 /* UndefinedKeyword */
+ || kind === 143 /* NeverKeyword */
+ || kind === 227 /* ExpressionWithTypeArguments */
+ || kind === 310 /* JSDocAllType */
+ || kind === 311 /* JSDocUnknownType */
+ || kind === 312 /* JSDocNullableType */
+ || kind === 313 /* JSDocNonNullableType */
+ || kind === 314 /* JSDocOptionalType */
+ || kind === 315 /* JSDocFunctionType */
+ || kind === 316 /* JSDocVariadicType */;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
+ function isAccessExpression(node) {
+ return node.kind === 205 /* PropertyAccessExpression */ || node.kind === 206 /* ElementAccessExpression */;
+ }
+ ts.isAccessExpression = isAccessExpression;
+ function getNameOfAccessExpression(node) {
+ if (node.kind === 205 /* PropertyAccessExpression */) {
+ return node.name;
+ }
+ ts.Debug.assert(node.kind === 206 /* ElementAccessExpression */);
+ return node.argumentExpression;
+ }
+ ts.getNameOfAccessExpression = getNameOfAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
+ function isNamedImportsOrExports(node) {
+ return node.kind === 268 /* NamedImports */ || node.kind === 272 /* NamedExports */;
+ }
+ ts.isNamedImportsOrExports = isNamedImportsOrExports;
+ function getLeftmostAccessExpression(expr) {
+ while (isAccessExpression(expr)) {
+ expr = expr.expression;
+ }
+ return expr;
+ }
+ ts.getLeftmostAccessExpression = getLeftmostAccessExpression;
+ function getLeftmostExpression(node, stopAtCallExpressions) {
+ while (true) {
+ switch (node.kind) {
+ case 219 /* PostfixUnaryExpression */:
+ node = node.operand;
+ continue;
+ case 220 /* BinaryExpression */:
+ node = node.left;
+ continue;
+ case 221 /* ConditionalExpression */:
+ node = node.condition;
+ continue;
+ case 209 /* TaggedTemplateExpression */:
+ node = node.tag;
+ continue;
+ case 207 /* CallExpression */:
+ if (stopAtCallExpressions) {
+ return node;
+ }
+ // falls through
+ case 228 /* AsExpression */:
+ case 206 /* ElementAccessExpression */:
+ case 205 /* PropertyAccessExpression */:
+ case 229 /* NonNullExpression */:
+ case 348 /* PartiallyEmittedExpression */:
+ node = node.expression;
+ continue;
+ }
+ return node;
+ }
+ }
+ ts.getLeftmostExpression = getLeftmostExpression;
+ function Symbol(flags, name) {
+ this.flags = flags;
+ this.escapedName = name;
+ this.declarations = undefined;
+ this.valueDeclaration = undefined;
+ this.id = undefined;
+ this.mergeId = undefined;
+ this.parent = undefined;
+ }
+ function Type(checker, flags) {
+ this.flags = flags;
+ if (ts.Debug.isDebugging || ts.tracing) {
+ this.checker = checker;
+ }
+ }
+ function Signature(checker, flags) {
+ this.flags = flags;
+ if (ts.Debug.isDebugging) {
+ this.checker = checker;
+ }
+ }
+ function Node(kind, pos, end) {
+ this.pos = pos;
+ this.end = end;
+ this.kind = kind;
+ this.id = 0;
+ this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
+ this.parent = undefined;
+ this.original = undefined;
+ }
+ function Token(kind, pos, end) {
+ this.pos = pos;
+ this.end = end;
+ this.kind = kind;
+ this.id = 0;
+ this.flags = 0 /* None */;
+ this.transformFlags = 0 /* None */;
+ this.parent = undefined;
+ }
+ function Identifier(kind, pos, end) {
+ this.pos = pos;
+ this.end = end;
+ this.kind = kind;
+ this.id = 0;
+ this.flags = 0 /* None */;
+ this.transformFlags = 0 /* None */;
+ this.parent = undefined;
+ this.original = undefined;
+ this.flowNode = undefined;
+ }
+ function SourceMapSource(fileName, text, skipTrivia) {
+ this.fileName = fileName;
+ this.text = text;
+ this.skipTrivia = skipTrivia || (function (pos) { return pos; });
+ }
+ // eslint-disable-next-line prefer-const
+ ts.objectAllocator = {
+ getNodeConstructor: function () { return Node; },
+ getTokenConstructor: function () { return Token; },
+ getIdentifierConstructor: function () { return Identifier; },
+ getPrivateIdentifierConstructor: function () { return Node; },
+ getSourceFileConstructor: function () { return Node; },
+ getSymbolConstructor: function () { return Symbol; },
+ getTypeConstructor: function () { return Type; },
+ getSignatureConstructor: function () { return Signature; },
+ getSourceMapSourceConstructor: function () { return SourceMapSource; },
+ };
+ function setObjectAllocator(alloc) {
+ ts.objectAllocator = alloc;
+ }
+ ts.setObjectAllocator = setObjectAllocator;
+ function formatStringFromArgs(text, args, baseIndex) {
+ if (baseIndex === void 0) { baseIndex = 0; }
+ return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
+ }
+ ts.formatStringFromArgs = formatStringFromArgs;
+ /* @internal */
+ function setLocalizedDiagnosticMessages(messages) {
+ ts.localizedDiagnosticMessages = messages;
+ }
+ ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
+ function getLocaleSpecificMessage(message) {
+ return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
+ }
+ ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
+ function createDetachedDiagnostic(fileName, start, length, message) {
+ assertDiagnosticLocation(/*file*/ undefined, start, length);
+ var text = getLocaleSpecificMessage(message);
+ if (arguments.length > 4) {
+ text = formatStringFromArgs(text, arguments, 4);
+ }
+ return {
+ file: undefined,
+ start: start,
+ length: length,
+ messageText: text,
+ category: message.category,
+ code: message.code,
+ reportsUnnecessary: message.reportsUnnecessary,
+ fileName: fileName,
+ };
+ }
+ ts.createDetachedDiagnostic = createDetachedDiagnostic;
+ function isDiagnosticWithDetachedLocation(diagnostic) {
+ return diagnostic.file === undefined
+ && diagnostic.start !== undefined
+ && diagnostic.length !== undefined
+ && typeof diagnostic.fileName === "string";
+ }
+ function attachFileToDiagnostic(diagnostic, file) {
+ var fileName = file.fileName || "";
+ var length = file.text.length;
+ ts.Debug.assertEqual(diagnostic.fileName, fileName);
+ ts.Debug.assertLessThanOrEqual(diagnostic.start, length);
+ ts.Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length);
+ var diagnosticWithLocation = {
+ file: file,
+ start: diagnostic.start,
+ length: diagnostic.length,
+ messageText: diagnostic.messageText,
+ category: diagnostic.category,
+ code: diagnostic.code,
+ reportsUnnecessary: diagnostic.reportsUnnecessary
+ };
+ if (diagnostic.relatedInformation) {
+ diagnosticWithLocation.relatedInformation = [];
+ for (var _i = 0, _a = diagnostic.relatedInformation; _i < _a.length; _i++) {
+ var related = _a[_i];
+ if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) {
+ ts.Debug.assertLessThanOrEqual(related.start, length);
+ ts.Debug.assertLessThanOrEqual(related.start + related.length, length);
+ diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file));
+ }
+ else {
+ diagnosticWithLocation.relatedInformation.push(related);
+ }
+ }
+ }
+ return diagnosticWithLocation;
+ }
+ function attachFileToDiagnostics(diagnostics, file) {
+ var diagnosticsWithLocation = [];
+ for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
+ var diagnostic = diagnostics_1[_i];
+ diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file));
+ }
+ return diagnosticsWithLocation;
+ }
+ ts.attachFileToDiagnostics = attachFileToDiagnostics;
+ function createFileDiagnostic(file, start, length, message) {
+ assertDiagnosticLocation(file, start, length);
+ var text = getLocaleSpecificMessage(message);
+ if (arguments.length > 4) {
+ text = formatStringFromArgs(text, arguments, 4);
+ }
+ return {
+ file: file,
+ start: start,
+ length: length,
+ messageText: text,
+ category: message.category,
+ code: message.code,
+ reportsUnnecessary: message.reportsUnnecessary,
+ reportsDeprecated: message.reportsDeprecated
+ };
+ }
+ ts.createFileDiagnostic = createFileDiagnostic;
+ function formatMessage(_dummy, message) {
+ var text = getLocaleSpecificMessage(message);
+ if (arguments.length > 2) {
+ text = formatStringFromArgs(text, arguments, 2);
+ }
+ return text;
+ }
+ ts.formatMessage = formatMessage;
+ function createCompilerDiagnostic(message) {
+ var text = getLocaleSpecificMessage(message);
+ if (arguments.length > 1) {
+ text = formatStringFromArgs(text, arguments, 1);
+ }
+ return {
+ file: undefined,
+ start: undefined,
+ length: undefined,
+ messageText: text,
+ category: message.category,
+ code: message.code,
+ reportsUnnecessary: message.reportsUnnecessary,
+ reportsDeprecated: message.reportsDeprecated
+ };
+ }
+ ts.createCompilerDiagnostic = createCompilerDiagnostic;
+ function createCompilerDiagnosticFromMessageChain(chain, relatedInformation) {
+ return {
+ file: undefined,
+ start: undefined,
+ length: undefined,
+ code: chain.code,
+ category: chain.category,
+ messageText: chain.next ? chain : chain.messageText,
+ relatedInformation: relatedInformation
+ };
+ }
+ ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
+ function chainDiagnosticMessages(details, message) {
+ var text = getLocaleSpecificMessage(message);
+ if (arguments.length > 2) {
+ text = formatStringFromArgs(text, arguments, 2);
+ }
+ return {
+ messageText: text,
+ category: message.category,
+ code: message.code,
+ next: details === undefined || Array.isArray(details) ? details : [details]
+ };
+ }
+ ts.chainDiagnosticMessages = chainDiagnosticMessages;
+ function concatenateDiagnosticMessageChains(headChain, tailChain) {
+ var lastChain = headChain;
+ while (lastChain.next) {
+ lastChain = lastChain.next[0];
+ }
+ lastChain.next = [tailChain];
+ }
+ ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
+ }
+ function compareDiagnostics(d1, d2) {
+ return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
+ compareRelatedInformation(d1, d2) ||
+ 0 /* EqualTo */;
+ }
+ ts.compareDiagnostics = compareDiagnostics;
+ function compareDiagnosticsSkipRelatedInformation(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 /* EqualTo */;
+ }
+ ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
+ function compareRelatedInformation(d1, d2) {
+ if (!d1.relatedInformation && !d2.relatedInformation) {
+ return 0 /* EqualTo */;
+ }
+ if (d1.relatedInformation && d2.relatedInformation) {
+ return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
+ var d2i = d2.relatedInformation[index];
+ return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
+ }) || 0 /* EqualTo */;
+ }
+ return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
+ }
+ function compareMessageText(t1, t2) {
+ if (typeof t1 === "string" && typeof t2 === "string") {
+ return ts.compareStringsCaseSensitive(t1, t2);
+ }
+ else if (typeof t1 === "string") {
+ return -1 /* LessThan */;
+ }
+ else if (typeof t2 === "string") {
+ return 1 /* GreaterThan */;
+ }
+ var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
+ if (res) {
+ return res;
+ }
+ if (!t1.next && !t2.next) {
+ return 0 /* EqualTo */;
+ }
+ if (!t1.next) {
+ return -1 /* LessThan */;
+ }
+ if (!t2.next) {
+ return 1 /* GreaterThan */;
+ }
+ var len = Math.min(t1.next.length, t2.next.length);
+ for (var i = 0; i < len; i++) {
+ res = compareMessageText(t1.next[i], t2.next[i]);
+ if (res) {
+ return res;
+ }
+ }
+ if (t1.next.length < t2.next.length) {
+ return -1 /* LessThan */;
+ }
+ else if (t1.next.length > t2.next.length) {
+ return 1 /* GreaterThan */;
+ }
+ return 0 /* EqualTo */;
+ }
+ function getLanguageVariant(scriptKind) {
+ // .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 */;
+ }
+ ts.getLanguageVariant = getLanguageVariant;
+ function getEmitScriptTarget(compilerOptions) {
+ return compilerOptions.target ||
+ (compilerOptions.module === ts.ModuleKind.Node12 && 7 /* ES2020 */) ||
+ (compilerOptions.module === ts.ModuleKind.NodeNext && 99 /* ESNext */) ||
+ 0 /* ES3 */;
+ }
+ ts.getEmitScriptTarget = getEmitScriptTarget;
+ function getEmitModuleKind(compilerOptions) {
+ return typeof compilerOptions.module === "number" ?
+ compilerOptions.module :
+ getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
+ }
+ ts.getEmitModuleKind = getEmitModuleKind;
+ function getEmitModuleResolutionKind(compilerOptions) {
+ var moduleResolution = compilerOptions.moduleResolution;
+ if (moduleResolution === undefined) {
+ switch (getEmitModuleKind(compilerOptions)) {
+ case ts.ModuleKind.CommonJS:
+ moduleResolution = ts.ModuleResolutionKind.NodeJs;
+ break;
+ case ts.ModuleKind.Node12:
+ moduleResolution = ts.ModuleResolutionKind.Node12;
+ break;
+ case ts.ModuleKind.NodeNext:
+ moduleResolution = ts.ModuleResolutionKind.NodeNext;
+ break;
+ default:
+ moduleResolution = ts.ModuleResolutionKind.Classic;
+ break;
+ }
+ }
+ return moduleResolution;
+ }
+ ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
+ function hasJsonModuleEmitEnabled(options) {
+ switch (getEmitModuleKind(options)) {
+ case ts.ModuleKind.CommonJS:
+ case ts.ModuleKind.AMD:
+ case ts.ModuleKind.ES2015:
+ case ts.ModuleKind.ES2020:
+ case ts.ModuleKind.ES2022:
+ case ts.ModuleKind.ESNext:
+ case ts.ModuleKind.Node12:
+ case ts.ModuleKind.NodeNext:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
+ function unreachableCodeIsError(options) {
+ return options.allowUnreachableCode === false;
+ }
+ ts.unreachableCodeIsError = unreachableCodeIsError;
+ function unusedLabelIsError(options) {
+ return options.allowUnusedLabels === false;
+ }
+ ts.unusedLabelIsError = unusedLabelIsError;
+ function getAreDeclarationMapsEnabled(options) {
+ return !!(getEmitDeclarations(options) && options.declarationMap);
+ }
+ ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
+ function getESModuleInterop(compilerOptions) {
+ if (compilerOptions.esModuleInterop !== undefined) {
+ return compilerOptions.esModuleInterop;
+ }
+ switch (getEmitModuleKind(compilerOptions)) {
+ case ts.ModuleKind.Node12:
+ case ts.ModuleKind.NodeNext:
+ return true;
+ }
+ return undefined;
+ }
+ ts.getESModuleInterop = getESModuleInterop;
+ function getAllowSyntheticDefaultImports(compilerOptions) {
+ var moduleKind = getEmitModuleKind(compilerOptions);
+ return compilerOptions.allowSyntheticDefaultImports !== undefined
+ ? compilerOptions.allowSyntheticDefaultImports
+ : getESModuleInterop(compilerOptions) ||
+ moduleKind === ts.ModuleKind.System;
+ }
+ ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
+ function shouldPreserveConstEnums(compilerOptions) {
+ return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);
+ }
+ ts.shouldPreserveConstEnums = shouldPreserveConstEnums;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
+ function getStrictOptionValue(compilerOptions, flag) {
+ return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
+ }
+ ts.getStrictOptionValue = getStrictOptionValue;
+ function getAllowJSCompilerOption(compilerOptions) {
+ return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs;
+ }
+ ts.getAllowJSCompilerOption = getAllowJSCompilerOption;
+ function getUseDefineForClassFields(compilerOptions) {
+ return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ : compilerOptions.useDefineForClassFields;
+ }
+ ts.getUseDefineForClassFields = getUseDefineForClassFields;
+ function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
+ return optionsHaveChanges(oldOptions, newOptions, ts.semanticDiagnosticsOptionDeclarations);
+ }
+ ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
+ function compilerOptionsAffectEmit(newOptions, oldOptions) {
+ return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations);
+ }
+ ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
+ function getCompilerOptionValue(options, option) {
+ return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
+ }
+ ts.getCompilerOptionValue = getCompilerOptionValue;
+ function getJSXTransformEnabled(options) {
+ var jsx = options.jsx;
+ return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */;
+ }
+ ts.getJSXTransformEnabled = getJSXTransformEnabled;
+ function getJSXImplicitImportBase(compilerOptions, file) {
+ var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource");
+ var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas;
+ return compilerOptions.jsx === 4 /* ReactJSX */ ||
+ compilerOptions.jsx === 5 /* ReactJSXDev */ ||
+ compilerOptions.jsxImportSource ||
+ jsxImportSourcePragma ?
+ (jsxImportSourcePragma === null || jsxImportSourcePragma === void 0 ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" :
+ undefined;
+ }
+ ts.getJSXImplicitImportBase = getJSXImplicitImportBase;
+ function getJSXRuntimeImport(base, options) {
+ return base ? "".concat(base, "/").concat(options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined;
+ }
+ ts.getJSXRuntimeImport = getJSXRuntimeImport;
+ function hasZeroOrOneAsteriskCharacter(str) {
+ var seenAsterisk = false;
+ for (var i = 0; i < str.length; i++) {
+ if (str.charCodeAt(i) === 42 /* asterisk */) {
+ if (!seenAsterisk) {
+ seenAsterisk = true;
+ }
+ else {
+ // have already seen asterisk
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ function createSymlinkCache(cwd, getCanonicalFileName) {
+ var symlinkedDirectories;
+ var symlinkedDirectoriesByRealpath;
+ var symlinkedFiles;
+ var hasProcessedResolutions = false;
+ return {
+ getSymlinkedFiles: function () { return symlinkedFiles; },
+ getSymlinkedDirectories: function () { return symlinkedDirectories; },
+ getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; },
+ setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
+ setSymlinkedDirectory: function (symlink, real) {
+ // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks
+ // where both the realpath and the symlink path are inside node_modules/.pnpm. Since
+ // this path is never a candidate for a module specifier, we can ignore it entirely.
+ var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName);
+ if (!containsIgnoredPath(symlinkPath)) {
+ symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath);
+ if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) {
+ (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink);
+ }
+ (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real);
+ }
},
- description: ts.Diagnostics.List_of_language_service_plugins
- },
- ]);
+ setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) {
+ this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real);
+ var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1];
+ if (commonResolved && commonOriginal) {
+ this.setSymlinkedDirectory(commonOriginal, {
+ real: commonResolved,
+ realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName),
+ });
+ }
+ },
+ setSymlinksFromResolutions: function (files, typeReferenceDirectives) {
+ var _this = this;
+ var _a;
+ ts.Debug.assert(!hasProcessedResolutions);
+ hasProcessedResolutions = true;
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var file = files_1[_i];
+ (_a = file.resolvedModules) === null || _a === void 0 ? void 0 : _a.forEach(function (resolution) { return processResolution(_this, resolution); });
+ }
+ typeReferenceDirectives === null || typeReferenceDirectives === void 0 ? void 0 : typeReferenceDirectives.forEach(function (resolution) { return processResolution(_this, resolution); });
+ },
+ hasProcessedResolutions: function () { return hasProcessedResolutions; },
+ };
+ function processResolution(cache, resolution) {
+ if (!resolution || !resolution.originalPath || !resolution.resolvedFileName)
+ return;
+ var resolvedFileName = resolution.resolvedFileName, originalPath = resolution.originalPath;
+ cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedFileName);
+ var _a = guessDirectorySymlink(resolvedFileName, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1];
+ if (commonResolved && commonOriginal) {
+ cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
+ }
+ }
+ }
+ ts.createSymlinkCache = createSymlinkCache;
+ function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
+ var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd));
+ var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd));
+ var isDirectory = false;
+ while (aParts.length >= 2 && bParts.length >= 2 &&
+ !isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
+ !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
+ getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
+ aParts.pop();
+ bParts.pop();
+ isDirectory = true;
+ }
+ return isDirectory ? [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)] : undefined;
+ }
+ // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
+ // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
+ function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
+ return s !== undefined && (getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"));
+ }
+ function stripLeadingDirectorySeparator(s) {
+ return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
+ }
+ function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
+ var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
+ return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
+ }
+ 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;
+ function regExpEscape(text) {
+ return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
+ }
+ ts.regExpEscape = regExpEscape;
+ function escapeRegExpCharacter(match) {
+ return "\\" + match;
+ }
+ var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
+ ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
+ var implicitExcludePathRegexPattern = "(?!(".concat(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: "(/".concat(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: "(/".concat(implicitExcludePathRegexPattern, "[^/.][^/]*)*?"),
+ replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
+ };
+ var excludeMatcher = {
+ singleAsteriskRegexFragment: "[^/]*",
+ doubleAsteriskRegexFragment: "(/.+?)?",
+ replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
+ };
+ var wildcardMatchers = {
+ files: filesMatcher,
+ directories: directoriesMatcher,
+ exclude: excludeMatcher
+ };
+ function getRegularExpressionForWildcard(specs, basePath, usage) {
+ var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
+ if (!patterns || !patterns.length) {
+ return undefined;
+ }
+ var pattern = patterns.map(function (pattern) { return "(".concat(pattern, ")"); }).join("|");
+ // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
+ var terminator = usage === "exclude" ? "($|/)" : "$";
+ return "^(".concat(pattern, ")").concat(terminator);
+ }
+ ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
+ function getRegularExpressionsForWildcards(specs, basePath, usage) {
+ if (specs === undefined || specs.length === 0) {
+ return undefined;
+ }
+ return ts.flatMap(specs, function (spec) {
+ return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
+ });
+ }
+ ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
+ /**
+ * 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);
+ }
+ ts.isImplicitGlob = isImplicitGlob;
+ function getPatternFromSpec(spec, basePath, usage) {
+ var pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
+ return pattern && "^(".concat(pattern, ")").concat(usage === "exclude" ? "($|/)" : "$");
+ }
+ ts.getPatternFromSpec = getPatternFromSpec;
+ function getSubPatternFromSpec(spec, basePath, usage, _a) {
+ var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
+ var subpattern = "";
+ var hasWrittenComponent = false;
+ var components = ts.getNormalizedPathComponents(spec, basePath);
+ var lastComponent = ts.last(components);
+ 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] = ts.removeTrailingDirectorySeparator(components[0]);
+ if (isImplicitGlob(lastComponent)) {
+ components.push("**", "*");
+ }
+ var optionalCount = 0;
+ for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
+ var component = components_1[_i];
+ if (component === "**") {
+ subpattern += doubleAsteriskRegexFragment;
+ }
+ else {
+ if (usage === "directories") {
+ subpattern += "(";
+ optionalCount++;
+ }
+ if (hasWrittenComponent) {
+ subpattern += ts.directorySeparator;
+ }
+ if (usage !== "exclude") {
+ var componentPattern = "";
+ // 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 /* 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;
+ }
+ subpattern += componentPattern;
+ }
+ else {
+ subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
+ }
+ }
+ hasWrittenComponent = true;
+ }
+ while (optionalCount > 0) {
+ subpattern += ")?";
+ optionalCount--;
+ }
+ return subpattern;
+ }
+ 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);
+ var absolutePath = ts.combinePaths(currentDirectory, path);
+ return {
+ includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^".concat(pattern, "$"); }),
+ includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
+ includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
+ excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
+ basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
+ };
+ }
+ ts.getFileMatcherPatterns = getFileMatcherPatterns;
+ function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
+ 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, realpath) {
+ path = ts.normalizePath(path);
+ currentDirectory = ts.normalizePath(currentDirectory);
+ var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
+ 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 []; }) : [[]];
+ var visited = new ts.Map();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
+ for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
+ var basePath = _a[_i];
+ visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
+ }
+ return ts.flatten(results);
+ function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
+ var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
+ var _loop_1 = function (current) {
+ var name = ts.combinePaths(path, current);
+ var absoluteName = ts.combinePaths(absolutePath, current);
+ if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
+ return "continue";
+ if (excludeRegex && excludeRegex.test(absoluteName))
+ return "continue";
+ if (!includeFileRegexes) {
+ results[0].push(name);
+ }
+ else {
+ var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
+ if (includeIndex !== -1) {
+ results[includeIndex].push(name);
+ }
+ }
+ };
+ for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
+ var current = _b[_i];
+ _loop_1(current);
+ }
+ if (depth !== undefined) {
+ depth--;
+ if (depth === 0) {
+ return;
+ }
+ }
+ for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
+ var current = _d[_c];
+ var name = ts.combinePaths(path, current);
+ var absoluteName = ts.combinePaths(absolutePath, current);
+ if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
+ (!excludeRegex || !excludeRegex.test(absoluteName))) {
+ visitDirectory(name, absoluteName, depth);
+ }
+ }
+ }
+ }
+ 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(ts.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 !ts.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);
+ }
+ }
+ return basePaths;
+ }
+ function getIncludeBasePath(absolute) {
+ var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
+ if (wildcardOffset < 0) {
+ // No "*" or "?" in the path
+ return !ts.hasExtension(absolute)
+ ? absolute
+ : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
+ }
+ return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
+ }
+ function ensureScriptKind(fileName, scriptKind) {
+ // 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" /* Js */:
+ case ".cjs" /* Cjs */:
+ case ".mjs" /* Mjs */:
+ return 1 /* JS */;
+ case ".jsx" /* Jsx */:
+ return 2 /* JSX */;
+ case ".ts" /* Ts */:
+ case ".cts" /* Cts */:
+ case ".mts" /* Mts */:
+ return 3 /* TS */;
+ case ".tsx" /* Tsx */:
+ return 4 /* TSX */;
+ case ".json" /* Json */:
+ return 6 /* JSON */;
+ default:
+ return 0 /* Unknown */;
+ }
+ }
+ ts.getScriptKindFromFileName = getScriptKindFromFileName;
+ /**
+ * Groups of supported extensions in order of file resolution precedence. (eg, TS > TSX > DTS and seperately, CTS > DCTS)
+ */
+ ts.supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]];
+ ts.supportedTSExtensionsFlat = ts.flatten(ts.supportedTSExtensions);
+ var supportedTSExtensionsWithJson = __spreadArray(__spreadArray([], ts.supportedTSExtensions, true), [[".json" /* Json */]], false);
+ /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
+ var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */];
+ ts.supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]];
+ ts.supportedJSExtensionsFlat = ts.flatten(ts.supportedJSExtensions);
+ var allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]];
+ var allSupportedExtensionsWithJson = __spreadArray(__spreadArray([], allSupportedExtensions, true), [[".json" /* Json */]], false);
+ function getSupportedExtensions(options, extraFileExtensions) {
+ var needJsExtensions = options && getAllowJSCompilerOption(options);
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
+ }
+ var builtins = needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
+ var flatBuiltins = ts.flatten(builtins);
+ var extensions = __spreadArray(__spreadArray([], builtins, true), ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension) === -1 ? [x.extension] : undefined; }), true);
+ return extensions;
+ }
+ ts.getSupportedExtensions = getSupportedExtensions;
+ function getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
+ if (!options || !options.resolveJsonModule)
+ return supportedExtensions;
+ if (supportedExtensions === allSupportedExtensions)
+ return allSupportedExtensionsWithJson;
+ if (supportedExtensions === ts.supportedTSExtensions)
+ return supportedTSExtensionsWithJson;
+ return __spreadArray(__spreadArray([], supportedExtensions, true), [[".json" /* Json */]], false);
+ }
+ ts.getSupportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule;
+ function isJSLike(scriptKind) {
+ return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
+ }
+ function hasJSFileExtension(fileName) {
+ return ts.some(ts.supportedJSExtensionsFlat, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasJSFileExtension = hasJSFileExtension;
+ function hasTSFileExtension(fileName) {
+ return ts.some(ts.supportedTSExtensionsFlat, function (extension) { return ts.fileExtensionIs(fileName, extension); });
+ }
+ ts.hasTSFileExtension = hasTSFileExtension;
+ function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
+ if (!fileName)
+ return false;
+ var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
+ for (var _i = 0, _a = ts.flatten(getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)); _i < _a.length; _i++) {
+ var extension = _a[_i];
+ if (ts.fileExtensionIs(fileName, extension)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ ts.isSupportedSourceFileName = isSupportedSourceFileName;
+ function numberOfDirectorySeparators(str) {
+ var match = str.match(/\//g);
+ return match ? match.length : 0;
+ }
+ function compareNumberOfDirectorySeparators(path1, path2) {
+ return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2));
+ }
+ ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators;
+ var extensionsToRemove = [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".mjs" /* Mjs */, ".mts" /* Mts */, ".cjs" /* Cjs */, ".cts" /* Cts */, ".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];
+ var extensionless = tryRemoveExtension(path, ext);
+ if (extensionless !== undefined) {
+ return extensionless;
+ }
+ }
+ return path;
+ }
+ ts.removeFileExtension = removeFileExtension;
+ function tryRemoveExtension(path, extension) {
+ return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
+ }
+ ts.tryRemoveExtension = tryRemoveExtension;
+ function removeExtension(path, extension) {
+ return path.substring(0, path.length - extension.length);
+ }
+ ts.removeExtension = removeExtension;
+ function changeExtension(path, newExtension) {
+ return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
+ }
+ ts.changeExtension = changeExtension;
+ /**
+ * Returns the input if there are no stars, a pattern if there is exactly one,
+ * and undefined if there are more.
+ */
+ function tryParsePattern(pattern) {
+ var indexOfStar = pattern.indexOf("*");
+ if (indexOfStar === -1) {
+ return pattern;
+ }
+ return pattern.indexOf("*", indexOfStar + 1) !== -1
+ ? undefined
+ : {
+ prefix: pattern.substr(0, indexOfStar),
+ suffix: pattern.substr(indexOfStar + 1)
+ };
+ }
+ ts.tryParsePattern = tryParsePattern;
+ function tryParsePatterns(paths) {
+ return ts.mapDefined(ts.getOwnKeys(paths), function (path) { return tryParsePattern(path); });
+ }
+ ts.tryParsePatterns = tryParsePatterns;
+ 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 extensionIsTS(ext) {
+ return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */ || ext === ".cts" /* Cts */ || ext === ".mts" /* Mts */ || ext === ".d.mts" /* Dmts */ || ext === ".d.cts" /* Dcts */;
+ }
+ ts.extensionIsTS = extensionIsTS;
+ function resolutionExtensionIsTSOrJson(ext) {
+ return extensionIsTS(ext) || ext === ".json" /* Json */;
+ }
+ ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
+ /**
+ * Gets the extension from a path.
+ * Path must have a valid extension.
+ */
+ function extensionFromPath(path) {
+ var ext = tryGetExtensionFromPath(path);
+ return ext !== undefined ? ext : ts.Debug.fail("File ".concat(path, " has unknown extension."));
+ }
+ ts.extensionFromPath = extensionFromPath;
+ function isAnySupportedFileExtension(path) {
+ return tryGetExtensionFromPath(path) !== undefined;
+ }
+ ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
+ function tryGetExtensionFromPath(path) {
+ return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
+ }
+ ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
+ function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
+ return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
+ }
+ ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
+ ts.emptyFileSystemEntries = {
+ files: ts.emptyArray,
+ directories: ts.emptyArray
+ };
+ /**
+ * patternOrStrings contains both patterns (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(patternOrStrings, candidate) {
+ var patterns = [];
+ for (var _i = 0, patternOrStrings_1 = patternOrStrings; _i < patternOrStrings_1.length; _i++) {
+ var patternOrString = patternOrStrings_1[_i];
+ if (patternOrString === candidate) {
+ return candidate;
+ }
+ if (!ts.isString(patternOrString)) {
+ patterns.push(patternOrString);
+ }
+ }
+ return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
+ }
+ ts.matchPatternOrExact = matchPatternOrExact;
+ function sliceAfter(arr, value) {
+ var index = arr.indexOf(value);
+ ts.Debug.assert(index !== -1);
+ return arr.slice(index);
+ }
+ ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!relatedInformation.length) {
+ return diagnostic;
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ ts.Debug.assert(diagnostic.relatedInformation !== ts.emptyArray, "Diagnostic had empty array singleton for related info, but is still being constructed!");
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
+ function minAndMax(arr, getValue) {
+ ts.Debug.assert(arr.length !== 0);
+ var min = getValue(arr[0]);
+ var max = min;
+ for (var i = 1; i < arr.length; i++) {
+ var value = getValue(arr[i]);
+ if (value < min) {
+ min = value;
+ }
+ else if (value > max) {
+ max = value;
+ }
+ }
+ return { min: min, max: max };
+ }
+ ts.minAndMax = minAndMax;
+ function rangeOfNode(node) {
+ return { pos: getTokenPosOfNode(node), end: node.end };
+ }
+ ts.rangeOfNode = rangeOfNode;
+ function rangeOfTypeParameters(sourceFile, typeParameters) {
+ // Include the `<>`
+ var pos = typeParameters.pos - 1;
+ var end = ts.skipTrivia(sourceFile.text, typeParameters.end) + 1;
+ return { pos: pos, end: end };
+ }
+ ts.rangeOfTypeParameters = rangeOfTypeParameters;
+ function skipTypeChecking(sourceFile, options, host) {
+ // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
+ // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
+ // '/// ' directive.
+ return (options.skipLibCheck && sourceFile.isDeclarationFile ||
+ options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
+ host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
+ }
+ ts.skipTypeChecking = skipTypeChecking;
+ function isJsonEqual(a, b) {
+ // eslint-disable-next-line no-null/no-null
+ return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
+ }
+ ts.isJsonEqual = isJsonEqual;
+ /**
+ * Converts a bigint literal string, e.g. `0x1234n`,
+ * to its decimal string representation, e.g. `4660`.
+ */
+ function parsePseudoBigInt(stringValue) {
+ var log2Base;
+ switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
+ case 98 /* b */:
+ case 66 /* B */: // 0b or 0B
+ log2Base = 1;
+ break;
+ case 111 /* o */:
+ case 79 /* O */: // 0o or 0O
+ log2Base = 3;
+ break;
+ case 120 /* x */:
+ case 88 /* X */: // 0x or 0X
+ log2Base = 4;
+ break;
+ default: // already in decimal; omit trailing "n"
+ var nIndex = stringValue.length - 1;
+ // Skip leading 0s
+ var nonZeroStart = 0;
+ while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
+ nonZeroStart++;
+ }
+ return stringValue.slice(nonZeroStart, nIndex) || "0";
+ }
+ // Omit leading "0b", "0o", or "0x", and trailing "n"
+ var startIndex = 2, endIndex = stringValue.length - 1;
+ var bitsNeeded = (endIndex - startIndex) * log2Base;
+ // Stores the value specified by the string as a LE array of 16-bit integers
+ // using Uint16 instead of Uint32 so combining steps can use bitwise operators
+ var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
+ // Add the digits, one at a time
+ for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
+ var segment = bitOffset >>> 4;
+ var digitChar = stringValue.charCodeAt(i);
+ // Find character range: 0-9 < A-F < a-f
+ var digit = digitChar <= 57 /* _9 */
+ ? digitChar - 48 /* _0 */
+ : 10 + digitChar -
+ (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
+ var shiftedDigit = digit << (bitOffset & 15);
+ segments[segment] |= shiftedDigit;
+ var residual = shiftedDigit >>> 16;
+ if (residual)
+ segments[segment + 1] |= residual; // overflows segment
+ }
+ // Repeatedly divide segments by 10 and add remainder to base10Value
+ var base10Value = "";
+ var firstNonzeroSegment = segments.length - 1;
+ var segmentsRemaining = true;
+ while (segmentsRemaining) {
+ var mod10 = 0;
+ segmentsRemaining = false;
+ for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
+ var newSegment = mod10 << 16 | segments[segment];
+ var segmentValue = (newSegment / 10) | 0;
+ segments[segment] = segmentValue;
+ mod10 = newSegment - segmentValue * 10;
+ if (segmentValue && !segmentsRemaining) {
+ firstNonzeroSegment = segment;
+ segmentsRemaining = true;
+ }
+ }
+ base10Value = mod10 + base10Value;
+ }
+ return base10Value;
+ }
+ ts.parsePseudoBigInt = parsePseudoBigInt;
+ function pseudoBigIntToString(_a) {
+ var negative = _a.negative, base10Value = _a.base10Value;
+ return (negative && base10Value !== "0" ? "-" : "") + base10Value;
+ }
+ ts.pseudoBigIntToString = pseudoBigIntToString;
+ function isValidTypeOnlyAliasUseSite(useSite) {
+ return !!(useSite.flags & 8388608 /* Ambient */)
+ || isPartOfTypeQuery(useSite)
+ || isIdentifierInNonEmittingHeritageClause(useSite)
+ || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
+ || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite));
+ }
+ ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
+ function isShorthandPropertyNameUseSite(useSite) {
+ return ts.isIdentifier(useSite) && ts.isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite;
+ }
+ function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
+ while (node.kind === 79 /* Identifier */ || node.kind === 205 /* PropertyAccessExpression */) {
+ node = node.parent;
+ }
+ if (node.kind !== 161 /* ComputedPropertyName */) {
+ return false;
+ }
+ if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) {
+ return true;
+ }
+ var containerKind = node.parent.parent.kind;
+ return containerKind === 257 /* InterfaceDeclaration */ || containerKind === 181 /* TypeLiteral */;
+ }
+ /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
+ function isIdentifierInNonEmittingHeritageClause(node) {
+ if (node.kind !== 79 /* Identifier */)
+ return false;
+ var heritageClause = ts.findAncestor(node.parent, function (parent) {
+ switch (parent.kind) {
+ case 290 /* HeritageClause */:
+ return true;
+ case 205 /* PropertyAccessExpression */:
+ case 227 /* ExpressionWithTypeArguments */:
+ return false;
+ default:
+ return "quit";
+ }
+ });
+ return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 117 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 257 /* InterfaceDeclaration */;
+ }
+ function isIdentifierTypeReference(node) {
+ return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
+ }
+ ts.isIdentifierTypeReference = isIdentifierTypeReference;
+ function arrayIsHomogeneous(array, comparer) {
+ if (comparer === void 0) { comparer = ts.equateValues; }
+ if (array.length < 2)
+ return true;
+ var first = array[0];
+ for (var i = 1, length_1 = array.length; i < length_1; i++) {
+ var target = array[i];
+ if (!comparer(first, target))
+ return false;
+ }
+ return true;
+ }
+ ts.arrayIsHomogeneous = arrayIsHomogeneous;
+ /**
+ * Bypasses immutability and directly sets the `pos` property of a `TextRange` or `Node`.
+ */
+ /* @internal */
+ function setTextRangePos(range, pos) {
+ range.pos = pos;
+ return range;
+ }
+ ts.setTextRangePos = setTextRangePos;
+ /**
+ * Bypasses immutability and directly sets the `end` property of a `TextRange` or `Node`.
+ */
+ /* @internal */
+ function setTextRangeEnd(range, end) {
+ range.end = end;
+ return range;
+ }
+ ts.setTextRangeEnd = setTextRangeEnd;
+ /**
+ * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node`.
+ */
+ /* @internal */
+ function setTextRangePosEnd(range, pos, end) {
+ return setTextRangeEnd(setTextRangePos(range, pos), end);
+ }
+ ts.setTextRangePosEnd = setTextRangePosEnd;
+ /**
+ * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node` from the
+ * provided position and width.
+ */
+ /* @internal */
+ function setTextRangePosWidth(range, pos, width) {
+ return setTextRangePosEnd(range, pos, pos + width);
+ }
+ ts.setTextRangePosWidth = setTextRangePosWidth;
+ function setNodeFlags(node, newFlags) {
+ if (node) {
+ node.flags = newFlags;
+ }
+ return node;
+ }
+ ts.setNodeFlags = setNodeFlags;
+ function setParent(child, parent) {
+ if (child && parent) {
+ child.parent = parent;
+ }
+ return child;
+ }
+ ts.setParent = setParent;
+ function setEachParent(children, parent) {
+ if (children) {
+ for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
+ var child = children_1[_i];
+ setParent(child, parent);
+ }
+ }
+ return children;
+ }
+ ts.setEachParent = setEachParent;
+ function setParentRecursive(rootNode, incremental) {
+ if (!rootNode)
+ return rootNode;
+ ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
+ return rootNode;
+ function bindParentToChildIgnoringJSDoc(child, parent) {
+ if (incremental && child.parent === parent) {
+ return "skip";
+ }
+ setParent(child, parent);
+ }
+ function bindJSDoc(child) {
+ if (ts.hasJSDocNodes(child)) {
+ for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
+ var doc = _a[_i];
+ bindParentToChildIgnoringJSDoc(doc, child);
+ ts.forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
+ }
+ }
+ }
+ function bindParentToChild(child, parent) {
+ return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
+ }
+ }
+ ts.setParentRecursive = setParentRecursive;
+ function isPackedElement(node) {
+ return !ts.isOmittedExpression(node);
+ }
+ /**
+ * Determines whether the provided node is an ArrayLiteralExpression that contains no missing elements.
+ */
+ function isPackedArrayLiteral(node) {
+ return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
+ }
+ ts.isPackedArrayLiteral = isPackedArrayLiteral;
+ /**
+ * Indicates whether the result of an `Expression` will be unused.
+ *
+ * NOTE: This requires a node with a valid `parent` pointer.
+ */
+ function expressionResultIsUnused(node) {
+ ts.Debug.assertIsDefined(node.parent);
+ while (true) {
+ var parent = node.parent;
+ // walk up parenthesized expressions, but keep a pointer to the top-most parenthesized expression
+ if (ts.isParenthesizedExpression(parent)) {
+ node = parent;
+ continue;
+ }
+ // result is unused in an expression statement, `void` expression, or the initializer or incrementer of a `for` loop
+ if (ts.isExpressionStatement(parent) ||
+ ts.isVoidExpression(parent) ||
+ ts.isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) {
+ return true;
+ }
+ if (ts.isCommaListExpression(parent)) {
+ // left side of comma is always unused
+ if (node !== ts.last(parent.elements))
+ return true;
+ // right side of comma is unused if parent is unused
+ node = parent;
+ continue;
+ }
+ if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 27 /* CommaToken */) {
+ // left side of comma is always unused
+ if (node === parent.left)
+ return true;
+ // right side of comma is unused if parent is unused
+ node = parent;
+ continue;
+ }
+ return false;
+ }
+ }
+ ts.expressionResultIsUnused = expressionResultIsUnused;
+ function containsIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); });
+ }
+ ts.containsIgnoredPath = containsIgnoredPath;
+ function getContainingNodeArray(node) {
+ if (!node.parent)
+ return undefined;
+ switch (node.kind) {
+ case 162 /* TypeParameter */:
+ var parent_1 = node.parent;
+ return parent_1.kind === 189 /* InferType */ ? undefined : parent_1.typeParameters;
+ case 163 /* Parameter */:
+ return node.parent.parameters;
+ case 198 /* TemplateLiteralTypeSpan */:
+ return node.parent.templateSpans;
+ case 232 /* TemplateSpan */:
+ return node.parent.templateSpans;
+ case 164 /* Decorator */:
+ return node.parent.decorators;
+ case 290 /* HeritageClause */:
+ return node.parent.heritageClauses;
+ }
+ var parent = node.parent;
+ if (ts.isJSDocTag(node)) {
+ return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags;
+ }
+ switch (parent.kind) {
+ case 181 /* TypeLiteral */:
+ case 257 /* InterfaceDeclaration */:
+ return ts.isTypeElement(node) ? parent.members : undefined;
+ case 186 /* UnionType */:
+ case 187 /* IntersectionType */:
+ return parent.types;
+ case 183 /* TupleType */:
+ case 203 /* ArrayLiteralExpression */:
+ case 349 /* CommaListExpression */:
+ case 268 /* NamedImports */:
+ case 272 /* NamedExports */:
+ return parent.elements;
+ case 204 /* ObjectLiteralExpression */:
+ case 285 /* JsxAttributes */:
+ return parent.properties;
+ case 207 /* CallExpression */:
+ case 208 /* NewExpression */:
+ return ts.isTypeNode(node) ? parent.typeArguments :
+ parent.expression === node ? undefined :
+ parent.arguments;
+ case 277 /* JsxElement */:
+ case 281 /* JsxFragment */:
+ return ts.isJsxChild(node) ? parent.children : undefined;
+ case 279 /* JsxOpeningElement */:
+ case 278 /* JsxSelfClosingElement */:
+ return ts.isTypeNode(node) ? parent.typeArguments : undefined;
+ case 234 /* Block */:
+ case 288 /* CaseClause */:
+ case 289 /* DefaultClause */:
+ case 261 /* ModuleBlock */:
+ return parent.statements;
+ case 262 /* CaseBlock */:
+ return parent.clauses;
+ case 256 /* ClassDeclaration */:
+ case 225 /* ClassExpression */:
+ return ts.isClassElement(node) ? parent.members : undefined;
+ case 259 /* EnumDeclaration */:
+ return ts.isEnumMember(node) ? parent.members : undefined;
+ case 303 /* SourceFile */:
+ return parent.statements;
+ }
+ }
+ ts.getContainingNodeArray = getContainingNodeArray;
+ function hasContextSensitiveParameters(node) {
+ // Functions with type parameters are not context sensitive.
+ if (!node.typeParameters) {
+ // Functions with any parameters that lack type annotations are context sensitive.
+ if (ts.some(node.parameters, function (p) { return !getEffectiveTypeAnnotationNode(p); })) {
+ return true;
+ }
+ if (node.kind !== 213 /* ArrowFunction */) {
+ // If the first parameter is not an explicit 'this' parameter, then the function has
+ // an implicit 'this' parameter which is subject to contextual typing.
+ var parameter = ts.firstOrUndefined(node.parameters);
+ if (!(parameter && parameterIsThisKeyword(parameter))) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ ts.hasContextSensitiveParameters = hasContextSensitiveParameters;
+ /* @internal */
+ function isInfinityOrNaNString(name) {
+ return name === "Infinity" || name === "-Infinity" || name === "NaN";
+ }
+ ts.isInfinityOrNaNString = isInfinityOrNaNString;
+ function isCatchClauseVariableDeclaration(node) {
+ return node.kind === 253 /* VariableDeclaration */ && node.parent.kind === 291 /* CatchClause */;
+ }
+ ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration;
+ function isParameterOrCatchClauseVariable(symbol) {
+ var declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration);
+ return !!declaration && (ts.isParameter(declaration) || isCatchClauseVariableDeclaration(declaration));
+ }
+ ts.isParameterOrCatchClauseVariable = isParameterOrCatchClauseVariable;
+ function isFunctionExpressionOrArrowFunction(node) {
+ return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */;
+ }
+ ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction;
+ function escapeSnippetText(text) {
+ return text.replace(/\$/gm, "\\$");
+ }
+ ts.escapeSnippetText = escapeSnippetText;
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ /**
+ * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
+ */
+ function createBaseNodeFactory() {
+ // tslint:disable variable-name
+ var NodeConstructor;
+ var TokenConstructor;
+ var IdentifierConstructor;
+ var PrivateIdentifierConstructor;
+ var SourceFileConstructor;
+ // tslint:enable variable-name
+ return {
+ createBaseSourceFileNode: createBaseSourceFileNode,
+ createBaseIdentifierNode: createBaseIdentifierNode,
+ createBasePrivateIdentifierNode: createBasePrivateIdentifierNode,
+ createBaseTokenNode: createBaseTokenNode,
+ createBaseNode: createBaseNode
+ };
+ function createBaseSourceFileNode(kind) {
+ return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
+ }
+ function createBaseIdentifierNode(kind) {
+ return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
+ }
+ function createBasePrivateIdentifierNode(kind) {
+ return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
+ }
+ function createBaseTokenNode(kind) {
+ return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
+ }
+ function createBaseNode(kind) {
+ return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
+ }
+ }
+ ts.createBaseNodeFactory = createBaseNodeFactory;
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ function createParenthesizerRules(factory) {
+ var binaryLeftOperandParenthesizerCache;
+ var binaryRightOperandParenthesizerCache;
+ return {
+ getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator,
+ getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator,
+ parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary,
+ parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary,
+ parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName,
+ parenthesizeConditionOfConditionalExpression: parenthesizeConditionOfConditionalExpression,
+ parenthesizeBranchOfConditionalExpression: parenthesizeBranchOfConditionalExpression,
+ parenthesizeExpressionOfExportDefault: parenthesizeExpressionOfExportDefault,
+ parenthesizeExpressionOfNew: parenthesizeExpressionOfNew,
+ parenthesizeLeftSideOfAccess: parenthesizeLeftSideOfAccess,
+ parenthesizeOperandOfPostfixUnary: parenthesizeOperandOfPostfixUnary,
+ parenthesizeOperandOfPrefixUnary: parenthesizeOperandOfPrefixUnary,
+ parenthesizeExpressionsOfCommaDelimitedList: parenthesizeExpressionsOfCommaDelimitedList,
+ parenthesizeExpressionForDisallowedComma: parenthesizeExpressionForDisallowedComma,
+ parenthesizeExpressionOfExpressionStatement: parenthesizeExpressionOfExpressionStatement,
+ parenthesizeConciseBodyOfArrowFunction: parenthesizeConciseBodyOfArrowFunction,
+ parenthesizeMemberOfConditionalType: parenthesizeMemberOfConditionalType,
+ parenthesizeMemberOfElementType: parenthesizeMemberOfElementType,
+ parenthesizeElementTypeOfArrayType: parenthesizeElementTypeOfArrayType,
+ parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType,
+ parenthesizeTypeArguments: parenthesizeTypeArguments,
+ };
+ function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) {
+ binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map());
+ var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind);
+ if (!parenthesizerRule) {
+ parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); };
+ binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule);
+ }
+ return parenthesizerRule;
+ }
+ function getParenthesizeRightSideOfBinaryForOperator(operatorKind) {
+ binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map());
+ var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind);
+ if (!parenthesizerRule) {
+ parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); };
+ binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule);
+ }
+ return parenthesizerRule;
+ }
+ /**
+ * Determines whether the operand to a BinaryExpression needs to be parenthesized.
+ *
+ * @param binaryOperator The operator for the BinaryExpression.
+ * @param operand The operand for the BinaryExpression.
+ * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
+ * BinaryExpression.
+ */
+ function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
+ // If the operand has lower precedence, then it needs to be parenthesized to preserve the
+ // intent of the expression. For example, if the operand is `a + b` and the operator is
+ // `*`, then we need to parenthesize the operand to preserve the intended order of
+ // operations: `(a + b) * x`.
+ //
+ // If the operand has higher precedence, then it does not need to be parenthesized. For
+ // example, if the operand is `a * b` and the operator is `+`, then we do not need to
+ // parenthesize to preserve the intended order of operations: `a * b + x`.
+ //
+ // If the operand has the same precedence, then we need to check the associativity of
+ // the operator based on whether this is the left or right operand of the expression.
+ //
+ // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
+ // to preserve the intended order of operations: `x * (a / d)`
+ //
+ // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
+ // the intended order of operations: `(a ** b) ** c`
+ var binaryOperatorPrecedence = ts.getOperatorPrecedence(220 /* BinaryExpression */, binaryOperator);
+ var binaryOperatorAssociativity = ts.getOperatorAssociativity(220 /* BinaryExpression */, binaryOperator);
+ var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
+ if (!isLeftSideOfBinary && operand.kind === 213 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
+ // We need to parenthesize arrow functions on the right side to avoid it being
+ // parsed as parenthesized expression: `a && (() => {})`
+ return true;
+ }
+ var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
+ switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
+ case -1 /* LessThan */:
+ // If the operand is the right side of a right-associative binary operation
+ // and is a yield expression, then we do not need parentheses.
+ if (!isLeftSideOfBinary
+ && binaryOperatorAssociativity === 1 /* Right */
+ && operand.kind === 223 /* YieldExpression */) {
+ return false;
+ }
+ return true;
+ case 1 /* GreaterThan */:
+ return false;
+ case 0 /* EqualTo */:
+ if (isLeftSideOfBinary) {
+ // No need to parenthesize the left operand when the binary operator is
+ // left associative:
+ // (a*b)/x -> a*b/x
+ // (a**b)/x -> a**b/x
+ //
+ // Parentheses are needed for the left operand when the binary operator is
+ // right associative:
+ // (a/b)**x -> (a/b)**x
+ // (a**b)**x -> (a**b)**x
+ return binaryOperatorAssociativity === 1 /* Right */;
+ }
+ else {
+ if (ts.isBinaryExpression(emittedOperand)
+ && emittedOperand.operatorToken.kind === binaryOperator) {
+ // No need to parenthesize the right operand when the binary operator and
+ // operand are the same and one of the following:
+ // x*(a*b) => x*a*b
+ // x|(a|b) => x|a|b
+ // x&(a&b) => x&a&b
+ // x^(a^b) => x^a^b
+ if (operatorHasAssociativeProperty(binaryOperator)) {
+ return false;
+ }
+ // No need to parenthesize the right operand when the binary operator
+ // is plus (+) if both the left and right operands consist solely of either
+ // literals of the same kind or binary plus (+) expressions for literals of
+ // the same kind (recursively).
+ // "a"+(1+2) => "a"+(1+2)
+ // "a"+("b"+"c") => "a"+"b"+"c"
+ if (binaryOperator === 39 /* PlusToken */) {
+ var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
+ if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
+ return false;
+ }
+ }
+ }
+ // No need to parenthesize the right operand when the operand is right
+ // associative:
+ // x/(a**b) -> x/a**b
+ // x**(a**b) -> x**a**b
+ //
+ // Parentheses are needed for the right operand when the operand is left
+ // associative:
+ // x/(a*b) -> x/(a*b)
+ // x**(a/b) -> x**(a/b)
+ var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
+ return operandAssociativity === 0 /* Left */;
+ }
+ }
+ }
+ /**
+ * Determines whether a binary operator is mathematically associative.
+ *
+ * @param binaryOperator The binary operator.
+ */
+ function operatorHasAssociativeProperty(binaryOperator) {
+ // The following operators are associative in JavaScript:
+ // (a*b)*c -> a*(b*c) -> a*b*c
+ // (a|b)|c -> a|(b|c) -> a|b|c
+ // (a&b)&c -> a&(b&c) -> a&b&c
+ // (a^b)^c -> a^(b^c) -> a^b^c
+ //
+ // While addition is associative in mathematics, JavaScript's `+` is not
+ // guaranteed to be associative as it is overloaded with string concatenation.
+ return binaryOperator === 41 /* AsteriskToken */
+ || binaryOperator === 51 /* BarToken */
+ || binaryOperator === 50 /* AmpersandToken */
+ || binaryOperator === 52 /* CaretToken */;
+ }
+ /**
+ * This function determines whether an expression consists of a homogeneous set of
+ * literal expressions or binary plus expressions that all share the same literal kind.
+ * It is used to determine whether the right-hand operand of a binary plus expression can be
+ * emitted without parentheses.
+ */
+ function getLiteralKindOfBinaryPlusOperand(node) {
+ node = ts.skipPartiallyEmittedExpressions(node);
+ if (ts.isLiteralKind(node.kind)) {
+ return node.kind;
+ }
+ if (node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
+ if (node.cachedLiteralKind !== undefined) {
+ return node.cachedLiteralKind;
+ }
+ var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
+ var literalKind = ts.isLiteralKind(leftKind)
+ && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
+ ? leftKind
+ : 0 /* Unknown */;
+ node.cachedLiteralKind = literalKind;
+ return literalKind;
+ }
+ return 0 /* Unknown */;
+ }
+ /**
+ * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
+ * order of operations.
+ *
+ * @param binaryOperator The operator for the BinaryExpression.
+ * @param operand The operand for the BinaryExpression.
+ * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
+ * BinaryExpression.
+ */
+ function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
+ var skipped = ts.skipPartiallyEmittedExpressions(operand);
+ // If the resulting expression is already parenthesized, we do not need to do any further processing.
+ if (skipped.kind === 211 /* ParenthesizedExpression */) {
+ return operand;
+ }
+ return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
+ ? factory.createParenthesizedExpression(operand)
+ : operand;
+ }
+ function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
+ return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true);
+ }
+ function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
+ return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide);
+ }
+ function parenthesizeExpressionOfComputedPropertyName(expression) {
+ return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression;
+ }
+ function parenthesizeConditionOfConditionalExpression(condition) {
+ var conditionalPrecedence = ts.getOperatorPrecedence(221 /* ConditionalExpression */, 57 /* QuestionToken */);
+ var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
+ var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
+ if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
+ return factory.createParenthesizedExpression(condition);
+ }
+ return condition;
+ }
+ function parenthesizeBranchOfConditionalExpression(branch) {
+ // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
+ // so in case when comma expression is introduced as a part of previous transformations
+ // if should be wrapped in parens since comma operator has the lowest precedence
+ var emittedExpression = ts.skipPartiallyEmittedExpressions(branch);
+ return ts.isCommaSequence(emittedExpression)
+ ? factory.createParenthesizedExpression(branch)
+ : branch;
+ }
+ /**
+ * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
+ * has a lookahead restriction for `function`, `async function`, and `class`.
+ *
+ * Basically, that means we need to parenthesize in the following cases:
+ *
+ * - BinaryExpression of CommaToken
+ * - CommaList (synthetic list of multiple comma expressions)
+ * - FunctionExpression
+ * - ClassExpression
+ */
+ function parenthesizeExpressionOfExportDefault(expression) {
+ var check = ts.skipPartiallyEmittedExpressions(expression);
+ var needsParens = ts.isCommaSequence(check);
+ if (!needsParens) {
+ switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
+ case 225 /* ClassExpression */:
+ case 212 /* FunctionExpression */:
+ needsParens = true;
+ }
+ }
+ return needsParens ? factory.createParenthesizedExpression(expression) : expression;
+ }
+ /**
+ * Wraps an expression in parentheses if it is needed in order to use the expression
+ * as the expression of a `NewExpression` node.
+ */
+ function parenthesizeExpressionOfNew(expression) {
+ var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
+ switch (leftmostExpr.kind) {
+ case 207 /* CallExpression */:
+ return factory.createParenthesizedExpression(expression);
+ case 208 /* NewExpression */:
+ return !leftmostExpr.arguments
+ ? factory.createParenthesizedExpression(expression)
+ : expression; // TODO(rbuckton): Verify this assertion holds
+ }
+ return parenthesizeLeftSideOfAccess(expression);
+ }
+ /**
+ * Wraps an expression in parentheses if it is needed in order to use the expression for
+ * property or element access.
+ */
+ function parenthesizeLeftSideOfAccess(expression) {
+ // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
+ // to parenthesize the expression before a dot. The known exception is:
+ //
+ // NewExpression:
+ // new C.x -> not the same as (new C).x
+ //
+ var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
+ if (ts.isLeftHandSideExpression(emittedExpression)
+ && (emittedExpression.kind !== 208 /* NewExpression */ || emittedExpression.arguments)) {
+ // TODO(rbuckton): Verify whether this assertion holds.
+ return expression;
+ }
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
+ }
+ function parenthesizeOperandOfPostfixUnary(operand) {
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ return ts.isLeftHandSideExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
+ }
+ function parenthesizeOperandOfPrefixUnary(operand) {
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ return ts.isUnaryExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
+ }
+ function parenthesizeExpressionsOfCommaDelimitedList(elements) {
+ var result = ts.sameMap(elements, parenthesizeExpressionForDisallowedComma);
+ return ts.setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements);
+ }
+ function parenthesizeExpressionForDisallowedComma(expression) {
+ var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
+ var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
+ var commaPrecedence = ts.getOperatorPrecedence(220 /* BinaryExpression */, 27 /* CommaToken */);
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
+ }
+ function parenthesizeExpressionOfExpressionStatement(expression) {
+ var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
+ if (ts.isCallExpression(emittedExpression)) {
+ var callee = emittedExpression.expression;
+ var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
+ if (kind === 212 /* FunctionExpression */ || kind === 213 /* ArrowFunction */) {
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments);
+ return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
+ }
+ }
+ var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
+ if (leftmostExpressionKind === 204 /* ObjectLiteralExpression */ || leftmostExpressionKind === 212 /* FunctionExpression */) {
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
+ }
+ return expression;
+ }
+ function parenthesizeConciseBodyOfArrowFunction(body) {
+ if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 204 /* ObjectLiteralExpression */)) {
+ // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
+ return ts.setTextRange(factory.createParenthesizedExpression(body), body);
+ }
+ return body;
+ }
+ function parenthesizeMemberOfConditionalType(member) {
+ return member.kind === 188 /* ConditionalType */ ? factory.createParenthesizedType(member) : member;
+ }
+ function parenthesizeMemberOfElementType(member) {
+ switch (member.kind) {
+ case 186 /* UnionType */:
+ case 187 /* IntersectionType */:
+ case 178 /* FunctionType */:
+ case 179 /* ConstructorType */:
+ return factory.createParenthesizedType(member);
+ }
+ return parenthesizeMemberOfConditionalType(member);
+ }
+ function parenthesizeElementTypeOfArrayType(member) {
+ switch (member.kind) {
+ case 180 /* TypeQuery */:
+ case 192 /* TypeOperator */:
+ case 189 /* InferType */:
+ return factory.createParenthesizedType(member);
+ }
+ return parenthesizeMemberOfElementType(member);
+ }
+ function parenthesizeConstituentTypesOfUnionOrIntersectionType(members) {
+ return factory.createNodeArray(ts.sameMap(members, parenthesizeMemberOfElementType));
+ }
+ function parenthesizeOrdinalTypeArgument(node, i) {
+ return i === 0 && ts.isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node;
+ }
+ function parenthesizeTypeArguments(typeArguments) {
+ if (ts.some(typeArguments)) {
+ return factory.createNodeArray(ts.sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
+ }
+ }
+ }
+ ts.createParenthesizerRules = createParenthesizerRules;
+ ts.nullParenthesizerRules = {
+ getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; },
+ getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; },
+ parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; },
+ parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; },
+ parenthesizeExpressionOfComputedPropertyName: ts.identity,
+ parenthesizeConditionOfConditionalExpression: ts.identity,
+ parenthesizeBranchOfConditionalExpression: ts.identity,
+ parenthesizeExpressionOfExportDefault: ts.identity,
+ parenthesizeExpressionOfNew: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
+ parenthesizeLeftSideOfAccess: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
+ parenthesizeOperandOfPostfixUnary: function (operand) { return ts.cast(operand, ts.isLeftHandSideExpression); },
+ parenthesizeOperandOfPrefixUnary: function (operand) { return ts.cast(operand, ts.isUnaryExpression); },
+ parenthesizeExpressionsOfCommaDelimitedList: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
+ parenthesizeExpressionForDisallowedComma: ts.identity,
+ parenthesizeExpressionOfExpressionStatement: ts.identity,
+ parenthesizeConciseBodyOfArrowFunction: ts.identity,
+ parenthesizeMemberOfConditionalType: ts.identity,
+ parenthesizeMemberOfElementType: ts.identity,
+ parenthesizeElementTypeOfArrayType: ts.identity,
+ parenthesizeConstituentTypesOfUnionOrIntersectionType: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
+ parenthesizeTypeArguments: function (nodes) { return nodes && ts.cast(nodes, ts.isNodeArray); },
+ };
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ function createNodeConverters(factory) {
+ return {
+ convertToFunctionBlock: convertToFunctionBlock,
+ convertToFunctionExpression: convertToFunctionExpression,
+ convertToArrayAssignmentElement: convertToArrayAssignmentElement,
+ convertToObjectAssignmentElement: convertToObjectAssignmentElement,
+ convertToAssignmentPattern: convertToAssignmentPattern,
+ convertToObjectAssignmentPattern: convertToObjectAssignmentPattern,
+ convertToArrayAssignmentPattern: convertToArrayAssignmentPattern,
+ convertToAssignmentElementTarget: convertToAssignmentElementTarget,
+ };
+ function convertToFunctionBlock(node, multiLine) {
+ if (ts.isBlock(node))
+ return node;
+ var returnStatement = factory.createReturnStatement(node);
+ ts.setTextRange(returnStatement, node);
+ var body = factory.createBlock([returnStatement], multiLine);
+ ts.setTextRange(body, node);
+ return body;
+ }
+ function convertToFunctionExpression(node) {
+ if (!node.body)
+ return ts.Debug.fail("Cannot convert a FunctionDeclaration without a body");
+ var updated = factory.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
+ ts.setOriginalNode(updated, node);
+ ts.setTextRange(updated, node);
+ if (ts.getStartsOnNewLine(node)) {
+ ts.setStartsOnNewLine(updated, /*newLine*/ true);
+ }
+ return updated;
+ }
+ function convertToArrayAssignmentElement(element) {
+ if (ts.isBindingElement(element)) {
+ if (element.dotDotDotToken) {
+ ts.Debug.assertNode(element.name, ts.isIdentifier);
+ return ts.setOriginalNode(ts.setTextRange(factory.createSpreadElement(element.name), element), element);
+ }
+ var expression = convertToAssignmentElementTarget(element.name);
+ return element.initializer
+ ? ts.setOriginalNode(ts.setTextRange(factory.createAssignment(expression, element.initializer), element), element)
+ : expression;
+ }
+ return ts.cast(element, ts.isExpression);
+ }
+ function convertToObjectAssignmentElement(element) {
+ if (ts.isBindingElement(element)) {
+ if (element.dotDotDotToken) {
+ ts.Debug.assertNode(element.name, ts.isIdentifier);
+ return ts.setOriginalNode(ts.setTextRange(factory.createSpreadAssignment(element.name), element), element);
+ }
+ if (element.propertyName) {
+ var expression = convertToAssignmentElementTarget(element.name);
+ return ts.setOriginalNode(ts.setTextRange(factory.createPropertyAssignment(element.propertyName, element.initializer ? factory.createAssignment(expression, element.initializer) : expression), element), element);
+ }
+ ts.Debug.assertNode(element.name, ts.isIdentifier);
+ return ts.setOriginalNode(ts.setTextRange(factory.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
+ }
+ return ts.cast(element, ts.isObjectLiteralElementLike);
+ }
+ function convertToAssignmentPattern(node) {
+ switch (node.kind) {
+ case 201 /* ArrayBindingPattern */:
+ case 203 /* ArrayLiteralExpression */:
+ return convertToArrayAssignmentPattern(node);
+ case 200 /* ObjectBindingPattern */:
+ case 204 /* ObjectLiteralExpression */:
+ return convertToObjectAssignmentPattern(node);
+ }
+ }
+ function convertToObjectAssignmentPattern(node) {
+ if (ts.isObjectBindingPattern(node)) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createObjectLiteralExpression(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
+ }
+ return ts.cast(node, ts.isObjectLiteralExpression);
+ }
+ function convertToArrayAssignmentPattern(node) {
+ if (ts.isArrayBindingPattern(node)) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createArrayLiteralExpression(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
+ }
+ return ts.cast(node, ts.isArrayLiteralExpression);
+ }
+ function convertToAssignmentElementTarget(node) {
+ if (ts.isBindingPattern(node)) {
+ return convertToAssignmentPattern(node);
+ }
+ return ts.cast(node, ts.isExpression);
+ }
+ }
+ ts.createNodeConverters = createNodeConverters;
+ ts.nullNodeConverters = {
+ convertToFunctionBlock: ts.notImplemented,
+ convertToFunctionExpression: ts.notImplemented,
+ convertToArrayAssignmentElement: ts.notImplemented,
+ convertToObjectAssignmentElement: ts.notImplemented,
+ convertToAssignmentPattern: ts.notImplemented,
+ convertToObjectAssignmentPattern: ts.notImplemented,
+ convertToArrayAssignmentPattern: ts.notImplemented,
+ convertToAssignmentElementTarget: ts.notImplemented,
+ };
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ var nextAutoGenerateId = 0;
+ /* @internal */
+ var NodeFactoryFlags;
+ (function (NodeFactoryFlags) {
+ NodeFactoryFlags[NodeFactoryFlags["None"] = 0] = "None";
+ // Disables the parenthesizer rules for the factory.
+ NodeFactoryFlags[NodeFactoryFlags["NoParenthesizerRules"] = 1] = "NoParenthesizerRules";
+ // Disables the node converters for the factory.
+ NodeFactoryFlags[NodeFactoryFlags["NoNodeConverters"] = 2] = "NoNodeConverters";
+ // Ensures new `PropertyAccessExpression` nodes are created with the `NoIndentation` emit flag set.
+ NodeFactoryFlags[NodeFactoryFlags["NoIndentationOnFreshPropertyAccess"] = 4] = "NoIndentationOnFreshPropertyAccess";
+ // Do not set an `original` pointer when updating a node.
+ NodeFactoryFlags[NodeFactoryFlags["NoOriginalNode"] = 8] = "NoOriginalNode";
+ })(NodeFactoryFlags = ts.NodeFactoryFlags || (ts.NodeFactoryFlags = {}));
+ /**
+ * Creates a `NodeFactory` that can be used to create and update a syntax tree.
+ * @param flags Flags that control factory behavior.
+ * @param baseFactory A `BaseNodeFactory` used to create the base `Node` objects.
+ */
+ /* @internal */
+ function createNodeFactory(flags, baseFactory) {
+ var update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal;
+ // Lazily load the parenthesizer, node converters, and some factory methods until they are used.
+ var parenthesizerRules = ts.memoize(function () { return flags & 1 /* NoParenthesizerRules */ ? ts.nullParenthesizerRules : ts.createParenthesizerRules(factory); });
+ var converters = ts.memoize(function () { return flags & 2 /* NoNodeConverters */ ? ts.nullNodeConverters : ts.createNodeConverters(factory); });
+ // lazy initializaton of common operator factories
+ var getBinaryCreateFunction = ts.memoizeOne(function (operator) { return function (left, right) { return createBinaryExpression(left, operator, right); }; });
+ var getPrefixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPrefixUnaryExpression(operator, operand); }; });
+ var getPostfixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPostfixUnaryExpression(operand, operator); }; });
+ var getJSDocPrimaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function () { return createJSDocPrimaryTypeWorker(kind); }; });
+ var getJSDocUnaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function (type) { return createJSDocUnaryTypeWorker(kind, type); }; });
+ var getJSDocUnaryTypeUpdateFunction = ts.memoizeOne(function (kind) { return function (node, type) { return updateJSDocUnaryTypeWorker(kind, node, type); }; });
+ var getJSDocSimpleTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, comment) { return createJSDocSimpleTagWorker(kind, tagName, comment); }; });
+ var getJSDocSimpleTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, comment) { return updateJSDocSimpleTagWorker(kind, node, tagName, comment); }; });
+ var getJSDocTypeLikeTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, typeExpression, comment) { return createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment); }; });
+ var getJSDocTypeLikeTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, typeExpression, comment) { return updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment); }; });
+ var factory = {
+ get parenthesizer() { return parenthesizerRules(); },
+ get converters() { return converters(); },
+ createNodeArray: createNodeArray,
+ createNumericLiteral: createNumericLiteral,
+ createBigIntLiteral: createBigIntLiteral,
+ createStringLiteral: createStringLiteral,
+ createStringLiteralFromNode: createStringLiteralFromNode,
+ createRegularExpressionLiteral: createRegularExpressionLiteral,
+ createLiteralLikeNode: createLiteralLikeNode,
+ createIdentifier: createIdentifier,
+ updateIdentifier: updateIdentifier,
+ createTempVariable: createTempVariable,
+ createLoopVariable: createLoopVariable,
+ createUniqueName: createUniqueName,
+ getGeneratedNameForNode: getGeneratedNameForNode,
+ createPrivateIdentifier: createPrivateIdentifier,
+ createToken: createToken,
+ createSuper: createSuper,
+ createThis: createThis,
+ createNull: createNull,
+ createTrue: createTrue,
+ createFalse: createFalse,
+ createModifier: createModifier,
+ createModifiersFromModifierFlags: createModifiersFromModifierFlags,
+ createQualifiedName: createQualifiedName,
+ updateQualifiedName: updateQualifiedName,
+ createComputedPropertyName: createComputedPropertyName,
+ updateComputedPropertyName: updateComputedPropertyName,
+ createTypeParameterDeclaration: createTypeParameterDeclaration,
+ updateTypeParameterDeclaration: updateTypeParameterDeclaration,
+ createParameterDeclaration: createParameterDeclaration,
+ updateParameterDeclaration: updateParameterDeclaration,
+ createDecorator: createDecorator,
+ updateDecorator: updateDecorator,
+ createPropertySignature: createPropertySignature,
+ updatePropertySignature: updatePropertySignature,
+ createPropertyDeclaration: createPropertyDeclaration,
+ updatePropertyDeclaration: updatePropertyDeclaration,
+ createMethodSignature: createMethodSignature,
+ updateMethodSignature: updateMethodSignature,
+ createMethodDeclaration: createMethodDeclaration,
+ updateMethodDeclaration: updateMethodDeclaration,
+ createConstructorDeclaration: createConstructorDeclaration,
+ updateConstructorDeclaration: updateConstructorDeclaration,
+ createGetAccessorDeclaration: createGetAccessorDeclaration,
+ updateGetAccessorDeclaration: updateGetAccessorDeclaration,
+ createSetAccessorDeclaration: createSetAccessorDeclaration,
+ updateSetAccessorDeclaration: updateSetAccessorDeclaration,
+ createCallSignature: createCallSignature,
+ updateCallSignature: updateCallSignature,
+ createConstructSignature: createConstructSignature,
+ updateConstructSignature: updateConstructSignature,
+ createIndexSignature: createIndexSignature,
+ updateIndexSignature: updateIndexSignature,
+ createClassStaticBlockDeclaration: createClassStaticBlockDeclaration,
+ updateClassStaticBlockDeclaration: updateClassStaticBlockDeclaration,
+ createTemplateLiteralTypeSpan: createTemplateLiteralTypeSpan,
+ updateTemplateLiteralTypeSpan: updateTemplateLiteralTypeSpan,
+ createKeywordTypeNode: createKeywordTypeNode,
+ createTypePredicateNode: createTypePredicateNode,
+ updateTypePredicateNode: updateTypePredicateNode,
+ createTypeReferenceNode: createTypeReferenceNode,
+ updateTypeReferenceNode: updateTypeReferenceNode,
+ createFunctionTypeNode: createFunctionTypeNode,
+ updateFunctionTypeNode: updateFunctionTypeNode,
+ createConstructorTypeNode: createConstructorTypeNode,
+ updateConstructorTypeNode: updateConstructorTypeNode,
+ createTypeQueryNode: createTypeQueryNode,
+ updateTypeQueryNode: updateTypeQueryNode,
+ createTypeLiteralNode: createTypeLiteralNode,
+ updateTypeLiteralNode: updateTypeLiteralNode,
+ createArrayTypeNode: createArrayTypeNode,
+ updateArrayTypeNode: updateArrayTypeNode,
+ createTupleTypeNode: createTupleTypeNode,
+ updateTupleTypeNode: updateTupleTypeNode,
+ createNamedTupleMember: createNamedTupleMember,
+ updateNamedTupleMember: updateNamedTupleMember,
+ createOptionalTypeNode: createOptionalTypeNode,
+ updateOptionalTypeNode: updateOptionalTypeNode,
+ createRestTypeNode: createRestTypeNode,
+ updateRestTypeNode: updateRestTypeNode,
+ createUnionTypeNode: createUnionTypeNode,
+ updateUnionTypeNode: updateUnionTypeNode,
+ createIntersectionTypeNode: createIntersectionTypeNode,
+ updateIntersectionTypeNode: updateIntersectionTypeNode,
+ createConditionalTypeNode: createConditionalTypeNode,
+ updateConditionalTypeNode: updateConditionalTypeNode,
+ createInferTypeNode: createInferTypeNode,
+ updateInferTypeNode: updateInferTypeNode,
+ createImportTypeNode: createImportTypeNode,
+ updateImportTypeNode: updateImportTypeNode,
+ createParenthesizedType: createParenthesizedType,
+ updateParenthesizedType: updateParenthesizedType,
+ createThisTypeNode: createThisTypeNode,
+ createTypeOperatorNode: createTypeOperatorNode,
+ updateTypeOperatorNode: updateTypeOperatorNode,
+ createIndexedAccessTypeNode: createIndexedAccessTypeNode,
+ updateIndexedAccessTypeNode: updateIndexedAccessTypeNode,
+ createMappedTypeNode: createMappedTypeNode,
+ updateMappedTypeNode: updateMappedTypeNode,
+ createLiteralTypeNode: createLiteralTypeNode,
+ updateLiteralTypeNode: updateLiteralTypeNode,
+ createTemplateLiteralType: createTemplateLiteralType,
+ updateTemplateLiteralType: updateTemplateLiteralType,
+ createObjectBindingPattern: createObjectBindingPattern,
+ updateObjectBindingPattern: updateObjectBindingPattern,
+ createArrayBindingPattern: createArrayBindingPattern,
+ updateArrayBindingPattern: updateArrayBindingPattern,
+ createBindingElement: createBindingElement,
+ updateBindingElement: updateBindingElement,
+ createArrayLiteralExpression: createArrayLiteralExpression,
+ updateArrayLiteralExpression: updateArrayLiteralExpression,
+ createObjectLiteralExpression: createObjectLiteralExpression,
+ updateObjectLiteralExpression: updateObjectLiteralExpression,
+ createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
+ function (expression, name) { return ts.setEmitFlags(createPropertyAccessExpression(expression, name), 131072 /* NoIndentation */); } :
+ createPropertyAccessExpression,
+ updatePropertyAccessExpression: updatePropertyAccessExpression,
+ createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
+ function (expression, questionDotToken, name) { return ts.setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 131072 /* NoIndentation */); } :
+ createPropertyAccessChain,
+ updatePropertyAccessChain: updatePropertyAccessChain,
+ createElementAccessExpression: createElementAccessExpression,
+ updateElementAccessExpression: updateElementAccessExpression,
+ createElementAccessChain: createElementAccessChain,
+ updateElementAccessChain: updateElementAccessChain,
+ createCallExpression: createCallExpression,
+ updateCallExpression: updateCallExpression,
+ createCallChain: createCallChain,
+ updateCallChain: updateCallChain,
+ createNewExpression: createNewExpression,
+ updateNewExpression: updateNewExpression,
+ createTaggedTemplateExpression: createTaggedTemplateExpression,
+ updateTaggedTemplateExpression: updateTaggedTemplateExpression,
+ createTypeAssertion: createTypeAssertion,
+ updateTypeAssertion: updateTypeAssertion,
+ createParenthesizedExpression: createParenthesizedExpression,
+ updateParenthesizedExpression: updateParenthesizedExpression,
+ createFunctionExpression: createFunctionExpression,
+ updateFunctionExpression: updateFunctionExpression,
+ createArrowFunction: createArrowFunction,
+ updateArrowFunction: updateArrowFunction,
+ createDeleteExpression: createDeleteExpression,
+ updateDeleteExpression: updateDeleteExpression,
+ createTypeOfExpression: createTypeOfExpression,
+ updateTypeOfExpression: updateTypeOfExpression,
+ createVoidExpression: createVoidExpression,
+ updateVoidExpression: updateVoidExpression,
+ createAwaitExpression: createAwaitExpression,
+ updateAwaitExpression: updateAwaitExpression,
+ createPrefixUnaryExpression: createPrefixUnaryExpression,
+ updatePrefixUnaryExpression: updatePrefixUnaryExpression,
+ createPostfixUnaryExpression: createPostfixUnaryExpression,
+ updatePostfixUnaryExpression: updatePostfixUnaryExpression,
+ createBinaryExpression: createBinaryExpression,
+ updateBinaryExpression: updateBinaryExpression,
+ createConditionalExpression: createConditionalExpression,
+ updateConditionalExpression: updateConditionalExpression,
+ createTemplateExpression: createTemplateExpression,
+ updateTemplateExpression: updateTemplateExpression,
+ createTemplateHead: createTemplateHead,
+ createTemplateMiddle: createTemplateMiddle,
+ createTemplateTail: createTemplateTail,
+ createNoSubstitutionTemplateLiteral: createNoSubstitutionTemplateLiteral,
+ createTemplateLiteralLikeNode: createTemplateLiteralLikeNode,
+ createYieldExpression: createYieldExpression,
+ updateYieldExpression: updateYieldExpression,
+ createSpreadElement: createSpreadElement,
+ updateSpreadElement: updateSpreadElement,
+ createClassExpression: createClassExpression,
+ updateClassExpression: updateClassExpression,
+ createOmittedExpression: createOmittedExpression,
+ createExpressionWithTypeArguments: createExpressionWithTypeArguments,
+ updateExpressionWithTypeArguments: updateExpressionWithTypeArguments,
+ createAsExpression: createAsExpression,
+ updateAsExpression: updateAsExpression,
+ createNonNullExpression: createNonNullExpression,
+ updateNonNullExpression: updateNonNullExpression,
+ createNonNullChain: createNonNullChain,
+ updateNonNullChain: updateNonNullChain,
+ createMetaProperty: createMetaProperty,
+ updateMetaProperty: updateMetaProperty,
+ createTemplateSpan: createTemplateSpan,
+ updateTemplateSpan: updateTemplateSpan,
+ createSemicolonClassElement: createSemicolonClassElement,
+ createBlock: createBlock,
+ updateBlock: updateBlock,
+ createVariableStatement: createVariableStatement,
+ updateVariableStatement: updateVariableStatement,
+ createEmptyStatement: createEmptyStatement,
+ createExpressionStatement: createExpressionStatement,
+ updateExpressionStatement: updateExpressionStatement,
+ createIfStatement: createIfStatement,
+ updateIfStatement: updateIfStatement,
+ createDoStatement: createDoStatement,
+ updateDoStatement: updateDoStatement,
+ createWhileStatement: createWhileStatement,
+ updateWhileStatement: updateWhileStatement,
+ createForStatement: createForStatement,
+ updateForStatement: updateForStatement,
+ createForInStatement: createForInStatement,
+ updateForInStatement: updateForInStatement,
+ createForOfStatement: createForOfStatement,
+ updateForOfStatement: updateForOfStatement,
+ createContinueStatement: createContinueStatement,
+ updateContinueStatement: updateContinueStatement,
+ createBreakStatement: createBreakStatement,
+ updateBreakStatement: updateBreakStatement,
+ createReturnStatement: createReturnStatement,
+ updateReturnStatement: updateReturnStatement,
+ createWithStatement: createWithStatement,
+ updateWithStatement: updateWithStatement,
+ createSwitchStatement: createSwitchStatement,
+ updateSwitchStatement: updateSwitchStatement,
+ createLabeledStatement: createLabeledStatement,
+ updateLabeledStatement: updateLabeledStatement,
+ createThrowStatement: createThrowStatement,
+ updateThrowStatement: updateThrowStatement,
+ createTryStatement: createTryStatement,
+ updateTryStatement: updateTryStatement,
+ createDebuggerStatement: createDebuggerStatement,
+ createVariableDeclaration: createVariableDeclaration,
+ updateVariableDeclaration: updateVariableDeclaration,
+ createVariableDeclarationList: createVariableDeclarationList,
+ updateVariableDeclarationList: updateVariableDeclarationList,
+ createFunctionDeclaration: createFunctionDeclaration,
+ updateFunctionDeclaration: updateFunctionDeclaration,
+ createClassDeclaration: createClassDeclaration,
+ updateClassDeclaration: updateClassDeclaration,
+ createInterfaceDeclaration: createInterfaceDeclaration,
+ updateInterfaceDeclaration: updateInterfaceDeclaration,
+ createTypeAliasDeclaration: createTypeAliasDeclaration,
+ updateTypeAliasDeclaration: updateTypeAliasDeclaration,
+ createEnumDeclaration: createEnumDeclaration,
+ updateEnumDeclaration: updateEnumDeclaration,
+ createModuleDeclaration: createModuleDeclaration,
+ updateModuleDeclaration: updateModuleDeclaration,
+ createModuleBlock: createModuleBlock,
+ updateModuleBlock: updateModuleBlock,
+ createCaseBlock: createCaseBlock,
+ updateCaseBlock: updateCaseBlock,
+ createNamespaceExportDeclaration: createNamespaceExportDeclaration,
+ updateNamespaceExportDeclaration: updateNamespaceExportDeclaration,
+ createImportEqualsDeclaration: createImportEqualsDeclaration,
+ updateImportEqualsDeclaration: updateImportEqualsDeclaration,
+ createImportDeclaration: createImportDeclaration,
+ updateImportDeclaration: updateImportDeclaration,
+ createImportClause: createImportClause,
+ updateImportClause: updateImportClause,
+ createAssertClause: createAssertClause,
+ updateAssertClause: updateAssertClause,
+ createAssertEntry: createAssertEntry,
+ updateAssertEntry: updateAssertEntry,
+ createNamespaceImport: createNamespaceImport,
+ updateNamespaceImport: updateNamespaceImport,
+ createNamespaceExport: createNamespaceExport,
+ updateNamespaceExport: updateNamespaceExport,
+ createNamedImports: createNamedImports,
+ updateNamedImports: updateNamedImports,
+ createImportSpecifier: createImportSpecifier,
+ updateImportSpecifier: updateImportSpecifier,
+ createExportAssignment: createExportAssignment,
+ updateExportAssignment: updateExportAssignment,
+ createExportDeclaration: createExportDeclaration,
+ updateExportDeclaration: updateExportDeclaration,
+ createNamedExports: createNamedExports,
+ updateNamedExports: updateNamedExports,
+ createExportSpecifier: createExportSpecifier,
+ updateExportSpecifier: updateExportSpecifier,
+ createMissingDeclaration: createMissingDeclaration,
+ createExternalModuleReference: createExternalModuleReference,
+ updateExternalModuleReference: updateExternalModuleReference,
+ // lazily load factory members for JSDoc types with similar structure
+ get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(310 /* JSDocAllType */); },
+ get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(311 /* JSDocUnknownType */); },
+ get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(313 /* JSDocNonNullableType */); },
+ get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(313 /* JSDocNonNullableType */); },
+ get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(312 /* JSDocNullableType */); },
+ get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(312 /* JSDocNullableType */); },
+ get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(314 /* JSDocOptionalType */); },
+ get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(314 /* JSDocOptionalType */); },
+ get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(316 /* JSDocVariadicType */); },
+ get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(316 /* JSDocVariadicType */); },
+ get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(317 /* JSDocNamepathType */); },
+ get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(317 /* JSDocNamepathType */); },
+ createJSDocFunctionType: createJSDocFunctionType,
+ updateJSDocFunctionType: updateJSDocFunctionType,
+ createJSDocTypeLiteral: createJSDocTypeLiteral,
+ updateJSDocTypeLiteral: updateJSDocTypeLiteral,
+ createJSDocTypeExpression: createJSDocTypeExpression,
+ updateJSDocTypeExpression: updateJSDocTypeExpression,
+ createJSDocSignature: createJSDocSignature,
+ updateJSDocSignature: updateJSDocSignature,
+ createJSDocTemplateTag: createJSDocTemplateTag,
+ updateJSDocTemplateTag: updateJSDocTemplateTag,
+ createJSDocTypedefTag: createJSDocTypedefTag,
+ updateJSDocTypedefTag: updateJSDocTypedefTag,
+ createJSDocParameterTag: createJSDocParameterTag,
+ updateJSDocParameterTag: updateJSDocParameterTag,
+ createJSDocPropertyTag: createJSDocPropertyTag,
+ updateJSDocPropertyTag: updateJSDocPropertyTag,
+ createJSDocCallbackTag: createJSDocCallbackTag,
+ updateJSDocCallbackTag: updateJSDocCallbackTag,
+ createJSDocAugmentsTag: createJSDocAugmentsTag,
+ updateJSDocAugmentsTag: updateJSDocAugmentsTag,
+ createJSDocImplementsTag: createJSDocImplementsTag,
+ updateJSDocImplementsTag: updateJSDocImplementsTag,
+ createJSDocSeeTag: createJSDocSeeTag,
+ updateJSDocSeeTag: updateJSDocSeeTag,
+ createJSDocNameReference: createJSDocNameReference,
+ updateJSDocNameReference: updateJSDocNameReference,
+ createJSDocMemberName: createJSDocMemberName,
+ updateJSDocMemberName: updateJSDocMemberName,
+ createJSDocLink: createJSDocLink,
+ updateJSDocLink: updateJSDocLink,
+ createJSDocLinkCode: createJSDocLinkCode,
+ updateJSDocLinkCode: updateJSDocLinkCode,
+ createJSDocLinkPlain: createJSDocLinkPlain,
+ updateJSDocLinkPlain: updateJSDocLinkPlain,
+ // lazily load factory members for JSDoc tags with similar structure
+ get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(341 /* JSDocTypeTag */); },
+ get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(341 /* JSDocTypeTag */); },
+ get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(339 /* JSDocReturnTag */); },
+ get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(339 /* JSDocReturnTag */); },
+ get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(340 /* JSDocThisTag */); },
+ get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(340 /* JSDocThisTag */); },
+ get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(337 /* JSDocEnumTag */); },
+ get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(337 /* JSDocEnumTag */); },
+ get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(328 /* JSDocAuthorTag */); },
+ get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(328 /* JSDocAuthorTag */); },
+ get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(330 /* JSDocClassTag */); },
+ get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(330 /* JSDocClassTag */); },
+ get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(331 /* JSDocPublicTag */); },
+ get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(331 /* JSDocPublicTag */); },
+ get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(332 /* JSDocPrivateTag */); },
+ get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(332 /* JSDocPrivateTag */); },
+ get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(333 /* JSDocProtectedTag */); },
+ get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(333 /* JSDocProtectedTag */); },
+ get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(334 /* JSDocReadonlyTag */); },
+ get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(334 /* JSDocReadonlyTag */); },
+ get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(335 /* JSDocOverrideTag */); },
+ get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(335 /* JSDocOverrideTag */); },
+ get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(329 /* JSDocDeprecatedTag */); },
+ get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(329 /* JSDocDeprecatedTag */); },
+ createJSDocUnknownTag: createJSDocUnknownTag,
+ updateJSDocUnknownTag: updateJSDocUnknownTag,
+ createJSDocText: createJSDocText,
+ updateJSDocText: updateJSDocText,
+ createJSDocComment: createJSDocComment,
+ updateJSDocComment: updateJSDocComment,
+ createJsxElement: createJsxElement,
+ updateJsxElement: updateJsxElement,
+ createJsxSelfClosingElement: createJsxSelfClosingElement,
+ updateJsxSelfClosingElement: updateJsxSelfClosingElement,
+ createJsxOpeningElement: createJsxOpeningElement,
+ updateJsxOpeningElement: updateJsxOpeningElement,
+ createJsxClosingElement: createJsxClosingElement,
+ updateJsxClosingElement: updateJsxClosingElement,
+ createJsxFragment: createJsxFragment,
+ createJsxText: createJsxText,
+ updateJsxText: updateJsxText,
+ createJsxOpeningFragment: createJsxOpeningFragment,
+ createJsxJsxClosingFragment: createJsxJsxClosingFragment,
+ updateJsxFragment: updateJsxFragment,
+ createJsxAttribute: createJsxAttribute,
+ updateJsxAttribute: updateJsxAttribute,
+ createJsxAttributes: createJsxAttributes,
+ updateJsxAttributes: updateJsxAttributes,
+ createJsxSpreadAttribute: createJsxSpreadAttribute,
+ updateJsxSpreadAttribute: updateJsxSpreadAttribute,
+ createJsxExpression: createJsxExpression,
+ updateJsxExpression: updateJsxExpression,
+ createCaseClause: createCaseClause,
+ updateCaseClause: updateCaseClause,
+ createDefaultClause: createDefaultClause,
+ updateDefaultClause: updateDefaultClause,
+ createHeritageClause: createHeritageClause,
+ updateHeritageClause: updateHeritageClause,
+ createCatchClause: createCatchClause,
+ updateCatchClause: updateCatchClause,
+ createPropertyAssignment: createPropertyAssignment,
+ updatePropertyAssignment: updatePropertyAssignment,
+ createShorthandPropertyAssignment: createShorthandPropertyAssignment,
+ updateShorthandPropertyAssignment: updateShorthandPropertyAssignment,
+ createSpreadAssignment: createSpreadAssignment,
+ updateSpreadAssignment: updateSpreadAssignment,
+ createEnumMember: createEnumMember,
+ updateEnumMember: updateEnumMember,
+ createSourceFile: createSourceFile,
+ updateSourceFile: updateSourceFile,
+ createBundle: createBundle,
+ updateBundle: updateBundle,
+ createUnparsedSource: createUnparsedSource,
+ createUnparsedPrologue: createUnparsedPrologue,
+ createUnparsedPrepend: createUnparsedPrepend,
+ createUnparsedTextLike: createUnparsedTextLike,
+ createUnparsedSyntheticReference: createUnparsedSyntheticReference,
+ createInputFiles: createInputFiles,
+ createSyntheticExpression: createSyntheticExpression,
+ createSyntaxList: createSyntaxList,
+ createNotEmittedStatement: createNotEmittedStatement,
+ createPartiallyEmittedExpression: createPartiallyEmittedExpression,
+ updatePartiallyEmittedExpression: updatePartiallyEmittedExpression,
+ createCommaListExpression: createCommaListExpression,
+ updateCommaListExpression: updateCommaListExpression,
+ createEndOfDeclarationMarker: createEndOfDeclarationMarker,
+ createMergeDeclarationMarker: createMergeDeclarationMarker,
+ createSyntheticReferenceExpression: createSyntheticReferenceExpression,
+ updateSyntheticReferenceExpression: updateSyntheticReferenceExpression,
+ cloneNode: cloneNode,
+ // Lazily load factory methods for common operator factories and utilities
+ get createComma() { return getBinaryCreateFunction(27 /* CommaToken */); },
+ get createAssignment() { return getBinaryCreateFunction(63 /* EqualsToken */); },
+ get createLogicalOr() { return getBinaryCreateFunction(56 /* BarBarToken */); },
+ get createLogicalAnd() { return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */); },
+ get createBitwiseOr() { return getBinaryCreateFunction(51 /* BarToken */); },
+ get createBitwiseXor() { return getBinaryCreateFunction(52 /* CaretToken */); },
+ get createBitwiseAnd() { return getBinaryCreateFunction(50 /* AmpersandToken */); },
+ get createStrictEquality() { return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */); },
+ get createStrictInequality() { return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */); },
+ get createEquality() { return getBinaryCreateFunction(34 /* EqualsEqualsToken */); },
+ get createInequality() { return getBinaryCreateFunction(35 /* ExclamationEqualsToken */); },
+ get createLessThan() { return getBinaryCreateFunction(29 /* LessThanToken */); },
+ get createLessThanEquals() { return getBinaryCreateFunction(32 /* LessThanEqualsToken */); },
+ get createGreaterThan() { return getBinaryCreateFunction(31 /* GreaterThanToken */); },
+ get createGreaterThanEquals() { return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */); },
+ get createLeftShift() { return getBinaryCreateFunction(47 /* LessThanLessThanToken */); },
+ get createRightShift() { return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */); },
+ get createUnsignedRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */); },
+ get createAdd() { return getBinaryCreateFunction(39 /* PlusToken */); },
+ get createSubtract() { return getBinaryCreateFunction(40 /* MinusToken */); },
+ get createMultiply() { return getBinaryCreateFunction(41 /* AsteriskToken */); },
+ get createDivide() { return getBinaryCreateFunction(43 /* SlashToken */); },
+ get createModulo() { return getBinaryCreateFunction(44 /* PercentToken */); },
+ get createExponent() { return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */); },
+ get createPrefixPlus() { return getPrefixUnaryCreateFunction(39 /* PlusToken */); },
+ get createPrefixMinus() { return getPrefixUnaryCreateFunction(40 /* MinusToken */); },
+ get createPrefixIncrement() { return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */); },
+ get createPrefixDecrement() { return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */); },
+ get createBitwiseNot() { return getPrefixUnaryCreateFunction(54 /* TildeToken */); },
+ get createLogicalNot() { return getPrefixUnaryCreateFunction(53 /* ExclamationToken */); },
+ get createPostfixIncrement() { return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */); },
+ get createPostfixDecrement() { return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */); },
+ // Compound nodes
+ createImmediatelyInvokedFunctionExpression: createImmediatelyInvokedFunctionExpression,
+ createImmediatelyInvokedArrowFunction: createImmediatelyInvokedArrowFunction,
+ createVoidZero: createVoidZero,
+ createExportDefault: createExportDefault,
+ createExternalModuleExport: createExternalModuleExport,
+ createTypeCheck: createTypeCheck,
+ createMethodCall: createMethodCall,
+ createGlobalMethodCall: createGlobalMethodCall,
+ createFunctionBindCall: createFunctionBindCall,
+ createFunctionCallCall: createFunctionCallCall,
+ createFunctionApplyCall: createFunctionApplyCall,
+ createArraySliceCall: createArraySliceCall,
+ createArrayConcatCall: createArrayConcatCall,
+ createObjectDefinePropertyCall: createObjectDefinePropertyCall,
+ createReflectGetCall: createReflectGetCall,
+ createReflectSetCall: createReflectSetCall,
+ createPropertyDescriptor: createPropertyDescriptor,
+ createCallBinding: createCallBinding,
+ createAssignmentTargetWrapper: createAssignmentTargetWrapper,
+ // Utilities
+ inlineExpressions: inlineExpressions,
+ getInternalName: getInternalName,
+ getLocalName: getLocalName,
+ getExportName: getExportName,
+ getDeclarationName: getDeclarationName,
+ getNamespaceMemberName: getNamespaceMemberName,
+ getExternalModuleOrNamespaceExportName: getExternalModuleOrNamespaceExportName,
+ restoreOuterExpressions: restoreOuterExpressions,
+ restoreEnclosingLabel: restoreEnclosingLabel,
+ createUseStrictPrologue: createUseStrictPrologue,
+ copyPrologue: copyPrologue,
+ copyStandardPrologue: copyStandardPrologue,
+ copyCustomPrologue: copyCustomPrologue,
+ ensureUseStrict: ensureUseStrict,
+ liftToBlock: liftToBlock,
+ mergeLexicalEnvironment: mergeLexicalEnvironment,
+ updateModifiers: updateModifiers,
+ };
+ return factory;
+ // @api
+ function createNodeArray(elements, hasTrailingComma) {
+ if (elements === undefined || elements === ts.emptyArray) {
+ elements = [];
+ }
+ else if (ts.isNodeArray(elements)) {
+ if (hasTrailingComma === undefined || elements.hasTrailingComma === hasTrailingComma) {
+ // Ensure the transform flags have been aggregated for this NodeArray
+ if (elements.transformFlags === undefined) {
+ aggregateChildrenFlags(elements);
+ }
+ ts.Debug.attachNodeArrayDebugInfo(elements);
+ return elements;
+ }
+ // This *was* a `NodeArray`, but the `hasTrailingComma` option differs. Recreate the
+ // array with the same elements, text range, and transform flags but with the updated
+ // value for `hasTrailingComma`
+ var array_8 = elements.slice();
+ array_8.pos = elements.pos;
+ array_8.end = elements.end;
+ array_8.hasTrailingComma = hasTrailingComma;
+ array_8.transformFlags = elements.transformFlags;
+ ts.Debug.attachNodeArrayDebugInfo(array_8);
+ return array_8;
+ }
+ // 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);
+ ts.setTextRangePosEnd(array, -1, -1);
+ array.hasTrailingComma = !!hasTrailingComma;
+ aggregateChildrenFlags(array);
+ ts.Debug.attachNodeArrayDebugInfo(array);
+ return array;
+ }
+ function createBaseNode(kind) {
+ return baseFactory.createBaseNode(kind);
+ }
+ function createBaseDeclaration(kind, decorators, modifiers) {
+ var node = createBaseNode(kind);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.transformFlags |=
+ propagateChildrenFlags(node.decorators) |
+ propagateChildrenFlags(node.modifiers);
+ // NOTE: The following properties are commonly set by the binder and are added here to
+ // ensure declarations have a stable shape.
+ node.symbol = undefined; // initialized by binder
+ node.localSymbol = undefined; // initialized by binder
+ node.locals = undefined; // initialized by binder
+ node.nextContainer = undefined; // initialized by binder
+ return node;
+ }
+ function createBaseNamedDeclaration(kind, decorators, modifiers, name) {
+ var node = createBaseDeclaration(kind, decorators, modifiers);
+ name = asName(name);
+ node.name = name;
+ // The PropertyName of a member is allowed to be `await`.
+ // We don't need to exclude `await` for type signatures since types
+ // don't propagate child flags.
+ if (name) {
+ switch (node.kind) {
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 166 /* PropertyDeclaration */:
+ case 294 /* PropertyAssignment */:
+ if (ts.isIdentifier(name)) {
+ node.transformFlags |= propagateIdentifierNameFlags(name);
+ break;
+ }
+ // fall through
+ default:
+ node.transformFlags |= propagateChildFlags(name);
+ break;
+ }
+ }
+ return node;
+ }
+ function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) {
+ var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
+ node.typeParameters = asNodeArray(typeParameters);
+ node.transformFlags |= propagateChildrenFlags(node.typeParameters);
+ if (typeParameters)
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ return node;
+ }
+ function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) {
+ var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
+ node.parameters = createNodeArray(parameters);
+ node.type = type;
+ node.transformFlags |=
+ propagateChildrenFlags(node.parameters) |
+ propagateChildFlags(node.type);
+ if (type)
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ return node;
+ }
+ function updateBaseSignatureDeclaration(updated, original) {
+ // copy children used only for error reporting
+ if (original.typeArguments)
+ updated.typeArguments = original.typeArguments;
+ return update(updated, original);
+ }
+ function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) {
+ var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type);
+ node.body = body;
+ node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */;
+ if (!body)
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ return node;
+ }
+ function updateBaseFunctionLikeDeclaration(updated, original) {
+ // copy children used only for error reporting
+ if (original.exclamationToken)
+ updated.exclamationToken = original.exclamationToken;
+ if (original.typeArguments)
+ updated.typeArguments = original.typeArguments;
+ return updateBaseSignatureDeclaration(updated, original);
+ }
+ function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) {
+ var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
+ node.heritageClauses = asNodeArray(heritageClauses);
+ node.transformFlags |= propagateChildrenFlags(node.heritageClauses);
+ return node;
+ }
+ function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses);
+ node.members = createNodeArray(members);
+ node.transformFlags |= propagateChildrenFlags(node.members);
+ return node;
+ }
+ function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) {
+ var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
+ node.initializer = initializer;
+ node.transformFlags |= propagateChildFlags(node.initializer);
+ return node;
+ }
+ function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) {
+ var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer);
+ node.type = type;
+ node.transformFlags |= propagateChildFlags(type);
+ if (type)
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ return node;
+ }
+ //
+ // Literals
+ //
+ function createBaseLiteral(kind, text) {
+ var node = createBaseToken(kind);
+ node.text = text;
+ return node;
+ }
+ // @api
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
+ var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value);
+ node.numericLiteralFlags = numericLiteralFlags;
+ if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */)
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function createBigIntLiteral(value) {
+ var node = createBaseLiteral(9 /* BigIntLiteral */, typeof value === "string" ? value : ts.pseudoBigIntToString(value) + "n");
+ node.transformFlags |= 4 /* ContainsESNext */;
+ return node;
+ }
+ function createBaseStringLiteral(text, isSingleQuote) {
+ var node = createBaseLiteral(10 /* StringLiteral */, text);
+ node.singleQuote = isSingleQuote;
+ return node;
+ }
+ // @api
+ function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
+ var node = createBaseStringLiteral(text, isSingleQuote);
+ node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
+ if (hasExtendedUnicodeEscape)
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function createStringLiteralFromNode(sourceNode) {
+ var node = createBaseStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined);
+ node.textSourceNode = sourceNode;
+ return node;
+ }
+ // @api
+ function createRegularExpressionLiteral(text) {
+ var node = createBaseLiteral(13 /* RegularExpressionLiteral */, text);
+ return node;
+ }
+ // @api
+ function createLiteralLikeNode(kind, text) {
+ switch (kind) {
+ case 8 /* NumericLiteral */: return createNumericLiteral(text, /*numericLiteralFlags*/ 0);
+ case 9 /* BigIntLiteral */: return createBigIntLiteral(text);
+ case 10 /* StringLiteral */: return createStringLiteral(text, /*isSingleQuote*/ undefined);
+ case 11 /* JsxText */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false);
+ case 12 /* JsxTextAllWhiteSpaces */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true);
+ case 13 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text);
+ case 14 /* NoSubstitutionTemplateLiteral */: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0);
+ }
+ }
+ //
+ // Identifiers
+ //
+ function createBaseIdentifier(text, originalKeywordKind) {
+ if (originalKeywordKind === undefined && text) {
+ originalKeywordKind = ts.stringToToken(text);
+ }
+ if (originalKeywordKind === 79 /* Identifier */) {
+ originalKeywordKind = undefined;
+ }
+ var node = baseFactory.createBaseIdentifierNode(79 /* Identifier */);
+ node.originalKeywordKind = originalKeywordKind;
+ node.escapedText = ts.escapeLeadingUnderscores(text);
+ return node;
+ }
+ function createBaseGeneratedIdentifier(text, autoGenerateFlags) {
+ var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined);
+ node.autoGenerateFlags = autoGenerateFlags;
+ node.autoGenerateId = nextAutoGenerateId;
+ nextAutoGenerateId++;
+ return node;
+ }
+ // @api
+ function createIdentifier(text, typeArguments, originalKeywordKind) {
+ var node = createBaseIdentifier(text, originalKeywordKind);
+ if (typeArguments) {
+ // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
+ node.typeArguments = createNodeArray(typeArguments);
+ }
+ if (node.originalKeywordKind === 132 /* AwaitKeyword */) {
+ node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */;
+ }
+ return node;
+ }
+ // @api
+ function updateIdentifier(node, typeArguments) {
+ return node.typeArguments !== typeArguments
+ ? update(createIdentifier(ts.idText(node), typeArguments), node)
+ : node;
+ }
+ // @api
+ function createTempVariable(recordTempVariable, reservedInNestedScopes) {
+ var flags = 1 /* Auto */;
+ if (reservedInNestedScopes)
+ flags |= 8 /* ReservedInNestedScopes */;
+ var name = createBaseGeneratedIdentifier("", flags);
+ if (recordTempVariable) {
+ recordTempVariable(name);
+ }
+ return name;
+ }
+ /** Create a unique temporary variable for use in a loop. */
+ // @api
+ function createLoopVariable(reservedInNestedScopes) {
+ var flags = 2 /* Loop */;
+ if (reservedInNestedScopes)
+ flags |= 8 /* ReservedInNestedScopes */;
+ return createBaseGeneratedIdentifier("", flags);
+ }
+ /** Create a unique name based on the supplied text. */
+ // @api
+ function createUniqueName(text, flags) {
+ if (flags === void 0) { flags = 0 /* None */; }
+ ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
+ ts.Debug.assert((flags & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
+ return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags);
+ }
+ /** Create a unique name generated for a node. */
+ // @api
+ function getGeneratedNameForNode(node, flags) {
+ if (flags === void 0) { flags = 0; }
+ ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
+ var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* Node */ | flags);
+ name.original = node;
+ return name;
+ }
+ // @api
+ function createPrivateIdentifier(text) {
+ if (!ts.startsWith(text, "#"))
+ ts.Debug.fail("First character of private identifier must be #: " + text);
+ var node = baseFactory.createBasePrivateIdentifierNode(80 /* PrivateIdentifier */);
+ node.escapedText = ts.escapeLeadingUnderscores(text);
+ node.transformFlags |= 8388608 /* ContainsClassFields */;
+ return node;
+ }
+ //
+ // Punctuation
+ //
+ function createBaseToken(kind) {
+ return baseFactory.createBaseTokenNode(kind);
+ }
+ function createToken(token) {
+ ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 159 /* LastToken */, "Invalid token");
+ ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
+ ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
+ ts.Debug.assert(token !== 79 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
+ var node = createBaseToken(token);
+ var transformFlags = 0 /* None */;
+ switch (token) {
+ case 131 /* AsyncKeyword */:
+ // 'async' modifier is ES2017 (async functions) or ES2018 (async generators)
+ transformFlags =
+ 128 /* ContainsES2017 */ |
+ 64 /* ContainsES2018 */;
+ break;
+ case 123 /* PublicKeyword */:
+ case 121 /* PrivateKeyword */:
+ case 122 /* ProtectedKeyword */:
+ case 144 /* ReadonlyKeyword */:
+ case 126 /* AbstractKeyword */:
+ case 135 /* DeclareKeyword */:
+ case 85 /* ConstKeyword */:
+ case 130 /* AnyKeyword */:
+ case 146 /* NumberKeyword */:
+ case 157 /* BigIntKeyword */:
+ case 143 /* NeverKeyword */:
+ case 147 /* ObjectKeyword */:
+ case 158 /* OverrideKeyword */:
+ case 149 /* StringKeyword */:
+ case 133 /* BooleanKeyword */:
+ case 150 /* SymbolKeyword */:
+ case 114 /* VoidKeyword */:
+ case 154 /* UnknownKeyword */:
+ case 152 /* UndefinedKeyword */: // `undefined` is an Identifier in the expression case.
+ transformFlags = 1 /* ContainsTypeScript */;
+ break;
+ case 106 /* SuperKeyword */:
+ transformFlags = 512 /* ContainsES2015 */ | 33554432 /* ContainsLexicalSuper */;
+ break;
+ case 124 /* StaticKeyword */:
+ transformFlags = 512 /* ContainsES2015 */;
+ break;
+ case 108 /* ThisKeyword */:
+ // 'this' indicates a lexical 'this'
+ transformFlags = 8192 /* ContainsLexicalThis */;
+ break;
+ }
+ if (transformFlags) {
+ node.transformFlags |= transformFlags;
+ }
+ return node;
+ }
+ //
+ // Reserved words
+ //
+ // @api
+ function createSuper() {
+ return createToken(106 /* SuperKeyword */);
+ }
+ // @api
+ function createThis() {
+ return createToken(108 /* ThisKeyword */);
+ }
+ // @api
+ function createNull() {
+ return createToken(104 /* NullKeyword */);
+ }
+ // @api
+ function createTrue() {
+ return createToken(110 /* TrueKeyword */);
+ }
+ // @api
+ function createFalse() {
+ return createToken(95 /* FalseKeyword */);
+ }
+ //
+ // Modifiers
+ //
+ // @api
+ function createModifier(kind) {
+ return createToken(kind);
+ }
+ // @api
+ function createModifiersFromModifierFlags(flags) {
+ var result = [];
+ if (flags & 1 /* Export */)
+ result.push(createModifier(93 /* ExportKeyword */));
+ if (flags & 2 /* Ambient */)
+ result.push(createModifier(135 /* DeclareKeyword */));
+ if (flags & 512 /* Default */)
+ result.push(createModifier(88 /* DefaultKeyword */));
+ if (flags & 2048 /* Const */)
+ result.push(createModifier(85 /* ConstKeyword */));
+ if (flags & 4 /* Public */)
+ result.push(createModifier(123 /* PublicKeyword */));
+ if (flags & 8 /* Private */)
+ result.push(createModifier(121 /* PrivateKeyword */));
+ if (flags & 16 /* Protected */)
+ result.push(createModifier(122 /* ProtectedKeyword */));
+ if (flags & 128 /* Abstract */)
+ result.push(createModifier(126 /* AbstractKeyword */));
+ if (flags & 32 /* Static */)
+ result.push(createModifier(124 /* StaticKeyword */));
+ if (flags & 16384 /* Override */)
+ result.push(createModifier(158 /* OverrideKeyword */));
+ if (flags & 64 /* Readonly */)
+ result.push(createModifier(144 /* ReadonlyKeyword */));
+ if (flags & 256 /* Async */)
+ result.push(createModifier(131 /* AsyncKeyword */));
+ return result;
+ }
+ //
+ // Names
+ //
+ // @api
+ function createQualifiedName(left, right) {
+ var node = createBaseNode(160 /* QualifiedName */);
+ node.left = left;
+ node.right = asName(right);
+ node.transformFlags |=
+ propagateChildFlags(node.left) |
+ propagateIdentifierNameFlags(node.right);
+ return node;
+ }
+ // @api
+ function updateQualifiedName(node, left, right) {
+ return node.left !== left
+ || node.right !== right
+ ? update(createQualifiedName(left, right), node)
+ : node;
+ }
+ // @api
+ function createComputedPropertyName(expression) {
+ var node = createBaseNode(161 /* ComputedPropertyName */);
+ node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 512 /* ContainsES2015 */ |
+ 65536 /* ContainsComputedPropertyName */;
+ return node;
+ }
+ // @api
+ function updateComputedPropertyName(node, expression) {
+ return node.expression !== expression
+ ? update(createComputedPropertyName(expression), node)
+ : node;
+ }
+ //
+ // Signature elements
+ //
+ // @api
+ function createTypeParameterDeclaration(name, constraint, defaultType) {
+ var node = createBaseNamedDeclaration(162 /* TypeParameter */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, name);
+ node.constraint = constraint;
+ node.default = defaultType;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
+ return node.name !== name
+ || node.constraint !== constraint
+ || node.default !== defaultType
+ ? update(createTypeParameterDeclaration(name, constraint, defaultType), node)
+ : node;
+ }
+ // @api
+ function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
+ var node = createBaseVariableLikeDeclaration(163 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
+ node.dotDotDotToken = dotDotDotToken;
+ node.questionToken = questionToken;
+ if (ts.isThisIdentifier(node.name)) {
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ }
+ else {
+ node.transformFlags |=
+ propagateChildFlags(node.dotDotDotToken) |
+ propagateChildFlags(node.questionToken);
+ if (questionToken)
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */)
+ node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ if (initializer || dotDotDotToken)
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ }
+ return node;
+ }
+ // @api
+ function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.dotDotDotToken !== dotDotDotToken
+ || node.name !== name
+ || node.questionToken !== questionToken
+ || node.type !== type
+ || node.initializer !== initializer
+ ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
+ : node;
+ }
+ // @api
+ function createDecorator(expression) {
+ var node = createBaseNode(164 /* Decorator */);
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 1 /* ContainsTypeScript */ |
+ 4096 /* ContainsTypeScriptClassSyntax */;
+ return node;
+ }
+ // @api
+ function updateDecorator(node, expression) {
+ return node.expression !== expression
+ ? update(createDecorator(expression), node)
+ : node;
+ }
+ //
+ // Type Elements
+ //
+ // @api
+ function createPropertySignature(modifiers, name, questionToken, type) {
+ var node = createBaseNamedDeclaration(165 /* PropertySignature */,
+ /*decorators*/ undefined, modifiers, name);
+ node.type = type;
+ node.questionToken = questionToken;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updatePropertySignature(node, modifiers, name, questionToken, type) {
+ return node.modifiers !== modifiers
+ || node.name !== name
+ || node.questionToken !== questionToken
+ || node.type !== type
+ ? update(createPropertySignature(modifiers, name, questionToken, type), node)
+ : node;
+ }
+ // @api
+ function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
+ var node = createBaseVariableLikeDeclaration(166 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer);
+ node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
+ node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
+ node.transformFlags |=
+ propagateChildFlags(node.questionToken) |
+ propagateChildFlags(node.exclamationToken) |
+ 8388608 /* ContainsClassFields */;
+ if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
+ node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ }
+ if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ return node;
+ }
+ // @api
+ function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
+ || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
+ || node.type !== type
+ || node.initializer !== initializer
+ ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
+ : node;
+ }
+ // @api
+ function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
+ var node = createBaseSignatureDeclaration(167 /* MethodSignature */,
+ /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type);
+ node.questionToken = questionToken;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
+ return node.modifiers !== modifiers
+ || node.name !== name
+ || node.questionToken !== questionToken
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node)
+ : node;
+ }
+ // @api
+ function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
+ var node = createBaseFunctionLikeDeclaration(168 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
+ node.asteriskToken = asteriskToken;
+ node.questionToken = questionToken;
+ node.transformFlags |=
+ propagateChildFlags(node.asteriskToken) |
+ propagateChildFlags(node.questionToken) |
+ 512 /* ContainsES2015 */;
+ if (questionToken) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
+ if (asteriskToken) {
+ node.transformFlags |= 64 /* ContainsES2018 */;
+ }
+ else {
+ node.transformFlags |= 128 /* ContainsES2017 */;
+ }
+ }
+ else if (asteriskToken) {
+ node.transformFlags |= 1024 /* ContainsGenerator */;
+ }
+ return node;
+ }
+ // @api
+ function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.asteriskToken !== asteriskToken
+ || node.name !== name
+ || node.questionToken !== questionToken
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
+ : node;
+ }
+ // @api
+ function createClassStaticBlockDeclaration(decorators, modifiers, body) {
+ var node = createBaseGenericNamedDeclaration(169 /* ClassStaticBlockDeclaration */, decorators, modifiers,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined);
+ node.body = body;
+ node.transformFlags = propagateChildFlags(body) | 8388608 /* ContainsClassFields */;
+ return node;
+ }
+ // @api
+ function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) {
+ return node.decorators !== decorators
+ || node.modifier !== modifiers
+ || node.body !== body
+ ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node)
+ : node;
+ }
+ // @api
+ function createConstructorDeclaration(decorators, modifiers, parameters, body) {
+ var node = createBaseFunctionLikeDeclaration(170 /* Constructor */, decorators, modifiers,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, parameters,
+ /*type*/ undefined, body);
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.parameters !== parameters
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node)
+ : node;
+ }
+ // @api
+ function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) {
+ return createBaseFunctionLikeDeclaration(171 /* GetAccessor */, decorators, modifiers, name,
+ /*typeParameters*/ undefined, parameters, type, body);
+ }
+ // @api
+ function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node)
+ : node;
+ }
+ // @api
+ function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) {
+ return createBaseFunctionLikeDeclaration(172 /* SetAccessor */, decorators, modifiers, name,
+ /*typeParameters*/ undefined, parameters,
+ /*type*/ undefined, body);
+ }
+ // @api
+ function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.parameters !== parameters
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node)
+ : node;
+ }
+ // @api
+ function createCallSignature(typeParameters, parameters, type) {
+ var node = createBaseSignatureDeclaration(173 /* CallSignature */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*name*/ undefined, typeParameters, parameters, type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateCallSignature(node, typeParameters, parameters, type) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node)
+ : node;
+ }
+ // @api
+ function createConstructSignature(typeParameters, parameters, type) {
+ var node = createBaseSignatureDeclaration(174 /* ConstructSignature */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*name*/ undefined, typeParameters, parameters, type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateConstructSignature(node, typeParameters, parameters, type) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node)
+ : node;
+ }
+ // @api
+ function createIndexSignature(decorators, modifiers, parameters, type) {
+ var node = createBaseSignatureDeclaration(175 /* IndexSignature */, decorators, modifiers,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, parameters, type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateIndexSignature(node, decorators, modifiers, parameters, type) {
+ return node.parameters !== parameters
+ || node.type !== type
+ || node.decorators !== decorators
+ || node.modifiers !== modifiers
+ ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node)
+ : node;
+ }
+ // @api
+ function createTemplateLiteralTypeSpan(type, literal) {
+ var node = createBaseNode(198 /* TemplateLiteralTypeSpan */);
+ node.type = type;
+ node.literal = literal;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTemplateLiteralTypeSpan(node, type, literal) {
+ return node.type !== type
+ || node.literal !== literal
+ ? update(createTemplateLiteralTypeSpan(type, literal), node)
+ : node;
+ }
+ //
+ // Types
+ //
+ // @api
+ function createKeywordTypeNode(kind) {
+ return createToken(kind);
+ }
+ // @api
+ function createTypePredicateNode(assertsModifier, parameterName, type) {
+ var node = createBaseNode(176 /* TypePredicate */);
+ node.assertsModifier = assertsModifier;
+ node.parameterName = asName(parameterName);
+ node.type = type;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
+ return node.assertsModifier !== assertsModifier
+ || node.parameterName !== parameterName
+ || node.type !== type
+ ? update(createTypePredicateNode(assertsModifier, parameterName, type), node)
+ : node;
+ }
+ // @api
+ function createTypeReferenceNode(typeName, typeArguments) {
+ var node = createBaseNode(177 /* TypeReference */);
+ node.typeName = asName(typeName);
+ node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeReferenceNode(node, typeName, typeArguments) {
+ return node.typeName !== typeName
+ || node.typeArguments !== typeArguments
+ ? update(createTypeReferenceNode(typeName, typeArguments), node)
+ : node;
+ }
+ // @api
+ function createFunctionTypeNode(typeParameters, parameters, type) {
+ var node = createBaseSignatureDeclaration(178 /* FunctionType */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*name*/ undefined, typeParameters, parameters, type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateFunctionTypeNode(node, typeParameters, parameters, type) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node)
+ : node;
+ }
+ // @api
+ function createConstructorTypeNode() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return args.length === 4 ? createConstructorTypeNode1.apply(void 0, args) :
+ args.length === 3 ? createConstructorTypeNode2.apply(void 0, args) :
+ ts.Debug.fail("Incorrect number of arguments specified.");
+ }
+ function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) {
+ var node = createBaseSignatureDeclaration(179 /* ConstructorType */,
+ /*decorators*/ undefined, modifiers,
+ /*name*/ undefined, typeParameters, parameters, type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ /** @deprecated */
+ function createConstructorTypeNode2(typeParameters, parameters, type) {
+ return createConstructorTypeNode1(/*modifiers*/ undefined, typeParameters, parameters, type);
+ }
+ // @api
+ function updateConstructorTypeNode() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return args.length === 5 ? updateConstructorTypeNode1.apply(void 0, args) :
+ args.length === 4 ? updateConstructorTypeNode2.apply(void 0, args) :
+ ts.Debug.fail("Incorrect number of arguments specified.");
+ }
+ function updateConstructorTypeNode1(node, modifiers, typeParameters, parameters, type) {
+ return node.modifiers !== modifiers
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node)
+ : node;
+ }
+ /** @deprecated */
+ function updateConstructorTypeNode2(node, typeParameters, parameters, type) {
+ return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type);
+ }
+ // @api
+ function createTypeQueryNode(exprName) {
+ var node = createBaseNode(180 /* TypeQuery */);
+ node.exprName = exprName;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeQueryNode(node, exprName) {
+ return node.exprName !== exprName
+ ? update(createTypeQueryNode(exprName), node)
+ : node;
+ }
+ // @api
+ function createTypeLiteralNode(members) {
+ var node = createBaseNode(181 /* TypeLiteral */);
+ node.members = createNodeArray(members);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeLiteralNode(node, members) {
+ return node.members !== members
+ ? update(createTypeLiteralNode(members), node)
+ : node;
+ }
+ // @api
+ function createArrayTypeNode(elementType) {
+ var node = createBaseNode(182 /* ArrayType */);
+ node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateArrayTypeNode(node, elementType) {
+ return node.elementType !== elementType
+ ? update(createArrayTypeNode(elementType), node)
+ : node;
+ }
+ // @api
+ function createTupleTypeNode(elements) {
+ var node = createBaseNode(183 /* TupleType */);
+ node.elements = createNodeArray(elements);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTupleTypeNode(node, elements) {
+ return node.elements !== elements
+ ? update(createTupleTypeNode(elements), node)
+ : node;
+ }
+ // @api
+ function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
+ var node = createBaseNode(196 /* NamedTupleMember */);
+ node.dotDotDotToken = dotDotDotToken;
+ node.name = name;
+ node.questionToken = questionToken;
+ node.type = type;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
+ return node.dotDotDotToken !== dotDotDotToken
+ || node.name !== name
+ || node.questionToken !== questionToken
+ || node.type !== type
+ ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node)
+ : node;
+ }
+ // @api
+ function createOptionalTypeNode(type) {
+ var node = createBaseNode(184 /* OptionalType */);
+ node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateOptionalTypeNode(node, type) {
+ return node.type !== type
+ ? update(createOptionalTypeNode(type), node)
+ : node;
+ }
+ // @api
+ function createRestTypeNode(type) {
+ var node = createBaseNode(185 /* RestType */);
+ node.type = type;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateRestTypeNode(node, type) {
+ return node.type !== type
+ ? update(createRestTypeNode(type), node)
+ : node;
+ }
+ function createUnionOrIntersectionTypeNode(kind, types) {
+ var node = createBaseNode(kind);
+ node.types = parenthesizerRules().parenthesizeConstituentTypesOfUnionOrIntersectionType(types);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ function updateUnionOrIntersectionTypeNode(node, types) {
+ return node.types !== types
+ ? update(createUnionOrIntersectionTypeNode(node.kind, types), node)
+ : node;
+ }
+ // @api
+ function createUnionTypeNode(types) {
+ return createUnionOrIntersectionTypeNode(186 /* UnionType */, types);
+ }
+ // @api
+ function updateUnionTypeNode(node, types) {
+ return updateUnionOrIntersectionTypeNode(node, types);
+ }
+ // @api
+ function createIntersectionTypeNode(types) {
+ return createUnionOrIntersectionTypeNode(187 /* IntersectionType */, types);
+ }
+ // @api
+ function updateIntersectionTypeNode(node, types) {
+ return updateUnionOrIntersectionTypeNode(node, types);
+ }
+ // @api
+ function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
+ var node = createBaseNode(188 /* ConditionalType */);
+ node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType);
+ node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType);
+ node.trueType = trueType;
+ node.falseType = falseType;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
+ return node.checkType !== checkType
+ || node.extendsType !== extendsType
+ || node.trueType !== trueType
+ || node.falseType !== falseType
+ ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
+ : node;
+ }
+ // @api
+ function createInferTypeNode(typeParameter) {
+ var node = createBaseNode(189 /* InferType */);
+ node.typeParameter = typeParameter;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateInferTypeNode(node, typeParameter) {
+ return node.typeParameter !== typeParameter
+ ? update(createInferTypeNode(typeParameter), node)
+ : node;
+ }
+ // @api
+ function createTemplateLiteralType(head, templateSpans) {
+ var node = createBaseNode(197 /* TemplateLiteralType */);
+ node.head = head;
+ node.templateSpans = createNodeArray(templateSpans);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTemplateLiteralType(node, head, templateSpans) {
+ return node.head !== head
+ || node.templateSpans !== templateSpans
+ ? update(createTemplateLiteralType(head, templateSpans), node)
+ : node;
+ }
+ // @api
+ function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
+ if (isTypeOf === void 0) { isTypeOf = false; }
+ var node = createBaseNode(199 /* ImportType */);
+ node.argument = argument;
+ node.qualifier = qualifier;
+ node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
+ node.isTypeOf = isTypeOf;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
+ if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; }
+ return node.argument !== argument
+ || node.qualifier !== qualifier
+ || node.typeArguments !== typeArguments
+ || node.isTypeOf !== isTypeOf
+ ? update(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
+ : node;
+ }
+ // @api
+ function createParenthesizedType(type) {
+ var node = createBaseNode(190 /* ParenthesizedType */);
+ node.type = type;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateParenthesizedType(node, type) {
+ return node.type !== type
+ ? update(createParenthesizedType(type), node)
+ : node;
+ }
+ // @api
+ function createThisTypeNode() {
+ var node = createBaseNode(191 /* ThisType */);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function createTypeOperatorNode(operator, type) {
+ var node = createBaseNode(192 /* TypeOperator */);
+ node.operator = operator;
+ node.type = parenthesizerRules().parenthesizeMemberOfElementType(type);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeOperatorNode(node, type) {
+ return node.type !== type
+ ? update(createTypeOperatorNode(node.operator, type), node)
+ : node;
+ }
+ // @api
+ function createIndexedAccessTypeNode(objectType, indexType) {
+ var node = createBaseNode(193 /* IndexedAccessType */);
+ node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType);
+ node.indexType = indexType;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateIndexedAccessTypeNode(node, objectType, indexType) {
+ return node.objectType !== objectType
+ || node.indexType !== indexType
+ ? update(createIndexedAccessTypeNode(objectType, indexType), node)
+ : node;
+ }
+ // @api
+ function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) {
+ var node = createBaseNode(194 /* MappedType */);
+ node.readonlyToken = readonlyToken;
+ node.typeParameter = typeParameter;
+ node.nameType = nameType;
+ node.questionToken = questionToken;
+ node.type = type;
+ node.members = members && createNodeArray(members);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) {
+ return node.readonlyToken !== readonlyToken
+ || node.typeParameter !== typeParameter
+ || node.nameType !== nameType
+ || node.questionToken !== questionToken
+ || node.type !== type
+ || node.members !== members
+ ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node)
+ : node;
+ }
+ // @api
+ function createLiteralTypeNode(literal) {
+ var node = createBaseNode(195 /* LiteralType */);
+ node.literal = literal;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateLiteralTypeNode(node, literal) {
+ return node.literal !== literal
+ ? update(createLiteralTypeNode(literal), node)
+ : node;
+ }
+ //
+ // Binding Patterns
+ //
+ // @api
+ function createObjectBindingPattern(elements) {
+ var node = createBaseNode(200 /* ObjectBindingPattern */);
+ node.elements = createNodeArray(elements);
+ node.transformFlags |=
+ propagateChildrenFlags(node.elements) |
+ 512 /* ContainsES2015 */ |
+ 262144 /* ContainsBindingPattern */;
+ if (node.transformFlags & 16384 /* ContainsRestOrSpread */) {
+ node.transformFlags |=
+ 64 /* ContainsES2018 */ |
+ 32768 /* ContainsObjectRestOrSpread */;
+ }
+ return node;
+ }
+ // @api
+ function updateObjectBindingPattern(node, elements) {
+ return node.elements !== elements
+ ? update(createObjectBindingPattern(elements), node)
+ : node;
+ }
+ // @api
+ function createArrayBindingPattern(elements) {
+ var node = createBaseNode(201 /* ArrayBindingPattern */);
+ node.elements = createNodeArray(elements);
+ node.transformFlags |=
+ propagateChildrenFlags(node.elements) |
+ 512 /* ContainsES2015 */ |
+ 262144 /* ContainsBindingPattern */;
+ return node;
+ }
+ // @api
+ function updateArrayBindingPattern(node, elements) {
+ return node.elements !== elements
+ ? update(createArrayBindingPattern(elements), node)
+ : node;
+ }
+ // @api
+ function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
+ var node = createBaseBindingLikeDeclaration(202 /* BindingElement */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
+ node.propertyName = asName(propertyName);
+ node.dotDotDotToken = dotDotDotToken;
+ node.transformFlags |=
+ propagateChildFlags(node.dotDotDotToken) |
+ 512 /* ContainsES2015 */;
+ if (node.propertyName) {
+ node.transformFlags |= ts.isIdentifier(node.propertyName) ?
+ propagateIdentifierNameFlags(node.propertyName) :
+ propagateChildFlags(node.propertyName);
+ }
+ if (dotDotDotToken)
+ node.transformFlags |= 16384 /* ContainsRestOrSpread */;
+ return node;
+ }
+ // @api
+ function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
+ return node.propertyName !== propertyName
+ || node.dotDotDotToken !== dotDotDotToken
+ || node.name !== name
+ || node.initializer !== initializer
+ ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
+ : node;
+ }
+ //
+ // Expression
+ //
+ function createBaseExpression(kind) {
+ var node = createBaseNode(kind);
+ // the following properties are commonly set by the checker/binder
+ return node;
+ }
+ // @api
+ function createArrayLiteralExpression(elements, multiLine) {
+ var node = createBaseExpression(203 /* ArrayLiteralExpression */);
+ // Ensure we add a trailing comma for something like `[NumericLiteral(1), NumericLiteral(2), OmittedExpresion]` so that
+ // we end up with `[1, 2, ,]` instead of `[1, 2, ]` otherwise the `OmittedExpression` will just end up being treated like
+ // a trailing comma.
+ var lastElement = elements && ts.lastOrUndefined(elements);
+ var elementsArray = createNodeArray(elements, lastElement && ts.isOmittedExpression(lastElement) ? true : undefined);
+ node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray);
+ node.multiLine = multiLine;
+ node.transformFlags |= propagateChildrenFlags(node.elements);
+ return node;
+ }
+ // @api
+ function updateArrayLiteralExpression(node, elements) {
+ return node.elements !== elements
+ ? update(createArrayLiteralExpression(elements, node.multiLine), node)
+ : node;
+ }
+ // @api
+ function createObjectLiteralExpression(properties, multiLine) {
+ var node = createBaseExpression(204 /* ObjectLiteralExpression */);
+ node.properties = createNodeArray(properties);
+ node.multiLine = multiLine;
+ node.transformFlags |= propagateChildrenFlags(node.properties);
+ return node;
+ }
+ // @api
+ function updateObjectLiteralExpression(node, properties) {
+ return node.properties !== properties
+ ? update(createObjectLiteralExpression(properties, node.multiLine), node)
+ : node;
+ }
+ // @api
+ function createPropertyAccessExpression(expression, name) {
+ var node = createBaseExpression(205 /* PropertyAccessExpression */);
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.name = asName(name);
+ node.transformFlags =
+ propagateChildFlags(node.expression) |
+ (ts.isIdentifier(node.name) ?
+ propagateIdentifierNameFlags(node.name) :
+ propagateChildFlags(node.name));
+ if (ts.isSuperKeyword(expression)) {
+ // super method calls require a lexical 'this'
+ // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
+ node.transformFlags |=
+ 128 /* ContainsES2017 */ |
+ 64 /* ContainsES2018 */;
+ }
+ return node;
+ }
+ // @api
+ function updatePropertyAccessExpression(node, expression, name) {
+ if (ts.isPropertyAccessChain(node)) {
+ return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
+ }
+ return node.expression !== expression
+ || node.name !== name
+ ? update(createPropertyAccessExpression(expression, name), node)
+ : node;
+ }
+ // @api
+ function createPropertyAccessChain(expression, questionDotToken, name) {
+ var node = createBaseExpression(205 /* PropertyAccessExpression */);
+ node.flags |= 32 /* OptionalChain */;
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.questionDotToken = questionDotToken;
+ node.name = asName(name);
+ node.transformFlags |=
+ 16 /* ContainsES2020 */ |
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.questionDotToken) |
+ (ts.isIdentifier(node.name) ?
+ propagateIdentifierNameFlags(node.name) :
+ propagateChildFlags(node.name));
+ return node;
+ }
+ // @api
+ function updatePropertyAccessChain(node, expression, questionDotToken, name) {
+ ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
+ // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
+ // instead of using the default from createPropertyAccess
+ return node.expression !== expression
+ || node.questionDotToken !== questionDotToken
+ || node.name !== name
+ ? update(createPropertyAccessChain(expression, questionDotToken, name), node)
+ : node;
+ }
+ // @api
+ function createElementAccessExpression(expression, index) {
+ var node = createBaseExpression(206 /* ElementAccessExpression */);
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.argumentExpression = asExpression(index);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.argumentExpression);
+ if (ts.isSuperKeyword(expression)) {
+ // super method calls require a lexical 'this'
+ // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
+ node.transformFlags |=
+ 128 /* ContainsES2017 */ |
+ 64 /* ContainsES2018 */;
+ }
+ return node;
+ }
+ // @api
+ function updateElementAccessExpression(node, expression, argumentExpression) {
+ if (ts.isElementAccessChain(node)) {
+ return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
+ }
+ return node.expression !== expression
+ || node.argumentExpression !== argumentExpression
+ ? update(createElementAccessExpression(expression, argumentExpression), node)
+ : node;
+ }
+ // @api
+ function createElementAccessChain(expression, questionDotToken, index) {
+ var node = createBaseExpression(206 /* ElementAccessExpression */);
+ node.flags |= 32 /* OptionalChain */;
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.questionDotToken = questionDotToken;
+ node.argumentExpression = asExpression(index);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.questionDotToken) |
+ propagateChildFlags(node.argumentExpression) |
+ 16 /* ContainsES2020 */;
+ return node;
+ }
+ // @api
+ function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
+ ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
+ // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags
+ // instead of using the default from createElementAccess
+ return node.expression !== expression
+ || node.questionDotToken !== questionDotToken
+ || node.argumentExpression !== argumentExpression
+ ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
+ : node;
+ }
+ // @api
+ function createCallExpression(expression, typeArguments, argumentsArray) {
+ var node = createBaseExpression(207 /* CallExpression */);
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.typeArguments = asNodeArray(typeArguments);
+ node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildrenFlags(node.typeArguments) |
+ propagateChildrenFlags(node.arguments);
+ if (node.typeArguments) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ if (ts.isImportKeyword(node.expression)) {
+ node.transformFlags |= 4194304 /* ContainsDynamicImport */;
+ }
+ else if (ts.isSuperProperty(node.expression)) {
+ node.transformFlags |= 8192 /* ContainsLexicalThis */;
+ }
+ return node;
+ }
+ // @api
+ function updateCallExpression(node, expression, typeArguments, argumentsArray) {
+ if (ts.isCallChain(node)) {
+ return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
+ }
+ return node.expression !== expression
+ || node.typeArguments !== typeArguments
+ || node.arguments !== argumentsArray
+ ? update(createCallExpression(expression, typeArguments, argumentsArray), node)
+ : node;
+ }
+ // @api
+ function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
+ var node = createBaseExpression(207 /* CallExpression */);
+ node.flags |= 32 /* OptionalChain */;
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.questionDotToken = questionDotToken;
+ node.typeArguments = asNodeArray(typeArguments);
+ node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.questionDotToken) |
+ propagateChildrenFlags(node.typeArguments) |
+ propagateChildrenFlags(node.arguments) |
+ 16 /* ContainsES2020 */;
+ if (node.typeArguments) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ if (ts.isSuperProperty(node.expression)) {
+ node.transformFlags |= 8192 /* ContainsLexicalThis */;
+ }
+ return node;
+ }
+ // @api
+ function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
+ ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
+ return node.expression !== expression
+ || node.questionDotToken !== questionDotToken
+ || node.typeArguments !== typeArguments
+ || node.arguments !== argumentsArray
+ ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
+ : node;
+ }
+ // @api
+ function createNewExpression(expression, typeArguments, argumentsArray) {
+ var node = createBaseExpression(208 /* NewExpression */);
+ node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
+ node.typeArguments = asNodeArray(typeArguments);
+ node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildrenFlags(node.typeArguments) |
+ propagateChildrenFlags(node.arguments) |
+ 16 /* ContainsES2020 */;
+ if (node.typeArguments) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ return node;
+ }
+ // @api
+ function updateNewExpression(node, expression, typeArguments, argumentsArray) {
+ return node.expression !== expression
+ || node.typeArguments !== typeArguments
+ || node.arguments !== argumentsArray
+ ? update(createNewExpression(expression, typeArguments, argumentsArray), node)
+ : node;
+ }
+ // @api
+ function createTaggedTemplateExpression(tag, typeArguments, template) {
+ var node = createBaseExpression(209 /* TaggedTemplateExpression */);
+ node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag);
+ node.typeArguments = asNodeArray(typeArguments);
+ node.template = template;
+ node.transformFlags |=
+ propagateChildFlags(node.tag) |
+ propagateChildrenFlags(node.typeArguments) |
+ propagateChildFlags(node.template) |
+ 512 /* ContainsES2015 */;
+ if (node.typeArguments) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ if (ts.hasInvalidEscape(node.template)) {
+ node.transformFlags |= 64 /* ContainsES2018 */;
+ }
+ return node;
+ }
+ // @api
+ function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
+ return node.tag !== tag
+ || node.typeArguments !== typeArguments
+ || node.template !== template
+ ? update(createTaggedTemplateExpression(tag, typeArguments, template), node)
+ : node;
+ }
+ // @api
+ function createTypeAssertion(type, expression) {
+ var node = createBaseExpression(210 /* TypeAssertionExpression */);
+ node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
+ node.type = type;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.type) |
+ 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeAssertion(node, type, expression) {
+ return node.type !== type
+ || node.expression !== expression
+ ? update(createTypeAssertion(type, expression), node)
+ : node;
+ }
+ // @api
+ function createParenthesizedExpression(expression) {
+ var node = createBaseExpression(211 /* ParenthesizedExpression */);
+ node.expression = expression;
+ node.transformFlags = propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateParenthesizedExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createParenthesizedExpression(expression), node)
+ : node;
+ }
+ // @api
+ function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ var node = createBaseFunctionLikeDeclaration(212 /* FunctionExpression */,
+ /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body);
+ node.asteriskToken = asteriskToken;
+ node.transformFlags |= propagateChildFlags(node.asteriskToken);
+ if (node.typeParameters) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
+ if (node.asteriskToken) {
+ node.transformFlags |= 64 /* ContainsES2018 */;
+ }
+ else {
+ node.transformFlags |= 128 /* ContainsES2017 */;
+ }
+ }
+ else if (node.asteriskToken) {
+ node.transformFlags |= 1024 /* ContainsGenerator */;
+ }
+ return node;
+ }
+ // @api
+ function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ return node.name !== name
+ || node.modifiers !== modifiers
+ || node.asteriskToken !== asteriskToken
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
+ : node;
+ }
+ // @api
+ function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
+ var node = createBaseFunctionLikeDeclaration(213 /* ArrowFunction */,
+ /*decorators*/ undefined, modifiers,
+ /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body));
+ node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */);
+ node.transformFlags |=
+ propagateChildFlags(node.equalsGreaterThanToken) |
+ 512 /* ContainsES2015 */;
+ if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
+ node.transformFlags |= 128 /* ContainsES2017 */ | 8192 /* ContainsLexicalThis */;
+ }
+ return node;
+ }
+ // @api
+ function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
+ return node.modifiers !== modifiers
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.equalsGreaterThanToken !== equalsGreaterThanToken
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
+ : node;
+ }
+ // @api
+ function createDeleteExpression(expression) {
+ var node = createBaseExpression(214 /* DeleteExpression */);
+ node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
+ node.transformFlags |= propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateDeleteExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createDeleteExpression(expression), node)
+ : node;
+ }
+ // @api
+ function createTypeOfExpression(expression) {
+ var node = createBaseExpression(215 /* TypeOfExpression */);
+ node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
+ node.transformFlags |= propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateTypeOfExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createTypeOfExpression(expression), node)
+ : node;
+ }
+ // @api
+ function createVoidExpression(expression) {
+ var node = createBaseExpression(216 /* VoidExpression */);
+ node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
+ node.transformFlags |= propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateVoidExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createVoidExpression(expression), node)
+ : node;
+ }
+ // @api
+ function createAwaitExpression(expression) {
+ var node = createBaseExpression(217 /* AwaitExpression */);
+ node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 128 /* ContainsES2017 */ |
+ 64 /* ContainsES2018 */ |
+ 1048576 /* ContainsAwait */;
+ return node;
+ }
+ // @api
+ function updateAwaitExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createAwaitExpression(expression), node)
+ : node;
+ }
+ // @api
+ function createPrefixUnaryExpression(operator, operand) {
+ var node = createBaseExpression(218 /* PrefixUnaryExpression */);
+ node.operator = operator;
+ node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
+ node.transformFlags |= propagateChildFlags(node.operand);
+ // Only set this flag for non-generated identifiers and non-"local" names. See the
+ // comment in `visitPreOrPostfixUnaryExpression` in module.ts
+ if ((operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */) &&
+ ts.isIdentifier(node.operand) &&
+ !ts.isGeneratedIdentifier(node.operand) &&
+ !ts.isLocalName(node.operand)) {
+ node.transformFlags |= 67108864 /* ContainsUpdateExpressionForIdentifier */;
+ }
+ return node;
+ }
+ // @api
+ function updatePrefixUnaryExpression(node, operand) {
+ return node.operand !== operand
+ ? update(createPrefixUnaryExpression(node.operator, operand), node)
+ : node;
+ }
+ // @api
+ function createPostfixUnaryExpression(operand, operator) {
+ var node = createBaseExpression(219 /* PostfixUnaryExpression */);
+ node.operator = operator;
+ node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
+ node.transformFlags |= propagateChildFlags(node.operand);
+ // Only set this flag for non-generated identifiers and non-"local" names. See the
+ // comment in `visitPreOrPostfixUnaryExpression` in module.ts
+ if (ts.isIdentifier(node.operand) &&
+ !ts.isGeneratedIdentifier(node.operand) &&
+ !ts.isLocalName(node.operand)) {
+ node.transformFlags |= 67108864 /* ContainsUpdateExpressionForIdentifier */;
+ }
+ return node;
+ }
+ // @api
+ function updatePostfixUnaryExpression(node, operand) {
+ return node.operand !== operand
+ ? update(createPostfixUnaryExpression(operand, node.operator), node)
+ : node;
+ }
+ // @api
+ function createBinaryExpression(left, operator, right) {
+ var node = createBaseExpression(220 /* BinaryExpression */);
+ var operatorToken = asToken(operator);
+ var operatorKind = operatorToken.kind;
+ node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
+ node.operatorToken = operatorToken;
+ node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
+ node.transformFlags |=
+ propagateChildFlags(node.left) |
+ propagateChildFlags(node.operatorToken) |
+ propagateChildFlags(node.right);
+ if (operatorKind === 60 /* QuestionQuestionToken */) {
+ node.transformFlags |= 16 /* ContainsES2020 */;
+ }
+ else if (operatorKind === 63 /* EqualsToken */) {
+ if (ts.isObjectLiteralExpression(node.left)) {
+ node.transformFlags |=
+ 512 /* ContainsES2015 */ |
+ 64 /* ContainsES2018 */ |
+ 2048 /* ContainsDestructuringAssignment */ |
+ propagateAssignmentPatternFlags(node.left);
+ }
+ else if (ts.isArrayLiteralExpression(node.left)) {
+ node.transformFlags |=
+ 512 /* ContainsES2015 */ |
+ 2048 /* ContainsDestructuringAssignment */ |
+ propagateAssignmentPatternFlags(node.left);
+ }
+ }
+ else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 67 /* AsteriskAsteriskEqualsToken */) {
+ node.transformFlags |= 256 /* ContainsES2016 */;
+ }
+ else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
+ node.transformFlags |= 8 /* ContainsES2021 */;
+ }
+ return node;
+ }
+ function propagateAssignmentPatternFlags(node) {
+ if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */)
+ return 32768 /* ContainsObjectRestOrSpread */;
+ if (node.transformFlags & 64 /* ContainsES2018 */) {
+ // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
+ // will not be correctly interpreted by the ES2018 transformer
+ for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) {
+ var element = _a[_i];
+ var target = ts.getTargetOfBindingOrAssignmentElement(element);
+ if (target && ts.isAssignmentPattern(target)) {
+ if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
+ return 32768 /* ContainsObjectRestOrSpread */;
+ }
+ if (target.transformFlags & 64 /* ContainsES2018 */) {
+ var flags_1 = propagateAssignmentPatternFlags(target);
+ if (flags_1)
+ return flags_1;
+ }
+ }
+ }
+ }
+ return 0 /* None */;
+ }
+ // @api
+ function updateBinaryExpression(node, left, operator, right) {
+ return node.left !== left
+ || node.operatorToken !== operator
+ || node.right !== right
+ ? update(createBinaryExpression(left, operator, right), node)
+ : node;
+ }
+ // @api
+ function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
+ var node = createBaseExpression(221 /* ConditionalExpression */);
+ node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
+ node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */);
+ node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
+ node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(58 /* ColonToken */);
+ node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
+ node.transformFlags |=
+ propagateChildFlags(node.condition) |
+ propagateChildFlags(node.questionToken) |
+ propagateChildFlags(node.whenTrue) |
+ propagateChildFlags(node.colonToken) |
+ propagateChildFlags(node.whenFalse);
+ return node;
+ }
+ // @api
+ function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
+ return node.condition !== condition
+ || node.questionToken !== questionToken
+ || node.whenTrue !== whenTrue
+ || node.colonToken !== colonToken
+ || node.whenFalse !== whenFalse
+ ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node)
+ : node;
+ }
+ // @api
+ function createTemplateExpression(head, templateSpans) {
+ var node = createBaseExpression(222 /* TemplateExpression */);
+ node.head = head;
+ node.templateSpans = createNodeArray(templateSpans);
+ node.transformFlags |=
+ propagateChildFlags(node.head) |
+ propagateChildrenFlags(node.templateSpans) |
+ 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function updateTemplateExpression(node, head, templateSpans) {
+ return node.head !== head
+ || node.templateSpans !== templateSpans
+ ? update(createTemplateExpression(head, templateSpans), node)
+ : node;
+ }
+ function createTemplateLiteralLikeNodeChecked(kind, text, rawText, templateFlags) {
+ if (templateFlags === void 0) { templateFlags = 0 /* None */; }
+ ts.Debug.assert(!(templateFlags & ~2048 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
+ // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`.
+ // eslint-disable-next-line no-undef-init
+ var cooked = undefined;
+ if (rawText !== undefined && rawText !== text) {
+ cooked = getCookedText(kind, rawText);
+ if (typeof cooked === "object") {
+ return ts.Debug.fail("Invalid raw text");
+ }
+ }
+ if (text === undefined) {
+ if (cooked === undefined) {
+ return ts.Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
+ }
+ text = cooked;
+ }
+ else if (cooked !== undefined) {
+ ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
+ }
+ return createTemplateLiteralLikeNode(kind, text, rawText, templateFlags);
+ }
+ // @api
+ function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
+ var node = createBaseToken(kind);
+ node.text = text;
+ node.rawText = rawText;
+ node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */;
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ if (node.templateFlags) {
+ node.transformFlags |= 64 /* ContainsES2018 */;
+ }
+ return node;
+ }
+ // @api
+ function createTemplateHead(text, rawText, templateFlags) {
+ return createTemplateLiteralLikeNodeChecked(15 /* TemplateHead */, text, rawText, templateFlags);
+ }
+ // @api
+ function createTemplateMiddle(text, rawText, templateFlags) {
+ return createTemplateLiteralLikeNodeChecked(16 /* TemplateMiddle */, text, rawText, templateFlags);
+ }
+ // @api
+ function createTemplateTail(text, rawText, templateFlags) {
+ return createTemplateLiteralLikeNodeChecked(17 /* TemplateTail */, text, rawText, templateFlags);
+ }
+ // @api
+ function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
+ return createTemplateLiteralLikeNodeChecked(14 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
+ }
+ // @api
+ function createYieldExpression(asteriskToken, expression) {
+ ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
+ var node = createBaseExpression(223 /* YieldExpression */);
+ node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
+ node.asteriskToken = asteriskToken;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.asteriskToken) |
+ 512 /* ContainsES2015 */ |
+ 64 /* ContainsES2018 */ |
+ 524288 /* ContainsYield */;
+ return node;
+ }
+ // @api
+ function updateYieldExpression(node, asteriskToken, expression) {
+ return node.expression !== expression
+ || node.asteriskToken !== asteriskToken
+ ? update(createYieldExpression(asteriskToken, expression), node)
+ : node;
+ }
+ // @api
+ function createSpreadElement(expression) {
+ var node = createBaseExpression(224 /* SpreadElement */);
+ node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 512 /* ContainsES2015 */ |
+ 16384 /* ContainsRestOrSpread */;
+ return node;
+ }
+ // @api
+ function updateSpreadElement(node, expression) {
+ return node.expression !== expression
+ ? update(createSpreadElement(expression), node)
+ : node;
+ }
+ // @api
+ function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ var node = createBaseClassLikeDeclaration(225 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members);
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.heritageClauses !== heritageClauses
+ || node.members !== members
+ ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
+ : node;
+ }
+ // @api
+ function createOmittedExpression() {
+ return createBaseExpression(226 /* OmittedExpression */);
+ }
+ // @api
+ function createExpressionWithTypeArguments(expression, typeArguments) {
+ var node = createBaseNode(227 /* ExpressionWithTypeArguments */);
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildrenFlags(node.typeArguments) |
+ 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function updateExpressionWithTypeArguments(node, expression, typeArguments) {
+ return node.expression !== expression
+ || node.typeArguments !== typeArguments
+ ? update(createExpressionWithTypeArguments(expression, typeArguments), node)
+ : node;
+ }
+ // @api
+ function createAsExpression(expression, type) {
+ var node = createBaseExpression(228 /* AsExpression */);
+ node.expression = expression;
+ node.type = type;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.type) |
+ 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateAsExpression(node, expression, type) {
+ return node.expression !== expression
+ || node.type !== type
+ ? update(createAsExpression(expression, type), node)
+ : node;
+ }
+ // @api
+ function createNonNullExpression(expression) {
+ var node = createBaseExpression(229 /* NonNullExpression */);
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateNonNullExpression(node, expression) {
+ if (ts.isNonNullChain(node)) {
+ return updateNonNullChain(node, expression);
+ }
+ return node.expression !== expression
+ ? update(createNonNullExpression(expression), node)
+ : node;
+ }
+ // @api
+ function createNonNullChain(expression) {
+ var node = createBaseExpression(229 /* NonNullExpression */);
+ node.flags |= 32 /* OptionalChain */;
+ node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateNonNullChain(node, expression) {
+ ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
+ return node.expression !== expression
+ ? update(createNonNullChain(expression), node)
+ : node;
+ }
+ // @api
+ function createMetaProperty(keywordToken, name) {
+ var node = createBaseExpression(230 /* MetaProperty */);
+ node.keywordToken = keywordToken;
+ node.name = name;
+ node.transformFlags |= propagateChildFlags(node.name);
+ switch (keywordToken) {
+ case 103 /* NewKeyword */:
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ break;
+ case 100 /* ImportKeyword */:
+ node.transformFlags |= 4 /* ContainsESNext */;
+ break;
+ default:
+ return ts.Debug.assertNever(keywordToken);
+ }
+ return node;
+ }
+ // @api
+ function updateMetaProperty(node, name) {
+ return node.name !== name
+ ? update(createMetaProperty(node.keywordToken, name), node)
+ : node;
+ }
+ //
+ // Misc
+ //
+ // @api
+ function createTemplateSpan(expression, literal) {
+ var node = createBaseNode(232 /* TemplateSpan */);
+ node.expression = expression;
+ node.literal = literal;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.literal) |
+ 512 /* ContainsES2015 */;
+ return node;
+ }
+ // @api
+ function updateTemplateSpan(node, expression, literal) {
+ return node.expression !== expression
+ || node.literal !== literal
+ ? update(createTemplateSpan(expression, literal), node)
+ : node;
+ }
+ // @api
+ function createSemicolonClassElement() {
+ var node = createBaseNode(233 /* SemicolonClassElement */);
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ return node;
+ }
+ //
+ // Element
+ //
+ // @api
+ function createBlock(statements, multiLine) {
+ var node = createBaseNode(234 /* Block */);
+ node.statements = createNodeArray(statements);
+ node.multiLine = multiLine;
+ node.transformFlags |= propagateChildrenFlags(node.statements);
+ return node;
+ }
+ // @api
+ function updateBlock(node, statements) {
+ return node.statements !== statements
+ ? update(createBlock(statements, node.multiLine), node)
+ : node;
+ }
+ // @api
+ function createVariableStatement(modifiers, declarationList) {
+ var node = createBaseDeclaration(236 /* VariableStatement */, /*decorators*/ undefined, modifiers);
+ node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
+ node.transformFlags |=
+ propagateChildFlags(node.declarationList);
+ if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ }
+ return node;
+ }
+ // @api
+ function updateVariableStatement(node, modifiers, declarationList) {
+ return node.modifiers !== modifiers
+ || node.declarationList !== declarationList
+ ? update(createVariableStatement(modifiers, declarationList), node)
+ : node;
+ }
+ // @api
+ function createEmptyStatement() {
+ return createBaseNode(235 /* EmptyStatement */);
+ }
+ // @api
+ function createExpressionStatement(expression) {
+ var node = createBaseNode(237 /* ExpressionStatement */);
+ node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
+ node.transformFlags |= propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateExpressionStatement(node, expression) {
+ return node.expression !== expression
+ ? update(createExpressionStatement(expression), node)
+ : node;
+ }
+ // @api
+ function createIfStatement(expression, thenStatement, elseStatement) {
+ var node = createBaseNode(238 /* IfStatement */);
+ node.expression = expression;
+ node.thenStatement = asEmbeddedStatement(thenStatement);
+ node.elseStatement = asEmbeddedStatement(elseStatement);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.thenStatement) |
+ propagateChildFlags(node.elseStatement);
+ return node;
+ }
+ // @api
+ function updateIfStatement(node, expression, thenStatement, elseStatement) {
+ return node.expression !== expression
+ || node.thenStatement !== thenStatement
+ || node.elseStatement !== elseStatement
+ ? update(createIfStatement(expression, thenStatement, elseStatement), node)
+ : node;
+ }
+ // @api
+ function createDoStatement(statement, expression) {
+ var node = createBaseNode(239 /* DoStatement */);
+ node.statement = asEmbeddedStatement(statement);
+ node.expression = expression;
+ node.transformFlags |=
+ propagateChildFlags(node.statement) |
+ propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateDoStatement(node, statement, expression) {
+ return node.statement !== statement
+ || node.expression !== expression
+ ? update(createDoStatement(statement, expression), node)
+ : node;
+ }
+ // @api
+ function createWhileStatement(expression, statement) {
+ var node = createBaseNode(240 /* WhileStatement */);
+ node.expression = expression;
+ node.statement = asEmbeddedStatement(statement);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.statement);
+ return node;
+ }
+ // @api
+ function updateWhileStatement(node, expression, statement) {
+ return node.expression !== expression
+ || node.statement !== statement
+ ? update(createWhileStatement(expression, statement), node)
+ : node;
+ }
+ // @api
+ function createForStatement(initializer, condition, incrementor, statement) {
+ var node = createBaseNode(241 /* ForStatement */);
+ node.initializer = initializer;
+ node.condition = condition;
+ node.incrementor = incrementor;
+ node.statement = asEmbeddedStatement(statement);
+ node.transformFlags |=
+ propagateChildFlags(node.initializer) |
+ propagateChildFlags(node.condition) |
+ propagateChildFlags(node.incrementor) |
+ propagateChildFlags(node.statement);
+ return node;
+ }
+ // @api
+ function updateForStatement(node, initializer, condition, incrementor, statement) {
+ return node.initializer !== initializer
+ || node.condition !== condition
+ || node.incrementor !== incrementor
+ || node.statement !== statement
+ ? update(createForStatement(initializer, condition, incrementor, statement), node)
+ : node;
+ }
+ // @api
+ function createForInStatement(initializer, expression, statement) {
+ var node = createBaseNode(242 /* ForInStatement */);
+ node.initializer = initializer;
+ node.expression = expression;
+ node.statement = asEmbeddedStatement(statement);
+ node.transformFlags |=
+ propagateChildFlags(node.initializer) |
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.statement);
+ return node;
+ }
+ // @api
+ function updateForInStatement(node, initializer, expression, statement) {
+ return node.initializer !== initializer
+ || node.expression !== expression
+ || node.statement !== statement
+ ? update(createForInStatement(initializer, expression, statement), node)
+ : node;
+ }
+ // @api
+ function createForOfStatement(awaitModifier, initializer, expression, statement) {
+ var node = createBaseNode(243 /* ForOfStatement */);
+ node.awaitModifier = awaitModifier;
+ node.initializer = initializer;
+ node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
+ node.statement = asEmbeddedStatement(statement);
+ node.transformFlags |=
+ propagateChildFlags(node.awaitModifier) |
+ propagateChildFlags(node.initializer) |
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.statement) |
+ 512 /* ContainsES2015 */;
+ if (awaitModifier)
+ node.transformFlags |= 64 /* ContainsES2018 */;
+ return node;
+ }
+ // @api
+ function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
+ return node.awaitModifier !== awaitModifier
+ || node.initializer !== initializer
+ || node.expression !== expression
+ || node.statement !== statement
+ ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node)
+ : node;
+ }
+ // @api
+ function createContinueStatement(label) {
+ var node = createBaseNode(244 /* ContinueStatement */);
+ node.label = asName(label);
+ node.transformFlags |=
+ propagateChildFlags(node.label) |
+ 2097152 /* ContainsHoistedDeclarationOrCompletion */;
+ return node;
+ }
+ // @api
+ function updateContinueStatement(node, label) {
+ return node.label !== label
+ ? update(createContinueStatement(label), node)
+ : node;
+ }
+ // @api
+ function createBreakStatement(label) {
+ var node = createBaseNode(245 /* BreakStatement */);
+ node.label = asName(label);
+ node.transformFlags |=
+ propagateChildFlags(node.label) |
+ 2097152 /* ContainsHoistedDeclarationOrCompletion */;
+ return node;
+ }
+ // @api
+ function updateBreakStatement(node, label) {
+ return node.label !== label
+ ? update(createBreakStatement(label), node)
+ : node;
+ }
+ // @api
+ function createReturnStatement(expression) {
+ var node = createBaseNode(246 /* ReturnStatement */);
+ node.expression = expression;
+ // return in an ES2018 async generator must be awaited
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 64 /* ContainsES2018 */ |
+ 2097152 /* ContainsHoistedDeclarationOrCompletion */;
+ return node;
+ }
+ // @api
+ function updateReturnStatement(node, expression) {
+ return node.expression !== expression
+ ? update(createReturnStatement(expression), node)
+ : node;
+ }
+ // @api
+ function createWithStatement(expression, statement) {
+ var node = createBaseNode(247 /* WithStatement */);
+ node.expression = expression;
+ node.statement = asEmbeddedStatement(statement);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.statement);
+ return node;
+ }
+ // @api
+ function updateWithStatement(node, expression, statement) {
+ return node.expression !== expression
+ || node.statement !== statement
+ ? update(createWithStatement(expression, statement), node)
+ : node;
+ }
+ // @api
+ function createSwitchStatement(expression, caseBlock) {
+ var node = createBaseNode(248 /* SwitchStatement */);
+ node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
+ node.caseBlock = caseBlock;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.caseBlock);
+ return node;
+ }
+ // @api
+ function updateSwitchStatement(node, expression, caseBlock) {
+ return node.expression !== expression
+ || node.caseBlock !== caseBlock
+ ? update(createSwitchStatement(expression, caseBlock), node)
+ : node;
+ }
+ // @api
+ function createLabeledStatement(label, statement) {
+ var node = createBaseNode(249 /* LabeledStatement */);
+ node.label = asName(label);
+ node.statement = asEmbeddedStatement(statement);
+ node.transformFlags |=
+ propagateChildFlags(node.label) |
+ propagateChildFlags(node.statement);
+ return node;
+ }
+ // @api
+ function updateLabeledStatement(node, label, statement) {
+ return node.label !== label
+ || node.statement !== statement
+ ? update(createLabeledStatement(label, statement), node)
+ : node;
+ }
+ // @api
+ function createThrowStatement(expression) {
+ var node = createBaseNode(250 /* ThrowStatement */);
+ node.expression = expression;
+ node.transformFlags |= propagateChildFlags(node.expression);
+ return node;
+ }
+ // @api
+ function updateThrowStatement(node, expression) {
+ return node.expression !== expression
+ ? update(createThrowStatement(expression), node)
+ : node;
+ }
+ // @api
+ function createTryStatement(tryBlock, catchClause, finallyBlock) {
+ var node = createBaseNode(251 /* TryStatement */);
+ node.tryBlock = tryBlock;
+ node.catchClause = catchClause;
+ node.finallyBlock = finallyBlock;
+ node.transformFlags |=
+ propagateChildFlags(node.tryBlock) |
+ propagateChildFlags(node.catchClause) |
+ propagateChildFlags(node.finallyBlock);
+ return node;
+ }
+ // @api
+ function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
+ return node.tryBlock !== tryBlock
+ || node.catchClause !== catchClause
+ || node.finallyBlock !== finallyBlock
+ ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node)
+ : node;
+ }
+ // @api
+ function createDebuggerStatement() {
+ return createBaseNode(252 /* DebuggerStatement */);
+ }
+ // @api
+ function createVariableDeclaration(name, exclamationToken, type, initializer) {
+ var node = createBaseVariableLikeDeclaration(253 /* VariableDeclaration */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
+ node.exclamationToken = exclamationToken;
+ node.transformFlags |= propagateChildFlags(node.exclamationToken);
+ if (exclamationToken) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ return node;
+ }
+ // @api
+ function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
+ return node.name !== name
+ || node.type !== type
+ || node.exclamationToken !== exclamationToken
+ || node.initializer !== initializer
+ ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node)
+ : node;
+ }
+ // @api
+ function createVariableDeclarationList(declarations, flags) {
+ if (flags === void 0) { flags = 0 /* None */; }
+ var node = createBaseNode(254 /* VariableDeclarationList */);
+ node.flags |= flags & 3 /* BlockScoped */;
+ node.declarations = createNodeArray(declarations);
+ node.transformFlags |=
+ propagateChildrenFlags(node.declarations) |
+ 2097152 /* ContainsHoistedDeclarationOrCompletion */;
+ if (flags & 3 /* BlockScoped */) {
+ node.transformFlags |=
+ 512 /* ContainsES2015 */ |
+ 131072 /* ContainsBlockScopedBinding */;
+ }
+ return node;
+ }
+ // @api
+ function updateVariableDeclarationList(node, declarations) {
+ return node.declarations !== declarations
+ ? update(createVariableDeclarationList(declarations, node.flags), node)
+ : node;
+ }
+ // @api
+ function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ var node = createBaseFunctionLikeDeclaration(255 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
+ node.asteriskToken = asteriskToken;
+ if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ }
+ else {
+ node.transformFlags |=
+ propagateChildFlags(node.asteriskToken) |
+ 2097152 /* ContainsHoistedDeclarationOrCompletion */;
+ if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
+ if (node.asteriskToken) {
+ node.transformFlags |= 64 /* ContainsES2018 */;
+ }
+ else {
+ node.transformFlags |= 128 /* ContainsES2017 */;
+ }
+ }
+ else if (node.asteriskToken) {
+ node.transformFlags |= 1024 /* ContainsGenerator */;
+ }
+ }
+ return node;
+ }
+ // @api
+ function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.asteriskToken !== asteriskToken
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
+ : node;
+ }
+ // @api
+ function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ var node = createBaseClassLikeDeclaration(256 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members);
+ if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ }
+ else {
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ }
+ return node;
+ }
+ // @api
+ function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.heritageClauses !== heritageClauses
+ || node.members !== members
+ ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
+ : node;
+ }
+ // @api
+ function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ var node = createBaseInterfaceOrClassLikeDeclaration(257 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses);
+ node.members = createNodeArray(members);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.heritageClauses !== heritageClauses
+ || node.members !== members
+ ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
+ : node;
+ }
+ // @api
+ function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
+ var node = createBaseGenericNamedDeclaration(258 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters);
+ node.type = type;
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.type !== type
+ ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
+ : node;
+ }
+ // @api
+ function createEnumDeclaration(decorators, modifiers, name, members) {
+ var node = createBaseNamedDeclaration(259 /* EnumDeclaration */, decorators, modifiers, name);
+ node.members = createNodeArray(members);
+ node.transformFlags |=
+ propagateChildrenFlags(node.members) |
+ 1 /* ContainsTypeScript */;
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await`
+ return node;
+ }
+ // @api
+ function updateEnumDeclaration(node, decorators, modifiers, name, members) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.members !== members
+ ? update(createEnumDeclaration(decorators, modifiers, name, members), node)
+ : node;
+ }
+ // @api
+ function createModuleDeclaration(decorators, modifiers, name, body, flags) {
+ if (flags === void 0) { flags = 0 /* None */; }
+ var node = createBaseDeclaration(260 /* ModuleDeclaration */, decorators, modifiers);
+ node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
+ node.name = name;
+ node.body = body;
+ if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ }
+ else {
+ node.transformFlags |=
+ propagateChildFlags(node.name) |
+ propagateChildFlags(node.body) |
+ 1 /* ContainsTypeScript */;
+ }
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`.
+ return node;
+ }
+ // @api
+ function updateModuleDeclaration(node, decorators, modifiers, name, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.body !== body
+ ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
+ : node;
+ }
+ // @api
+ function createModuleBlock(statements) {
+ var node = createBaseNode(261 /* ModuleBlock */);
+ node.statements = createNodeArray(statements);
+ node.transformFlags |= propagateChildrenFlags(node.statements);
+ return node;
+ }
+ // @api
+ function updateModuleBlock(node, statements) {
+ return node.statements !== statements
+ ? update(createModuleBlock(statements), node)
+ : node;
+ }
+ // @api
+ function createCaseBlock(clauses) {
+ var node = createBaseNode(262 /* CaseBlock */);
+ node.clauses = createNodeArray(clauses);
+ node.transformFlags |= propagateChildrenFlags(node.clauses);
+ return node;
+ }
+ // @api
+ function updateCaseBlock(node, clauses) {
+ return node.clauses !== clauses
+ ? update(createCaseBlock(clauses), node)
+ : node;
+ }
+ // @api
+ function createNamespaceExportDeclaration(name) {
+ var node = createBaseNamedDeclaration(263 /* NamespaceExportDeclaration */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, name);
+ node.transformFlags = 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateNamespaceExportDeclaration(node, name) {
+ return node.name !== name
+ ? update(createNamespaceExportDeclaration(name), node)
+ : node;
+ }
+ // @api
+ function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) {
+ var node = createBaseNamedDeclaration(264 /* ImportEqualsDeclaration */, decorators, modifiers, name);
+ node.isTypeOnly = isTypeOnly;
+ node.moduleReference = moduleReference;
+ node.transformFlags |= propagateChildFlags(node.moduleReference);
+ if (!ts.isExternalModuleReference(node.moduleReference))
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.isTypeOnly !== isTypeOnly
+ || node.name !== name
+ || node.moduleReference !== moduleReference
+ ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node)
+ : node;
+ }
+ // @api
+ function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) {
+ var node = createBaseDeclaration(265 /* ImportDeclaration */, decorators, modifiers);
+ node.importClause = importClause;
+ node.moduleSpecifier = moduleSpecifier;
+ node.assertClause = assertClause;
+ node.transformFlags |=
+ propagateChildFlags(node.importClause) |
+ propagateChildFlags(node.moduleSpecifier);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.importClause !== importClause
+ || node.moduleSpecifier !== moduleSpecifier
+ || node.assertClause !== assertClause
+ ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node)
+ : node;
+ }
+ // @api
+ function createImportClause(isTypeOnly, name, namedBindings) {
+ var node = createBaseNode(266 /* ImportClause */);
+ node.isTypeOnly = isTypeOnly;
+ node.name = name;
+ node.namedBindings = namedBindings;
+ node.transformFlags |=
+ propagateChildFlags(node.name) |
+ propagateChildFlags(node.namedBindings);
+ if (isTypeOnly) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateImportClause(node, isTypeOnly, name, namedBindings) {
+ return node.isTypeOnly !== isTypeOnly
+ || node.name !== name
+ || node.namedBindings !== namedBindings
+ ? update(createImportClause(isTypeOnly, name, namedBindings), node)
+ : node;
+ }
+ // @api
+ function createAssertClause(elements, multiLine) {
+ var node = createBaseNode(292 /* AssertClause */);
+ node.elements = elements;
+ node.multiLine = multiLine;
+ node.transformFlags |= 4 /* ContainsESNext */;
+ return node;
+ }
+ // @api
+ function updateAssertClause(node, elements, multiLine) {
+ return node.elements !== elements
+ || node.multiLine !== multiLine
+ ? update(createAssertClause(elements, multiLine), node)
+ : node;
+ }
+ // @api
+ function createAssertEntry(name, value) {
+ var node = createBaseNode(293 /* AssertEntry */);
+ node.name = name;
+ node.value = value;
+ node.transformFlags |= 4 /* ContainsESNext */;
+ return node;
+ }
+ // @api
+ function updateAssertEntry(node, name, value) {
+ return node.name !== name
+ || node.value !== value
+ ? update(createAssertEntry(name, value), node)
+ : node;
+ }
+ // @api
+ function createNamespaceImport(name) {
+ var node = createBaseNode(267 /* NamespaceImport */);
+ node.name = name;
+ node.transformFlags |= propagateChildFlags(node.name);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateNamespaceImport(node, name) {
+ return node.name !== name
+ ? update(createNamespaceImport(name), node)
+ : node;
+ }
+ // @api
+ function createNamespaceExport(name) {
+ var node = createBaseNode(273 /* NamespaceExport */);
+ node.name = name;
+ node.transformFlags |=
+ propagateChildFlags(node.name) |
+ 4 /* ContainsESNext */;
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateNamespaceExport(node, name) {
+ return node.name !== name
+ ? update(createNamespaceExport(name), node)
+ : node;
+ }
+ // @api
+ function createNamedImports(elements) {
+ var node = createBaseNode(268 /* NamedImports */);
+ node.elements = createNodeArray(elements);
+ node.transformFlags |= propagateChildrenFlags(node.elements);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateNamedImports(node, elements) {
+ return node.elements !== elements
+ ? update(createNamedImports(elements), node)
+ : node;
+ }
+ // @api
+ function createImportSpecifier(isTypeOnly, propertyName, name) {
+ var node = createBaseNode(269 /* ImportSpecifier */);
+ node.isTypeOnly = isTypeOnly;
+ node.propertyName = propertyName;
+ node.name = name;
+ node.transformFlags |=
+ propagateChildFlags(node.propertyName) |
+ propagateChildFlags(node.name);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateImportSpecifier(node, isTypeOnly, propertyName, name) {
+ return node.isTypeOnly !== isTypeOnly
+ || node.propertyName !== propertyName
+ || node.name !== name
+ ? update(createImportSpecifier(isTypeOnly, propertyName, name), node)
+ : node;
+ }
+ // @api
+ function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
+ var node = createBaseDeclaration(270 /* ExportAssignment */, decorators, modifiers);
+ node.isExportEquals = isExportEquals;
+ node.expression = isExportEquals
+ ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* EqualsToken */, /*leftSide*/ undefined, expression)
+ : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
+ node.transformFlags |= propagateChildFlags(node.expression);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateExportAssignment(node, decorators, modifiers, expression) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.expression !== expression
+ ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
+ : node;
+ }
+ // @api
+ function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) {
+ var node = createBaseDeclaration(271 /* ExportDeclaration */, decorators, modifiers);
+ node.isTypeOnly = isTypeOnly;
+ node.exportClause = exportClause;
+ node.moduleSpecifier = moduleSpecifier;
+ node.assertClause = assertClause;
+ node.transformFlags |=
+ propagateChildFlags(node.exportClause) |
+ propagateChildFlags(node.moduleSpecifier);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.isTypeOnly !== isTypeOnly
+ || node.exportClause !== exportClause
+ || node.moduleSpecifier !== moduleSpecifier
+ || node.assertClause !== assertClause
+ ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node)
+ : node;
+ }
+ // @api
+ function createNamedExports(elements) {
+ var node = createBaseNode(272 /* NamedExports */);
+ node.elements = createNodeArray(elements);
+ node.transformFlags |= propagateChildrenFlags(node.elements);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateNamedExports(node, elements) {
+ return node.elements !== elements
+ ? update(createNamedExports(elements), node)
+ : node;
+ }
+ // @api
+ function createExportSpecifier(isTypeOnly, propertyName, name) {
+ var node = createBaseNode(274 /* ExportSpecifier */);
+ node.isTypeOnly = isTypeOnly;
+ node.propertyName = asName(propertyName);
+ node.name = asName(name);
+ node.transformFlags |=
+ propagateChildFlags(node.propertyName) |
+ propagateChildFlags(node.name);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateExportSpecifier(node, isTypeOnly, propertyName, name) {
+ return node.isTypeOnly !== isTypeOnly
+ || node.propertyName !== propertyName
+ || node.name !== name
+ ? update(createExportSpecifier(isTypeOnly, propertyName, name), node)
+ : node;
+ }
+ // @api
+ function createMissingDeclaration() {
+ var node = createBaseDeclaration(275 /* MissingDeclaration */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined);
+ return node;
+ }
+ //
+ // Module references
+ //
+ // @api
+ function createExternalModuleReference(expression) {
+ var node = createBaseNode(276 /* ExternalModuleReference */);
+ node.expression = expression;
+ node.transformFlags |= propagateChildFlags(node.expression);
+ node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
+ return node;
+ }
+ // @api
+ function updateExternalModuleReference(node, expression) {
+ return node.expression !== expression
+ ? update(createExternalModuleReference(expression), node)
+ : node;
+ }
+ //
+ // JSDoc
+ //
+ // @api
+ // createJSDocAllType
+ // createJSDocUnknownType
+ function createJSDocPrimaryTypeWorker(kind) {
+ return createBaseNode(kind);
+ }
+ // @api
+ // createJSDocNonNullableType
+ // createJSDocNullableType
+ // createJSDocOptionalType
+ // createJSDocVariadicType
+ // createJSDocNamepathType
+ function createJSDocUnaryTypeWorker(kind, type) {
+ var node = createBaseNode(kind);
+ node.type = type;
+ return node;
+ }
+ // @api
+ // updateJSDocNonNullableType
+ // updateJSDocNullableType
+ // updateJSDocOptionalType
+ // updateJSDocVariadicType
+ // updateJSDocNamepathType
+ function updateJSDocUnaryTypeWorker(kind, node, type) {
+ return node.type !== type
+ ? update(createJSDocUnaryTypeWorker(kind, type), node)
+ : node;
+ }
+ // @api
+ function createJSDocFunctionType(parameters, type) {
+ var node = createBaseSignatureDeclaration(315 /* JSDocFunctionType */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, parameters, type);
+ return node;
+ }
+ // @api
+ function updateJSDocFunctionType(node, parameters, type) {
+ return node.parameters !== parameters
+ || node.type !== type
+ ? update(createJSDocFunctionType(parameters, type), node)
+ : node;
+ }
+ // @api
+ function createJSDocTypeLiteral(propertyTags, isArrayType) {
+ if (isArrayType === void 0) { isArrayType = false; }
+ var node = createBaseNode(320 /* JSDocTypeLiteral */);
+ node.jsDocPropertyTags = asNodeArray(propertyTags);
+ node.isArrayType = isArrayType;
+ return node;
+ }
+ // @api
+ function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
+ return node.jsDocPropertyTags !== propertyTags
+ || node.isArrayType !== isArrayType
+ ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node)
+ : node;
+ }
+ // @api
+ function createJSDocTypeExpression(type) {
+ var node = createBaseNode(307 /* JSDocTypeExpression */);
+ node.type = type;
+ return node;
+ }
+ // @api
+ function updateJSDocTypeExpression(node, type) {
+ return node.type !== type
+ ? update(createJSDocTypeExpression(type), node)
+ : node;
+ }
+ // @api
+ function createJSDocSignature(typeParameters, parameters, type) {
+ var node = createBaseNode(321 /* JSDocSignature */);
+ node.typeParameters = asNodeArray(typeParameters);
+ node.parameters = createNodeArray(parameters);
+ node.type = type;
+ return node;
+ }
+ // @api
+ function updateJSDocSignature(node, typeParameters, parameters, type) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? update(createJSDocSignature(typeParameters, parameters, type), node)
+ : node;
+ }
+ function getDefaultTagName(node) {
+ var defaultTagName = getDefaultTagNameForKind(node.kind);
+ return node.tagName.escapedText === ts.escapeLeadingUnderscores(defaultTagName)
+ ? node.tagName
+ : createIdentifier(defaultTagName);
+ }
+ // @api
+ function createBaseJSDocTag(kind, tagName, comment) {
+ var node = createBaseNode(kind);
+ node.tagName = tagName;
+ node.comment = comment;
+ return node;
+ }
+ // @api
+ function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
+ var node = createBaseJSDocTag(342 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment);
+ node.constraint = constraint;
+ node.typeParameters = createNodeArray(typeParameters);
+ return node;
+ }
+ // @api
+ function updateJSDocTemplateTag(node, tagName, constraint, typeParameters, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.constraint !== constraint
+ || node.typeParameters !== typeParameters
+ || node.comment !== comment
+ ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
+ var node = createBaseJSDocTag(343 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment);
+ node.typeExpression = typeExpression;
+ node.fullName = fullName;
+ node.name = ts.getJSDocTypeAliasName(fullName);
+ return node;
+ }
+ // @api
+ function updateJSDocTypedefTag(node, tagName, typeExpression, fullName, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.typeExpression !== typeExpression
+ || node.fullName !== fullName
+ || node.comment !== comment
+ ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
+ var node = createBaseJSDocTag(338 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment);
+ node.typeExpression = typeExpression;
+ node.name = name;
+ node.isNameFirst = !!isNameFirst;
+ node.isBracketed = isBracketed;
+ return node;
+ }
+ // @api
+ function updateJSDocParameterTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.name !== name
+ || node.isBracketed !== isBracketed
+ || node.typeExpression !== typeExpression
+ || node.isNameFirst !== isNameFirst
+ || node.comment !== comment
+ ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
+ var node = createBaseJSDocTag(345 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment);
+ node.typeExpression = typeExpression;
+ node.name = name;
+ node.isNameFirst = !!isNameFirst;
+ node.isBracketed = isBracketed;
+ return node;
+ }
+ // @api
+ function updateJSDocPropertyTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.name !== name
+ || node.isBracketed !== isBracketed
+ || node.typeExpression !== typeExpression
+ || node.isNameFirst !== isNameFirst
+ || node.comment !== comment
+ ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
+ var node = createBaseJSDocTag(336 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment);
+ node.typeExpression = typeExpression;
+ node.fullName = fullName;
+ node.name = ts.getJSDocTypeAliasName(fullName);
+ return node;
+ }
+ // @api
+ function updateJSDocCallbackTag(node, tagName, typeExpression, fullName, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.typeExpression !== typeExpression
+ || node.fullName !== fullName
+ || node.comment !== comment
+ ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocAugmentsTag(tagName, className, comment) {
+ var node = createBaseJSDocTag(326 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment);
+ node.class = className;
+ return node;
+ }
+ // @api
+ function updateJSDocAugmentsTag(node, tagName, className, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.class !== className
+ || node.comment !== comment
+ ? update(createJSDocAugmentsTag(tagName, className, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocImplementsTag(tagName, className, comment) {
+ var node = createBaseJSDocTag(327 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment);
+ node.class = className;
+ return node;
+ }
+ // @api
+ function createJSDocSeeTag(tagName, name, comment) {
+ var node = createBaseJSDocTag(344 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment);
+ node.name = name;
+ return node;
+ }
+ // @api
+ function updateJSDocSeeTag(node, tagName, name, comment) {
+ return node.tagName !== tagName
+ || node.name !== name
+ || node.comment !== comment
+ ? update(createJSDocSeeTag(tagName, name, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocNameReference(name) {
+ var node = createBaseNode(308 /* JSDocNameReference */);
+ node.name = name;
+ return node;
+ }
+ // @api
+ function updateJSDocNameReference(node, name) {
+ return node.name !== name
+ ? update(createJSDocNameReference(name), node)
+ : node;
+ }
+ // @api
+ function createJSDocMemberName(left, right) {
+ var node = createBaseNode(309 /* JSDocMemberName */);
+ node.left = left;
+ node.right = right;
+ node.transformFlags |=
+ propagateChildFlags(node.left) |
+ propagateChildFlags(node.right);
+ return node;
+ }
+ // @api
+ function updateJSDocMemberName(node, left, right) {
+ return node.left !== left
+ || node.right !== right
+ ? update(createJSDocMemberName(left, right), node)
+ : node;
+ }
+ // @api
+ function createJSDocLink(name, text) {
+ var node = createBaseNode(322 /* JSDocLink */);
+ node.name = name;
+ node.text = text;
+ return node;
+ }
+ // @api
+ function updateJSDocLink(node, name, text) {
+ return node.name !== name
+ ? update(createJSDocLink(name, text), node)
+ : node;
+ }
+ // @api
+ function createJSDocLinkCode(name, text) {
+ var node = createBaseNode(323 /* JSDocLinkCode */);
+ node.name = name;
+ node.text = text;
+ return node;
+ }
+ // @api
+ function updateJSDocLinkCode(node, name, text) {
+ return node.name !== name
+ ? update(createJSDocLinkCode(name, text), node)
+ : node;
+ }
+ // @api
+ function createJSDocLinkPlain(name, text) {
+ var node = createBaseNode(324 /* JSDocLinkPlain */);
+ node.name = name;
+ node.text = text;
+ return node;
+ }
+ // @api
+ function updateJSDocLinkPlain(node, name, text) {
+ return node.name !== name
+ ? update(createJSDocLinkPlain(name, text), node)
+ : node;
+ }
+ // @api
+ function updateJSDocImplementsTag(node, tagName, className, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.class !== className
+ || node.comment !== comment
+ ? update(createJSDocImplementsTag(tagName, className, comment), node)
+ : node;
+ }
+ // @api
+ // createJSDocAuthorTag
+ // createJSDocClassTag
+ // createJSDocPublicTag
+ // createJSDocPrivateTag
+ // createJSDocProtectedTag
+ // createJSDocReadonlyTag
+ // createJSDocDeprecatedTag
+ function createJSDocSimpleTagWorker(kind, tagName, comment) {
+ var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
+ return node;
+ }
+ // @api
+ // updateJSDocAuthorTag
+ // updateJSDocClassTag
+ // updateJSDocPublicTag
+ // updateJSDocPrivateTag
+ // updateJSDocProtectedTag
+ // updateJSDocReadonlyTag
+ // updateJSDocDeprecatedTag
+ function updateJSDocSimpleTagWorker(kind, node, tagName, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.comment !== comment
+ ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
+ node;
+ }
+ // @api
+ // createJSDocTypeTag
+ // createJSDocReturnTag
+ // createJSDocThisTag
+ // createJSDocEnumTag
+ function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
+ var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
+ node.typeExpression = typeExpression;
+ return node;
+ }
+ // @api
+ // updateJSDocTypeTag
+ // updateJSDocReturnTag
+ // updateJSDocThisTag
+ // updateJSDocEnumTag
+ function updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment) {
+ if (tagName === void 0) { tagName = getDefaultTagName(node); }
+ return node.tagName !== tagName
+ || node.typeExpression !== typeExpression
+ || node.comment !== comment
+ ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocUnknownTag(tagName, comment) {
+ var node = createBaseJSDocTag(325 /* JSDocTag */, tagName, comment);
+ return node;
+ }
+ // @api
+ function updateJSDocUnknownTag(node, tagName, comment) {
+ return node.tagName !== tagName
+ || node.comment !== comment
+ ? update(createJSDocUnknownTag(tagName, comment), node)
+ : node;
+ }
+ // @api
+ function createJSDocText(text) {
+ var node = createBaseNode(319 /* JSDocText */);
+ node.text = text;
+ return node;
+ }
+ // @api
+ function updateJSDocText(node, text) {
+ return node.text !== text
+ ? update(createJSDocText(text), node)
+ : node;
+ }
+ // @api
+ function createJSDocComment(comment, tags) {
+ var node = createBaseNode(318 /* JSDocComment */);
+ node.comment = comment;
+ node.tags = asNodeArray(tags);
+ return node;
+ }
+ // @api
+ function updateJSDocComment(node, comment, tags) {
+ return node.comment !== comment
+ || node.tags !== tags
+ ? update(createJSDocComment(comment, tags), node)
+ : node;
+ }
+ //
+ // JSX
+ //
+ // @api
+ function createJsxElement(openingElement, children, closingElement) {
+ var node = createBaseNode(277 /* JsxElement */);
+ node.openingElement = openingElement;
+ node.children = createNodeArray(children);
+ node.closingElement = closingElement;
+ node.transformFlags |=
+ propagateChildFlags(node.openingElement) |
+ propagateChildrenFlags(node.children) |
+ propagateChildFlags(node.closingElement) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxElement(node, openingElement, children, closingElement) {
+ return node.openingElement !== openingElement
+ || node.children !== children
+ || node.closingElement !== closingElement
+ ? update(createJsxElement(openingElement, children, closingElement), node)
+ : node;
+ }
+ // @api
+ function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
+ var node = createBaseNode(278 /* JsxSelfClosingElement */);
+ node.tagName = tagName;
+ node.typeArguments = asNodeArray(typeArguments);
+ node.attributes = attributes;
+ node.transformFlags |=
+ propagateChildFlags(node.tagName) |
+ propagateChildrenFlags(node.typeArguments) |
+ propagateChildFlags(node.attributes) |
+ 2 /* ContainsJsx */;
+ if (node.typeArguments) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ return node;
+ }
+ // @api
+ function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
+ return node.tagName !== tagName
+ || node.typeArguments !== typeArguments
+ || node.attributes !== attributes
+ ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
+ : node;
+ }
+ // @api
+ function createJsxOpeningElement(tagName, typeArguments, attributes) {
+ var node = createBaseNode(279 /* JsxOpeningElement */);
+ node.tagName = tagName;
+ node.typeArguments = asNodeArray(typeArguments);
+ node.attributes = attributes;
+ node.transformFlags |=
+ propagateChildFlags(node.tagName) |
+ propagateChildrenFlags(node.typeArguments) |
+ propagateChildFlags(node.attributes) |
+ 2 /* ContainsJsx */;
+ if (typeArguments) {
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ }
+ return node;
+ }
+ // @api
+ function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
+ return node.tagName !== tagName
+ || node.typeArguments !== typeArguments
+ || node.attributes !== attributes
+ ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node)
+ : node;
+ }
+ // @api
+ function createJsxClosingElement(tagName) {
+ var node = createBaseNode(280 /* JsxClosingElement */);
+ node.tagName = tagName;
+ node.transformFlags |=
+ propagateChildFlags(node.tagName) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxClosingElement(node, tagName) {
+ return node.tagName !== tagName
+ ? update(createJsxClosingElement(tagName), node)
+ : node;
+ }
+ // @api
+ function createJsxFragment(openingFragment, children, closingFragment) {
+ var node = createBaseNode(281 /* JsxFragment */);
+ node.openingFragment = openingFragment;
+ node.children = createNodeArray(children);
+ node.closingFragment = closingFragment;
+ node.transformFlags |=
+ propagateChildFlags(node.openingFragment) |
+ propagateChildrenFlags(node.children) |
+ propagateChildFlags(node.closingFragment) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxFragment(node, openingFragment, children, closingFragment) {
+ return node.openingFragment !== openingFragment
+ || node.children !== children
+ || node.closingFragment !== closingFragment
+ ? update(createJsxFragment(openingFragment, children, closingFragment), node)
+ : node;
+ }
+ // @api
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createBaseNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ node.transformFlags |= 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ // @api
+ function createJsxOpeningFragment() {
+ var node = createBaseNode(282 /* JsxOpeningFragment */);
+ node.transformFlags |= 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function createJsxJsxClosingFragment() {
+ var node = createBaseNode(283 /* JsxClosingFragment */);
+ node.transformFlags |= 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function createJsxAttribute(name, initializer) {
+ var node = createBaseNode(284 /* JsxAttribute */);
+ node.name = name;
+ node.initializer = initializer;
+ node.transformFlags |=
+ propagateChildFlags(node.name) |
+ propagateChildFlags(node.initializer) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxAttribute(node, name, initializer) {
+ return node.name !== name
+ || node.initializer !== initializer
+ ? update(createJsxAttribute(name, initializer), node)
+ : node;
+ }
+ // @api
+ function createJsxAttributes(properties) {
+ var node = createBaseNode(285 /* JsxAttributes */);
+ node.properties = createNodeArray(properties);
+ node.transformFlags |=
+ propagateChildrenFlags(node.properties) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxAttributes(node, properties) {
+ return node.properties !== properties
+ ? update(createJsxAttributes(properties), node)
+ : node;
+ }
+ // @api
+ function createJsxSpreadAttribute(expression) {
+ var node = createBaseNode(286 /* JsxSpreadAttribute */);
+ node.expression = expression;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxSpreadAttribute(node, expression) {
+ return node.expression !== expression
+ ? update(createJsxSpreadAttribute(expression), node)
+ : node;
+ }
+ // @api
+ function createJsxExpression(dotDotDotToken, expression) {
+ var node = createBaseNode(287 /* JsxExpression */);
+ node.dotDotDotToken = dotDotDotToken;
+ node.expression = expression;
+ node.transformFlags |=
+ propagateChildFlags(node.dotDotDotToken) |
+ propagateChildFlags(node.expression) |
+ 2 /* ContainsJsx */;
+ return node;
+ }
+ // @api
+ function updateJsxExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createJsxExpression(node.dotDotDotToken, expression), node)
+ : node;
+ }
+ //
+ // Clauses
+ //
+ // @api
+ function createCaseClause(expression, statements) {
+ var node = createBaseNode(288 /* CaseClause */);
+ node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
+ node.statements = createNodeArray(statements);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildrenFlags(node.statements);
+ return node;
+ }
+ // @api
+ function updateCaseClause(node, expression, statements) {
+ return node.expression !== expression
+ || node.statements !== statements
+ ? update(createCaseClause(expression, statements), node)
+ : node;
+ }
+ // @api
+ function createDefaultClause(statements) {
+ var node = createBaseNode(289 /* DefaultClause */);
+ node.statements = createNodeArray(statements);
+ node.transformFlags = propagateChildrenFlags(node.statements);
+ return node;
+ }
+ // @api
+ function updateDefaultClause(node, statements) {
+ return node.statements !== statements
+ ? update(createDefaultClause(statements), node)
+ : node;
+ }
+ // @api
+ function createHeritageClause(token, types) {
+ var node = createBaseNode(290 /* HeritageClause */);
+ node.token = token;
+ node.types = createNodeArray(types);
+ node.transformFlags |= propagateChildrenFlags(node.types);
+ switch (token) {
+ case 94 /* ExtendsKeyword */:
+ node.transformFlags |= 512 /* ContainsES2015 */;
+ break;
+ case 117 /* ImplementsKeyword */:
+ node.transformFlags |= 1 /* ContainsTypeScript */;
+ break;
+ default:
+ return ts.Debug.assertNever(token);
+ }
+ return node;
+ }
+ // @api
+ function updateHeritageClause(node, types) {
+ return node.types !== types
+ ? update(createHeritageClause(node.token, types), node)
+ : node;
+ }
+ // @api
+ function createCatchClause(variableDeclaration, block) {
+ var node = createBaseNode(291 /* CatchClause */);
+ if (typeof variableDeclaration === "string" || variableDeclaration && !ts.isVariableDeclaration(variableDeclaration)) {
+ variableDeclaration = createVariableDeclaration(variableDeclaration,
+ /*exclamationToken*/ undefined,
+ /*type*/ undefined,
+ /*initializer*/ undefined);
+ }
+ node.variableDeclaration = variableDeclaration;
+ node.block = block;
+ node.transformFlags |=
+ propagateChildFlags(node.variableDeclaration) |
+ propagateChildFlags(node.block);
+ if (!variableDeclaration)
+ node.transformFlags |= 32 /* ContainsES2019 */;
+ return node;
+ }
+ // @api
+ function updateCatchClause(node, variableDeclaration, block) {
+ return node.variableDeclaration !== variableDeclaration
+ || node.block !== block
+ ? update(createCatchClause(variableDeclaration, block), node)
+ : node;
+ }
+ //
+ // Property assignments
+ //
+ // @api
+ function createPropertyAssignment(name, initializer) {
+ var node = createBaseNamedDeclaration(294 /* PropertyAssignment */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, name);
+ node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
+ node.transformFlags |=
+ propagateChildFlags(node.name) |
+ propagateChildFlags(node.initializer);
+ return node;
+ }
+ function finishUpdatePropertyAssignment(updated, original) {
+ // copy children used only for error reporting
+ if (original.decorators)
+ updated.decorators = original.decorators;
+ if (original.modifiers)
+ updated.modifiers = original.modifiers;
+ if (original.questionToken)
+ updated.questionToken = original.questionToken;
+ if (original.exclamationToken)
+ updated.exclamationToken = original.exclamationToken;
+ return update(updated, original);
+ }
+ // @api
+ function updatePropertyAssignment(node, name, initializer) {
+ return node.name !== name
+ || node.initializer !== initializer
+ ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node)
+ : node;
+ }
+ // @api
+ function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
+ var node = createBaseNamedDeclaration(295 /* ShorthandPropertyAssignment */,
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, name);
+ node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
+ node.transformFlags |=
+ propagateChildFlags(node.objectAssignmentInitializer) |
+ 512 /* ContainsES2015 */;
+ return node;
+ }
+ function finishUpdateShorthandPropertyAssignment(updated, original) {
+ // copy children used only for error reporting
+ if (original.decorators)
+ updated.decorators = original.decorators;
+ if (original.modifiers)
+ updated.modifiers = original.modifiers;
+ if (original.equalsToken)
+ updated.equalsToken = original.equalsToken;
+ if (original.questionToken)
+ updated.questionToken = original.questionToken;
+ if (original.exclamationToken)
+ updated.exclamationToken = original.exclamationToken;
+ return update(updated, original);
+ }
+ // @api
+ function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
+ return node.name !== name
+ || node.objectAssignmentInitializer !== objectAssignmentInitializer
+ ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
+ : node;
+ }
+ // @api
+ function createSpreadAssignment(expression) {
+ var node = createBaseNode(296 /* SpreadAssignment */);
+ node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 64 /* ContainsES2018 */ |
+ 32768 /* ContainsObjectRestOrSpread */;
+ return node;
+ }
+ // @api
+ function updateSpreadAssignment(node, expression) {
+ return node.expression !== expression
+ ? update(createSpreadAssignment(expression), node)
+ : node;
+ }
+ //
+ // Enum
+ //
+ // @api
+ function createEnumMember(name, initializer) {
+ var node = createBaseNode(297 /* EnumMember */);
+ node.name = asName(name);
+ node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
+ node.transformFlags |=
+ propagateChildFlags(node.name) |
+ propagateChildFlags(node.initializer) |
+ 1 /* ContainsTypeScript */;
+ return node;
+ }
+ // @api
+ function updateEnumMember(node, name, initializer) {
+ return node.name !== name
+ || node.initializer !== initializer
+ ? update(createEnumMember(name, initializer), node)
+ : node;
+ }
+ //
+ // Top-level nodes
+ //
+ // @api
+ function createSourceFile(statements, endOfFileToken, flags) {
+ var node = baseFactory.createBaseSourceFileNode(303 /* SourceFile */);
+ node.statements = createNodeArray(statements);
+ node.endOfFileToken = endOfFileToken;
+ node.flags |= flags;
+ node.fileName = "";
+ node.text = "";
+ node.languageVersion = 0;
+ node.languageVariant = 0;
+ node.scriptKind = 0;
+ node.isDeclarationFile = false;
+ node.hasNoDefaultLib = false;
+ node.transformFlags |=
+ propagateChildrenFlags(node.statements) |
+ propagateChildFlags(node.endOfFileToken);
+ return node;
+ }
+ function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
+ var node = baseFactory.createBaseSourceFileNode(303 /* SourceFile */);
+ for (var p in source) {
+ if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p))
+ continue;
+ node[p] = source[p];
+ }
+ node.flags |= source.flags;
+ node.statements = createNodeArray(statements);
+ node.endOfFileToken = source.endOfFileToken;
+ node.isDeclarationFile = isDeclarationFile;
+ node.referencedFiles = referencedFiles;
+ node.typeReferenceDirectives = typeReferences;
+ node.hasNoDefaultLib = hasNoDefaultLib;
+ node.libReferenceDirectives = libReferences;
+ node.transformFlags =
+ propagateChildrenFlags(node.statements) |
+ propagateChildFlags(node.endOfFileToken);
+ node.impliedNodeFormat = source.impliedNodeFormat;
+ return node;
+ }
+ // @api
+ function updateSourceFile(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives) {
+ if (isDeclarationFile === void 0) { isDeclarationFile = node.isDeclarationFile; }
+ if (referencedFiles === void 0) { referencedFiles = node.referencedFiles; }
+ if (typeReferenceDirectives === void 0) { typeReferenceDirectives = node.typeReferenceDirectives; }
+ if (hasNoDefaultLib === void 0) { hasNoDefaultLib = node.hasNoDefaultLib; }
+ if (libReferenceDirectives === void 0) { libReferenceDirectives = node.libReferenceDirectives; }
+ return node.statements !== statements
+ || node.isDeclarationFile !== isDeclarationFile
+ || node.referencedFiles !== referencedFiles
+ || node.typeReferenceDirectives !== typeReferenceDirectives
+ || node.hasNoDefaultLib !== hasNoDefaultLib
+ || node.libReferenceDirectives !== libReferenceDirectives
+ ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node)
+ : node;
+ }
+ // @api
+ function createBundle(sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
+ var node = createBaseNode(304 /* Bundle */);
+ node.prepends = prepends;
+ node.sourceFiles = sourceFiles;
+ return node;
+ }
+ // @api
+ function updateBundle(node, sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
+ return node.sourceFiles !== sourceFiles
+ || node.prepends !== prepends
+ ? update(createBundle(sourceFiles, prepends), node)
+ : node;
+ }
+ // @api
+ function createUnparsedSource(prologues, syntheticReferences, texts) {
+ var node = createBaseNode(305 /* UnparsedSource */);
+ node.prologues = prologues;
+ node.syntheticReferences = syntheticReferences;
+ node.texts = texts;
+ node.fileName = "";
+ node.text = "";
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createBaseUnparsedNode(kind, data) {
+ var node = createBaseNode(kind);
+ node.data = data;
+ return node;
+ }
+ // @api
+ function createUnparsedPrologue(data) {
+ return createBaseUnparsedNode(298 /* UnparsedPrologue */, data);
+ }
+ // @api
+ function createUnparsedPrepend(data, texts) {
+ var node = createBaseUnparsedNode(299 /* UnparsedPrepend */, data);
+ node.texts = texts;
+ return node;
+ }
+ // @api
+ function createUnparsedTextLike(data, internal) {
+ return createBaseUnparsedNode(internal ? 301 /* UnparsedInternalText */ : 300 /* UnparsedText */, data);
+ }
+ // @api
+ function createUnparsedSyntheticReference(section) {
+ var node = createBaseNode(302 /* UnparsedSyntheticReference */);
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ // @api
+ function createInputFiles() {
+ var node = createBaseNode(306 /* InputFiles */);
+ node.javascriptText = "";
+ node.declarationText = "";
+ return node;
+ }
+ //
+ // Synthetic Nodes (used by checker)
+ //
+ // @api
+ function createSyntheticExpression(type, isSpread, tupleNameSource) {
+ if (isSpread === void 0) { isSpread = false; }
+ var node = createBaseNode(231 /* SyntheticExpression */);
+ node.type = type;
+ node.isSpread = isSpread;
+ node.tupleNameSource = tupleNameSource;
+ return node;
+ }
+ // @api
+ function createSyntaxList(children) {
+ var node = createBaseNode(346 /* SyntaxList */);
+ node._children = children;
+ return node;
+ }
+ //
+ // Transformation nodes
+ //
+ /**
+ * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
+ * order to preserve comments.
+ *
+ * @param original The original statement.
+ */
+ // @api
+ function createNotEmittedStatement(original) {
+ var node = createBaseNode(347 /* NotEmittedStatement */);
+ node.original = original;
+ ts.setTextRange(node, original);
+ return node;
+ }
+ /**
+ * 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.
+ */
+ // @api
+ function createPartiallyEmittedExpression(expression, original) {
+ var node = createBaseNode(348 /* PartiallyEmittedExpression */);
+ node.expression = expression;
+ node.original = original;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ 1 /* ContainsTypeScript */;
+ ts.setTextRange(node, original);
+ return node;
+ }
+ // @api
+ function updatePartiallyEmittedExpression(node, expression) {
+ return node.expression !== expression
+ ? update(createPartiallyEmittedExpression(expression, node.original), node)
+ : node;
+ }
+ function flattenCommaElements(node) {
+ if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
+ if (ts.isCommaListExpression(node)) {
+ return node.elements;
+ }
+ if (ts.isBinaryExpression(node) && ts.isCommaToken(node.operatorToken)) {
+ return [node.left, node.right];
+ }
+ }
+ return node;
+ }
+ // @api
+ function createCommaListExpression(elements) {
+ var node = createBaseNode(349 /* CommaListExpression */);
+ node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
+ node.transformFlags |= propagateChildrenFlags(node.elements);
+ return node;
+ }
+ // @api
+ function updateCommaListExpression(node, elements) {
+ return node.elements !== elements
+ ? update(createCommaListExpression(elements), node)
+ : node;
+ }
+ /**
+ * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
+ * order to properly emit exports.
+ */
+ // @api
+ function createEndOfDeclarationMarker(original) {
+ var node = createBaseNode(351 /* EndOfDeclarationMarker */);
+ node.emitNode = {};
+ node.original = original;
+ return node;
+ }
+ /**
+ * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
+ * order to properly emit exports.
+ */
+ // @api
+ function createMergeDeclarationMarker(original) {
+ var node = createBaseNode(350 /* MergeDeclarationMarker */);
+ node.emitNode = {};
+ node.original = original;
+ return node;
+ }
+ // @api
+ function createSyntheticReferenceExpression(expression, thisArg) {
+ var node = createBaseNode(352 /* SyntheticReferenceExpression */);
+ node.expression = expression;
+ node.thisArg = thisArg;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.thisArg);
+ return node;
+ }
+ // @api
+ function updateSyntheticReferenceExpression(node, expression, thisArg) {
+ return node.expression !== expression
+ || node.thisArg !== thisArg
+ ? update(createSyntheticReferenceExpression(expression, thisArg), node)
+ : node;
+ }
+ function cloneNode(node) {
+ // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
+ // the original node. We also need to exclude specific properties and only include own-
+ // properties (to skip members already defined on the shared prototype).
+ if (node === undefined) {
+ return node;
+ }
+ var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(303 /* SourceFile */) :
+ ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(79 /* Identifier */) :
+ ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(80 /* PrivateIdentifier */) :
+ !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) :
+ baseFactory.createBaseNode(node.kind);
+ clone.flags |= (node.flags & ~8 /* Synthesized */);
+ clone.transformFlags = node.transformFlags;
+ setOriginalNode(clone, node);
+ for (var key in node) {
+ if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
+ continue;
+ }
+ clone[key] = node[key];
+ }
+ return clone;
+ }
+ function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
+ return createCallExpression(createFunctionExpression(
+ /*modifiers*/ undefined,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined,
+ /*parameters*/ param ? [param] : [],
+ /*type*/ undefined, createBlock(statements, /*multiLine*/ true)),
+ /*typeArguments*/ undefined,
+ /*argumentsArray*/ paramValue ? [paramValue] : []);
+ }
+ function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
+ return createCallExpression(createArrowFunction(
+ /*modifiers*/ undefined,
+ /*typeParameters*/ undefined,
+ /*parameters*/ param ? [param] : [],
+ /*type*/ undefined,
+ /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)),
+ /*typeArguments*/ undefined,
+ /*argumentsArray*/ paramValue ? [paramValue] : []);
+ }
+ function createVoidZero() {
+ return createVoidExpression(createNumericLiteral("0"));
+ }
+ function createExportDefault(expression) {
+ return createExportAssignment(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*isExportEquals*/ false, expression);
+ }
+ function createExternalModuleExport(exportName) {
+ return createExportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*isTypeOnly*/ false, createNamedExports([
+ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName)
+ ]));
+ }
+ //
+ // Utilities
+ //
+ function createTypeCheck(value, tag) {
+ return tag === "undefined"
+ ? factory.createStrictEquality(value, createVoidZero())
+ : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
+ }
+ function createMethodCall(object, methodName, argumentsList) {
+ // Preserve the optionality of `object`.
+ if (ts.isCallChain(object)) {
+ return createCallChain(createPropertyAccessChain(object, /*questionDotToken*/ undefined, methodName),
+ /*questionDotToken*/ undefined,
+ /*typeArguments*/ undefined, argumentsList);
+ }
+ return createCallExpression(createPropertyAccessExpression(object, methodName),
+ /*typeArguments*/ undefined, argumentsList);
+ }
+ function createFunctionBindCall(target, thisArg, argumentsList) {
+ return createMethodCall(target, "bind", __spreadArray([thisArg], argumentsList, true));
+ }
+ function createFunctionCallCall(target, thisArg, argumentsList) {
+ return createMethodCall(target, "call", __spreadArray([thisArg], argumentsList, true));
+ }
+ function createFunctionApplyCall(target, thisArg, argumentsExpression) {
+ return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
+ }
+ function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
+ return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
+ }
+ function createArraySliceCall(array, start) {
+ return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]);
+ }
+ function createArrayConcatCall(array, argumentsList) {
+ return createMethodCall(array, "concat", argumentsList);
+ }
+ function createObjectDefinePropertyCall(target, propertyName, attributes) {
+ return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
+ }
+ function createReflectGetCall(target, propertyKey, receiver) {
+ return createGlobalMethodCall("Reflect", "get", receiver ? [target, propertyKey, receiver] : [target, propertyKey]);
+ }
+ function createReflectSetCall(target, propertyKey, value, receiver) {
+ return createGlobalMethodCall("Reflect", "set", receiver ? [target, propertyKey, value, receiver] : [target, propertyKey, value]);
+ }
+ function tryAddPropertyAssignment(properties, propertyName, expression) {
+ if (expression) {
+ properties.push(createPropertyAssignment(propertyName, expression));
+ return true;
+ }
+ return false;
+ }
+ function createPropertyDescriptor(attributes, singleLine) {
+ var properties = [];
+ tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
+ tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
+ var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
+ isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
+ var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
+ isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
+ ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
+ return createObjectLiteralExpression(properties, !singleLine);
+ }
+ function updateOuterExpression(outerExpression, expression) {
+ switch (outerExpression.kind) {
+ case 211 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression);
+ case 210 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
+ case 228 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type);
+ case 229 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression);
+ case 348 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression);
+ }
+ }
+ /**
+ * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
+ *
+ * A parenthesized expression can be ignored when all of the following are true:
+ *
+ * - It's `pos` and `end` are not -1
+ * - It does not have a custom source map range
+ * - It does not have a custom comment range
+ * - It does not have synthetic leading or trailing comments
+ *
+ * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
+ * the expression to maintain precedence, a new parenthesized expression should be created automatically when
+ * the containing expression is created/updated.
+ */
+ function isIgnorableParen(node) {
+ return ts.isParenthesizedExpression(node)
+ && ts.nodeIsSynthesized(node)
+ && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
+ && ts.nodeIsSynthesized(ts.getCommentRange(node))
+ && !ts.some(ts.getSyntheticLeadingComments(node))
+ && !ts.some(ts.getSyntheticTrailingComments(node));
+ }
+ function restoreOuterExpressions(outerExpression, innerExpression, kinds) {
+ if (kinds === void 0) { kinds = 15 /* All */; }
+ if (outerExpression && ts.isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
+ return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression));
+ }
+ return innerExpression;
+ }
+ function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
+ if (!outermostLabeledStatement) {
+ return node;
+ }
+ var updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, ts.isLabeledStatement(outermostLabeledStatement.statement)
+ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
+ : node);
+ if (afterRestoreLabelCallback) {
+ afterRestoreLabelCallback(outermostLabeledStatement);
+ }
+ return updated;
+ }
+ function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
+ var target = ts.skipParentheses(node);
+ switch (target.kind) {
+ case 79 /* Identifier */:
+ return cacheIdentifiers;
+ case 108 /* ThisKeyword */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 10 /* StringLiteral */:
+ return false;
+ case 203 /* ArrayLiteralExpression */:
+ var elements = target.elements;
+ if (elements.length === 0) {
+ return false;
+ }
+ return true;
+ case 204 /* ObjectLiteralExpression */:
+ return target.properties.length > 0;
+ default:
+ return true;
+ }
+ }
+ function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
+ if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
+ var callee = ts.skipOuterExpressions(expression, 15 /* All */);
+ var thisArg;
+ var target;
+ if (ts.isSuperProperty(callee)) {
+ thisArg = createThis();
+ target = callee;
+ }
+ else if (ts.isSuperKeyword(callee)) {
+ thisArg = createThis();
+ target = languageVersion !== undefined && languageVersion < 2 /* ES2015 */
+ ? ts.setTextRange(createIdentifier("_super"), callee)
+ : callee;
+ }
+ else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
+ thisArg = createVoidZero();
+ target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee);
+ }
+ else if (ts.isPropertyAccessExpression(callee)) {
+ if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
+ // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
+ thisArg = createTempVariable(recordTempVariable);
+ target = createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
+ ts.setTextRange(target, callee);
+ }
+ else {
+ thisArg = callee.expression;
+ target = callee;
+ }
+ }
+ else if (ts.isElementAccessExpression(callee)) {
+ if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
+ // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
+ thisArg = createTempVariable(recordTempVariable);
+ target = createElementAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
+ ts.setTextRange(target, callee);
+ }
+ else {
+ thisArg = callee.expression;
+ target = callee;
+ }
+ }
+ else {
+ // for `a()` target is `a` and thisArg is `void 0`
+ thisArg = createVoidZero();
+ target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
+ }
+ return { target: target, thisArg: thisArg };
+ }
+ function createAssignmentTargetWrapper(paramName, expression) {
+ return createPropertyAccessExpression(
+ // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
+ createParenthesizedExpression(createObjectLiteralExpression([
+ createSetAccessorDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, "value", [createParameterDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, paramName,
+ /*questionToken*/ undefined,
+ /*type*/ undefined,
+ /*initializer*/ undefined)], createBlock([
+ createExpressionStatement(expression)
+ ]))
+ ])), "value");
+ }
+ function inlineExpressions(expressions) {
+ // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
+ // stack size exceeded" errors.
+ return expressions.length > 10
+ ? createCommaListExpression(expressions)
+ : ts.reduceLeft(expressions, factory.createComma);
+ }
+ function getName(node, allowComments, allowSourceMaps, emitFlags) {
+ if (emitFlags === void 0) { emitFlags = 0; }
+ var nodeName = ts.getNameOfDeclaration(node);
+ if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
+ // TODO(rbuckton): Does this need to be parented?
+ var name = ts.setParent(ts.setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
+ emitFlags |= ts.getEmitFlags(nodeName);
+ if (!allowSourceMaps)
+ emitFlags |= 48 /* NoSourceMap */;
+ if (!allowComments)
+ emitFlags |= 1536 /* NoComments */;
+ if (emitFlags)
+ ts.setEmitFlags(name, emitFlags);
+ return name;
+ }
+ return getGeneratedNameForNode(node);
+ }
+ /**
+ * Gets the internal name of a declaration. This is primarily used for declarations that can be
+ * referred to by name in the body of an ES5 class function body. An internal name will *never*
+ * be prefixed with an module or namespace export modifier like "exports." when emitted as an
+ * expression. An internal name will also *never* be renamed due to a collision with a block
+ * scoped variable.
+ *
+ * @param node The declaration.
+ * @param allowComments A value indicating whether comments may be emitted for the name.
+ * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
+ */
+ function getInternalName(node, allowComments, allowSourceMaps) {
+ return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
+ }
+ /**
+ * Gets the local name of a declaration. This is primarily used for declarations that can be
+ * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
+ * local name will *never* be prefixed with an module or namespace export modifier like
+ * "exports." when emitted as an expression.
+ *
+ * @param node The declaration.
+ * @param allowComments A value indicating whether comments may be emitted for the name.
+ * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
+ */
+ function getLocalName(node, allowComments, allowSourceMaps) {
+ return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
+ }
+ /**
+ * Gets the export name of a declaration. This is primarily used for declarations that can be
+ * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
+ * export name will *always* be prefixed with an module or namespace export modifier like
+ * `"exports."` when emitted as an expression if the name points to an exported symbol.
+ *
+ * @param node The declaration.
+ * @param allowComments A value indicating whether comments may be emitted for the name.
+ * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
+ */
+ function getExportName(node, allowComments, allowSourceMaps) {
+ return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
+ }
+ /**
+ * Gets the name of a declaration for use in declarations.
+ *
+ * @param node The declaration.
+ * @param allowComments A value indicating whether comments may be emitted for the name.
+ * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
+ */
+ function getDeclarationName(node, allowComments, allowSourceMaps) {
+ return getName(node, allowComments, allowSourceMaps);
+ }
+ /**
+ * Gets a namespace-qualified name for use in expressions.
+ *
+ * @param ns The namespace identifier.
+ * @param name The name.
+ * @param allowComments A value indicating whether comments may be emitted for the name.
+ * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
+ */
+ function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
+ var qualifiedName = createPropertyAccessExpression(ns, ts.nodeIsSynthesized(name) ? name : cloneNode(name));
+ ts.setTextRange(qualifiedName, name);
+ var emitFlags = 0;
+ if (!allowSourceMaps)
+ emitFlags |= 48 /* NoSourceMap */;
+ if (!allowComments)
+ emitFlags |= 1536 /* NoComments */;
+ if (emitFlags)
+ ts.setEmitFlags(qualifiedName, emitFlags);
+ return qualifiedName;
+ }
+ /**
+ * Gets the exported name of a declaration for use in expressions.
+ *
+ * An exported name will *always* be prefixed with an module or namespace export modifier like
+ * "exports." if the name points to an exported symbol.
+ *
+ * @param ns The namespace identifier.
+ * @param node The declaration.
+ * @param allowComments A value indicating whether comments may be emitted for the name.
+ * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
+ */
+ function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
+ if (ns && ts.hasSyntacticModifier(node, 1 /* Export */)) {
+ return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
+ }
+ return getExportName(node, allowComments, allowSourceMaps);
+ }
+ /**
+ * Copies any necessary standard and custom prologue-directives into target array.
+ * @param source origin statements array
+ * @param target result statements array
+ * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
+ * @param visitor Optional callback used to visit any custom prologue directives.
+ */
+ function copyPrologue(source, target, ensureUseStrict, visitor) {
+ var offset = copyStandardPrologue(source, target, ensureUseStrict);
+ return copyCustomPrologue(source, target, offset, visitor);
+ }
+ function isUseStrictPrologue(node) {
+ return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
+ }
+ function createUseStrictPrologue() {
+ return ts.startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
+ }
+ /**
+ * Copies only the standard (string-expression) prologue-directives into the target statement-array.
+ * @param source origin statements array
+ * @param target result statements array
+ * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
+ */
+ function copyStandardPrologue(source, target, ensureUseStrict) {
+ ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
+ var foundUseStrict = false;
+ var statementOffset = 0;
+ var numStatements = source.length;
+ while (statementOffset < numStatements) {
+ var statement = source[statementOffset];
+ if (ts.isPrologueDirective(statement)) {
+ if (isUseStrictPrologue(statement)) {
+ foundUseStrict = true;
+ }
+ target.push(statement);
+ }
+ else {
+ break;
+ }
+ statementOffset++;
+ }
+ if (ensureUseStrict && !foundUseStrict) {
+ target.push(createUseStrictPrologue());
+ }
+ return statementOffset;
+ }
+ function copyCustomPrologue(source, target, statementOffset, visitor, filter) {
+ if (filter === void 0) { filter = ts.returnTrue; }
+ var numStatements = source.length;
+ while (statementOffset !== undefined && statementOffset < numStatements) {
+ var statement = source[statementOffset];
+ if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
+ ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
+ }
+ else {
+ break;
+ }
+ statementOffset++;
+ }
+ return statementOffset;
+ }
+ /**
+ * Ensures "use strict" directive is added
+ *
+ * @param statements An array of statements
+ */
+ function ensureUseStrict(statements) {
+ var foundUseStrict = ts.findUseStrictPrologue(statements);
+ if (!foundUseStrict) {
+ return ts.setTextRange(createNodeArray(__spreadArray([createUseStrictPrologue()], statements, true)), statements);
+ }
+ return statements;
+ }
+ /**
+ * Lifts a NodeArray containing only Statement nodes to a block.
+ *
+ * @param nodes The NodeArray.
+ */
+ function liftToBlock(nodes) {
+ ts.Debug.assert(ts.every(nodes, ts.isStatementOrBlock), "Cannot lift nodes to a Block.");
+ return ts.singleOrUndefined(nodes) || createBlock(nodes);
+ }
+ function findSpanEnd(array, test, start) {
+ var i = start;
+ while (i < array.length && test(array[i])) {
+ i++;
+ }
+ return i;
+ }
+ function mergeLexicalEnvironment(statements, declarations) {
+ if (!ts.some(declarations)) {
+ return statements;
+ }
+ // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
+ //
+ // Given:
+ //
+ // | Left | Right |
+ // |------------------------------------|-------------------------------------|
+ // | [standard prologues (left)] | [standard prologues (right)] |
+ // | [hoisted functions (left)] | [hoisted functions (right)] |
+ // | [hoisted variables (left)] | [hoisted variables (right)] |
+ // | [lexical init statements (left)] | [lexical init statements (right)] |
+ // | [other statements (left)] | |
+ //
+ // The resulting statement list will be:
+ //
+ // | Result |
+ // |-------------------------------------|
+ // | [standard prologues (right)] |
+ // | [standard prologues (left)] |
+ // | [hoisted functions (right)] |
+ // | [hoisted functions (left)] |
+ // | [hoisted variables (right)] |
+ // | [hoisted variables (left)] |
+ // | [lexical init statements (right)] |
+ // | [lexical init statements (left)] |
+ // | [other statements (left)] |
+ //
+ // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
+ // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
+ // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
+ var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
+ var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
+ var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
+ // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
+ var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
+ var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
+ var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
+ var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
+ ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
+ // splice prologues from the right into the left. We do this in reverse order
+ // so that we don't need to recompute the index on the left when we insert items.
+ var left = ts.isNodeArray(statements) ? statements.slice() : statements;
+ // splice other custom prologues from right into left
+ if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
+ left.splice.apply(left, __spreadArray([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd), false));
+ }
+ // splice hoisted variables from right into left
+ if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
+ left.splice.apply(left, __spreadArray([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd), false));
+ }
+ // splice hoisted functions from right into left
+ if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
+ left.splice.apply(left, __spreadArray([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd), false));
+ }
+ // splice standard prologues from right into left (that are not already in left)
+ if (rightStandardPrologueEnd > 0) {
+ if (leftStandardPrologueEnd === 0) {
+ left.splice.apply(left, __spreadArray([0, 0], declarations.slice(0, rightStandardPrologueEnd), false));
+ }
+ else {
+ var leftPrologues = new ts.Map();
+ for (var i = 0; i < leftStandardPrologueEnd; i++) {
+ var leftPrologue = statements[i];
+ leftPrologues.set(leftPrologue.expression.text, true);
+ }
+ for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
+ var rightPrologue = declarations[i];
+ if (!leftPrologues.has(rightPrologue.expression.text)) {
+ left.unshift(rightPrologue);
+ }
+ }
+ }
+ }
+ if (ts.isNodeArray(statements)) {
+ return ts.setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
+ }
+ return statements;
+ }
+ function updateModifiers(node, modifiers) {
+ var _a;
+ if (typeof modifiers === "number") {
+ modifiers = createModifiersFromModifierFlags(modifiers);
+ }
+ return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
+ ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
+ ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) :
+ ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
+ ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
+ ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
+ ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
+ ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
+ ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
+ ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
+ ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
+ ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
+ ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
+ ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
+ ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
+ ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
+ ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
+ ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
+ ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
+ ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) :
+ ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier, node.assertClause) :
+ ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
+ ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) :
+ ts.Debug.assertNever(node);
+ }
+ function asNodeArray(array) {
+ return array ? createNodeArray(array) : undefined;
+ }
+ function asName(name) {
+ return typeof name === "string" ? createIdentifier(name) :
+ name;
+ }
+ function asExpression(value) {
+ return typeof value === "string" ? createStringLiteral(value) :
+ typeof value === "number" ? createNumericLiteral(value) :
+ typeof value === "boolean" ? value ? createTrue() : createFalse() :
+ value;
+ }
+ function asToken(value) {
+ return typeof value === "number" ? createToken(value) : value;
+ }
+ function asEmbeddedStatement(statement) {
+ return statement && ts.isNotEmittedStatement(statement) ? ts.setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
+ }
+ }
+ ts.createNodeFactory = createNodeFactory;
+ function updateWithoutOriginal(updated, original) {
+ if (updated !== original) {
+ ts.setTextRange(updated, original);
+ }
+ return updated;
+ }
+ function updateWithOriginal(updated, original) {
+ if (updated !== original) {
+ setOriginalNode(updated, original);
+ ts.setTextRange(updated, original);
+ }
+ return updated;
+ }
+ function getDefaultTagNameForKind(kind) {
+ switch (kind) {
+ case 341 /* JSDocTypeTag */: return "type";
+ case 339 /* JSDocReturnTag */: return "returns";
+ case 340 /* JSDocThisTag */: return "this";
+ case 337 /* JSDocEnumTag */: return "enum";
+ case 328 /* JSDocAuthorTag */: return "author";
+ case 330 /* JSDocClassTag */: return "class";
+ case 331 /* JSDocPublicTag */: return "public";
+ case 332 /* JSDocPrivateTag */: return "private";
+ case 333 /* JSDocProtectedTag */: return "protected";
+ case 334 /* JSDocReadonlyTag */: return "readonly";
+ case 335 /* JSDocOverrideTag */: return "override";
+ case 342 /* JSDocTemplateTag */: return "template";
+ case 343 /* JSDocTypedefTag */: return "typedef";
+ case 338 /* JSDocParameterTag */: return "param";
+ case 345 /* JSDocPropertyTag */: return "prop";
+ case 336 /* JSDocCallbackTag */: return "callback";
+ case 326 /* JSDocAugmentsTag */: return "augments";
+ case 327 /* JSDocImplementsTag */: return "implements";
+ default:
+ return ts.Debug.fail("Unsupported kind: ".concat(ts.Debug.formatSyntaxKind(kind)));
+ }
+ }
+ var rawTextScanner;
+ var invalidValueSentinel = {};
+ function getCookedText(kind, rawText) {
+ if (!rawTextScanner) {
+ rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
+ }
+ switch (kind) {
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ rawTextScanner.setText("`" + rawText + "`");
+ break;
+ case 15 /* TemplateHead */:
+ // tslint:disable-next-line no-invalid-template-strings
+ rawTextScanner.setText("`" + rawText + "${");
+ break;
+ case 16 /* TemplateMiddle */:
+ // tslint:disable-next-line no-invalid-template-strings
+ rawTextScanner.setText("}" + rawText + "${");
+ break;
+ case 17 /* TemplateTail */:
+ rawTextScanner.setText("}" + rawText + "`");
+ break;
+ }
+ var token = rawTextScanner.scan();
+ if (token === 19 /* CloseBraceToken */) {
+ token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false);
+ }
+ if (rawTextScanner.isUnterminated()) {
+ rawTextScanner.setText(undefined);
+ return invalidValueSentinel;
+ }
+ var tokenValue;
+ switch (token) {
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 15 /* TemplateHead */:
+ case 16 /* TemplateMiddle */:
+ case 17 /* TemplateTail */:
+ tokenValue = rawTextScanner.getTokenValue();
+ break;
+ }
+ if (tokenValue === undefined || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
+ rawTextScanner.setText(undefined);
+ return invalidValueSentinel;
+ }
+ rawTextScanner.setText(undefined);
+ return tokenValue;
+ }
+ function propagateIdentifierNameFlags(node) {
+ // An IdentifierName is allowed to be `await`
+ return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */;
+ }
+ function propagatePropertyNameFlagsOfChild(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 33562624 /* PropertyNamePropagatingFlags */);
+ }
+ function propagateChildFlags(child) {
+ if (!child)
+ return 0 /* None */;
+ var childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
+ return ts.isNamedDeclaration(child) && ts.isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
+ }
+ function propagateChildrenFlags(children) {
+ return children ? children.transformFlags : 0 /* None */;
+ }
+ function aggregateChildrenFlags(children) {
+ var subtreeFlags = 0 /* None */;
+ for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
+ var child = children_2[_i];
+ subtreeFlags |= propagateChildFlags(child);
+ }
+ children.transformFlags = subtreeFlags;
+ }
+ /**
+ * Gets the transform flags to exclude when unioning the transform flags of a subtree.
+ */
+ /* @internal */
+ function getTransformFlagsSubtreeExclusions(kind) {
+ if (kind >= 176 /* FirstTypeNode */ && kind <= 199 /* LastTypeNode */) {
+ return -2 /* TypeExcludes */;
+ }
+ switch (kind) {
+ case 207 /* CallExpression */:
+ case 208 /* NewExpression */:
+ case 203 /* ArrayLiteralExpression */:
+ return 536887296 /* ArrayLiteralOrCallOrNewExcludes */;
+ case 260 /* ModuleDeclaration */:
+ return 589443072 /* ModuleExcludes */;
+ case 163 /* Parameter */:
+ return 536870912 /* ParameterExcludes */;
+ case 213 /* ArrowFunction */:
+ return 557748224 /* ArrowFunctionExcludes */;
+ case 212 /* FunctionExpression */:
+ case 255 /* FunctionDeclaration */:
+ return 591310848 /* FunctionExcludes */;
+ case 254 /* VariableDeclarationList */:
+ return 537165824 /* VariableDeclarationListExcludes */;
+ case 256 /* ClassDeclaration */:
+ case 225 /* ClassExpression */:
+ return 536940544 /* ClassExcludes */;
+ case 170 /* Constructor */:
+ return 591306752 /* ConstructorExcludes */;
+ case 166 /* PropertyDeclaration */:
+ return 570433536 /* PropertyExcludes */;
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ return 574529536 /* MethodOrAccessorExcludes */;
+ case 130 /* AnyKeyword */:
+ case 146 /* NumberKeyword */:
+ case 157 /* BigIntKeyword */:
+ case 143 /* NeverKeyword */:
+ case 149 /* StringKeyword */:
+ case 147 /* ObjectKeyword */:
+ case 133 /* BooleanKeyword */:
+ case 150 /* SymbolKeyword */:
+ case 114 /* VoidKeyword */:
+ case 162 /* TypeParameter */:
+ case 165 /* PropertySignature */:
+ case 167 /* MethodSignature */:
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 175 /* IndexSignature */:
+ case 257 /* InterfaceDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ return -2 /* TypeExcludes */;
+ case 204 /* ObjectLiteralExpression */:
+ return 536973312 /* ObjectLiteralExcludes */;
+ case 291 /* CatchClause */:
+ return 536903680 /* CatchClauseExcludes */;
+ case 200 /* ObjectBindingPattern */:
+ case 201 /* ArrayBindingPattern */:
+ return 536887296 /* BindingPatternExcludes */;
+ case 210 /* TypeAssertionExpression */:
+ case 228 /* AsExpression */:
+ case 348 /* PartiallyEmittedExpression */:
+ case 211 /* ParenthesizedExpression */:
+ case 106 /* SuperKeyword */:
+ return 536870912 /* OuterExpressionExcludes */;
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ return 536870912 /* PropertyAccessExcludes */;
+ default:
+ return 536870912 /* NodeExcludes */;
+ }
+ }
+ ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
+ var baseFactory = ts.createBaseNodeFactory();
+ function makeSynthetic(node) {
+ node.flags |= 8 /* Synthesized */;
+ return node;
+ }
+ var syntheticFactory = {
+ createBaseSourceFileNode: function (kind) { return makeSynthetic(baseFactory.createBaseSourceFileNode(kind)); },
+ createBaseIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBaseIdentifierNode(kind)); },
+ createBasePrivateIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)); },
+ createBaseTokenNode: function (kind) { return makeSynthetic(baseFactory.createBaseTokenNode(kind)); },
+ createBaseNode: function (kind) { return makeSynthetic(baseFactory.createBaseNode(kind)); },
+ };
+ ts.factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var stripInternal;
+ var bundleFileInfo;
+ var fileName;
+ var text;
+ var length;
+ var sourceMapPath;
+ var sourceMapText;
+ var getText;
+ var getSourceMapText;
+ var oldFileOfCurrentEmit;
+ if (!ts.isString(textOrInputFiles)) {
+ ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
+ fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
+ sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
+ getText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; };
+ getSourceMapText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; };
+ length = function () { return getText().length; };
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ }
+ }
+ else {
+ fileName = "";
+ text = textOrInputFiles;
+ length = textOrInputFiles.length;
+ sourceMapPath = mapPathOrType;
+ sourceMapText = mapTextOrStripInternal;
+ }
+ var node = oldFileOfCurrentEmit ?
+ parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) :
+ parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
+ node.fileName = fileName;
+ node.sourceMapPath = sourceMapPath;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
+ if (getText && getSourceMapText) {
+ Object.defineProperty(node, "text", { get: getText });
+ Object.defineProperty(node, "sourceMapText", { get: getSourceMapText });
+ }
+ else {
+ ts.Debug.assert(!oldFileOfCurrentEmit);
+ node.text = text !== null && text !== void 0 ? text : "";
+ node.sourceMapText = sourceMapText;
+ }
+ return node;
+ }
+ ts.createUnparsedSourceFile = createUnparsedSourceFile;
+ function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var prependChildren;
+ var texts;
+ var hasNoDefaultLib;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ prologues = ts.append(prologues, ts.setTextRange(ts.factory.createUnparsedPrologue(section.data), section));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ helpers = ts.append(helpers, ts.getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
+ break;
+ case "lib" /* Lib */:
+ libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ prependTexts = ts.append(prependTexts, ts.setTextRange(ts.factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */), text));
+ }
+ }
+ prependChildren = ts.addRange(prependChildren, prependTexts);
+ texts = ts.append(texts, ts.factory.createUnparsedPrepend(section.data, prependTexts !== null && prependTexts !== void 0 ? prependTexts : ts.emptyArray));
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal) {
+ if (!texts)
+ texts = [];
+ break;
+ }
+ // falls through
+ case "text" /* Text */:
+ texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ if (!texts) {
+ var textNode = ts.factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false);
+ ts.setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length);
+ texts = [textNode];
+ }
+ var node = ts.parseNodeFactory.createUnparsedSource(prologues !== null && prologues !== void 0 ? prologues : ts.emptyArray, /*syntheticReferences*/ undefined, texts);
+ ts.setEachParent(prologues, node);
+ ts.setEachParent(texts, node);
+ ts.setEachParent(prependChildren, node);
+ node.hasNoDefaultLib = hasNoDefaultLib;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ return node;
+ }
+ function parseOldFileOfCurrentEmit(bundleFileInfo) {
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ var node = ts.factory.createUnparsedSource(ts.emptyArray, syntheticReferences, texts !== null && texts !== void 0 ? texts : ts.emptyArray);
+ ts.setEachParent(syntheticReferences, node);
+ ts.setEachParent(texts, node);
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return ts.getAllUnscopedEmitHelpers().get(name); });
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.parseNodeFactory.createInputFiles();
+ if (!ts.isString(javascriptTextOrReadFileText)) {
+ var cache_1 = new ts.Map();
+ var textGetter_1 = function (path) {
+ if (path === undefined)
+ return undefined;
+ var value = cache_1.get(path);
+ if (value === undefined) {
+ value = javascriptTextOrReadFileText(path);
+ cache_1.set(path, value !== undefined ? value : false);
+ }
+ return value !== false ? value : undefined;
+ };
+ var definedTextGetter_1 = function (path) {
+ var result = textGetter_1(path);
+ return result !== undefined ? result : "/* Input file ".concat(path, " was missing */\r\n");
+ };
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
+ node.javascriptPath = declarationTextOrJavascriptPath;
+ node.javascriptMapPath = javascriptMapPath;
+ node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
+ node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
+ Object.defineProperties(node, {
+ javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
+ javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
+ declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
+ });
+ }
+ else {
+ node.javascriptText = javascriptTextOrReadFileText;
+ node.javascriptMapPath = javascriptMapPath;
+ node.javascriptMapText = javascriptMapTextOrDeclarationPath;
+ node.declarationText = declarationTextOrJavascriptPath;
+ node.declarationMapPath = declarationMapPath;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath;
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
+ }
+ return node;
+ }
+ ts.createInputFiles = createInputFiles;
+ // tslint:disable-next-line variable-name
+ var SourceMapSource;
+ /**
+ * Create an external source map source file reference
+ */
+ function createSourceMapSource(fileName, text, skipTrivia) {
+ return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
+ }
+ ts.createSourceMapSource = createSourceMapSource;
+ // Utilities
+ function setOriginalNode(node, original) {
+ node.original = original;
+ if (original) {
+ var emitNode = original.emitNode;
+ if (emitNode)
+ node.emitNode = mergeEmitNode(emitNode, node.emitNode);
+ }
+ return node;
+ }
+ ts.setOriginalNode = setOriginalNode;
+ function mergeEmitNode(sourceEmitNode, destEmitNode) {
+ var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine;
+ if (!destEmitNode)
+ destEmitNode = {};
+ // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
+ if (leadingComments)
+ destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
+ if (trailingComments)
+ destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
+ if (flags)
+ destEmitNode.flags = flags & ~268435456 /* Immutable */;
+ if (commentRange)
+ destEmitNode.commentRange = commentRange;
+ if (sourceMapRange)
+ destEmitNode.sourceMapRange = sourceMapRange;
+ if (tokenSourceMapRanges)
+ destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
+ if (constantValue !== undefined)
+ destEmitNode.constantValue = constantValue;
+ if (helpers) {
+ for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
+ var helper = helpers_1[_i];
+ destEmitNode.helpers = ts.appendIfUnique(destEmitNode.helpers, helper);
+ }
+ }
+ if (startsOnNewLine !== undefined)
+ destEmitNode.startsOnNewLine = startsOnNewLine;
+ return destEmitNode;
+ }
+ function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
+ if (!destRanges)
+ destRanges = [];
+ for (var key in sourceRanges) {
+ destRanges[key] = sourceRanges[key];
+ }
+ return destRanges;
+ }
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ /**
+ * Associates a node with the current transformation, initializing
+ * various transient transformation properties.
+ * @internal
+ */
+ function getOrCreateEmitNode(node) {
+ var _a;
+ if (!node.emitNode) {
+ if (ts.isParseTreeNode(node)) {
+ // To avoid holding onto transformation artifacts, we keep track of any
+ // parse tree node we are annotating. This allows us to clean them up after
+ // all transformations have completed.
+ if (node.kind === 303 /* SourceFile */) {
+ return node.emitNode = { annotatedNodes: [node] };
+ }
+ var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file.");
+ getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
+ }
+ node.emitNode = {};
+ }
+ else {
+ ts.Debug.assert(!(node.emitNode.flags & 268435456 /* Immutable */), "Invalid attempt to mutate an immutable node.");
+ }
+ return node.emitNode;
+ }
+ ts.getOrCreateEmitNode = getOrCreateEmitNode;
+ /**
+ * Clears any `EmitNode` entries from parse-tree nodes.
+ * @param sourceFile A source file.
+ */
+ function disposeEmitNodes(sourceFile) {
+ var _a, _b;
+ // During transformation we may need to annotate a parse tree node with transient
+ // transformation properties. As parse tree nodes live longer than transformation
+ // nodes, we need to make sure we reclaim any memory allocated for custom ranges
+ // from these nodes to ensure we do not hold onto entire subtrees just for position
+ // information. We also need to reset these nodes to a pre-transformation state
+ // for incremental parsing scenarios so that we do not impact later emit.
+ var annotatedNodes = (_b = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile))) === null || _a === void 0 ? void 0 : _a.emitNode) === null || _b === void 0 ? void 0 : _b.annotatedNodes;
+ if (annotatedNodes) {
+ for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
+ var node = annotatedNodes_1[_i];
+ node.emitNode = undefined;
+ }
+ }
+ }
+ ts.disposeEmitNodes = disposeEmitNodes;
+ /**
+ * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
+ * @internal
+ */
+ function removeAllComments(node) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.flags |= 1536 /* NoComments */;
+ emitNode.leadingComments = undefined;
+ emitNode.trailingComments = undefined;
+ return node;
+ }
+ ts.removeAllComments = removeAllComments;
+ /**
+ * Sets flags that control emit behavior of a node.
+ */
+ function setEmitFlags(node, emitFlags) {
+ getOrCreateEmitNode(node).flags = emitFlags;
+ return node;
+ }
+ ts.setEmitFlags = setEmitFlags;
+ /**
+ * Sets flags that control emit behavior of a node.
+ */
+ /* @internal */
+ function addEmitFlags(node, emitFlags) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.flags = emitNode.flags | emitFlags;
+ return node;
+ }
+ ts.addEmitFlags = addEmitFlags;
+ /**
+ * Gets a custom text range to use when emitting source maps.
+ */
+ function getSourceMapRange(node) {
+ var _a, _b;
+ return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.sourceMapRange) !== null && _b !== void 0 ? _b : node;
+ }
+ ts.getSourceMapRange = getSourceMapRange;
+ /**
+ * Sets a custom text range to use when emitting source maps.
+ */
+ function setSourceMapRange(node, range) {
+ getOrCreateEmitNode(node).sourceMapRange = range;
+ return node;
+ }
+ ts.setSourceMapRange = setSourceMapRange;
+ /**
+ * Gets the TextRange to use for source maps for a token of a node.
+ */
+ function getTokenSourceMapRange(node, token) {
+ var _a, _b;
+ return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.tokenSourceMapRanges) === null || _b === void 0 ? void 0 : _b[token];
+ }
+ ts.getTokenSourceMapRange = getTokenSourceMapRange;
+ /**
+ * Sets the TextRange to use for source maps for a token of a node.
+ */
+ function setTokenSourceMapRange(node, token, range) {
+ var _a;
+ var emitNode = getOrCreateEmitNode(node);
+ var tokenSourceMapRanges = (_a = emitNode.tokenSourceMapRanges) !== null && _a !== void 0 ? _a : (emitNode.tokenSourceMapRanges = []);
+ tokenSourceMapRanges[token] = range;
+ return node;
+ }
+ ts.setTokenSourceMapRange = setTokenSourceMapRange;
+ /**
+ * Gets a custom text range to use when emitting comments.
+ */
+ /*@internal*/
+ function getStartsOnNewLine(node) {
+ var _a;
+ return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.startsOnNewLine;
+ }
+ ts.getStartsOnNewLine = getStartsOnNewLine;
+ /**
+ * Sets a custom text range to use when emitting comments.
+ */
+ /*@internal*/
+ function setStartsOnNewLine(node, newLine) {
+ getOrCreateEmitNode(node).startsOnNewLine = newLine;
+ return node;
+ }
+ ts.setStartsOnNewLine = setStartsOnNewLine;
+ /**
+ * Gets a custom text range to use when emitting comments.
+ */
+ function getCommentRange(node) {
+ var _a, _b;
+ return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.commentRange) !== null && _b !== void 0 ? _b : node;
+ }
+ ts.getCommentRange = getCommentRange;
+ /**
+ * Sets a custom text range to use when emitting comments.
+ */
+ function setCommentRange(node, range) {
+ getOrCreateEmitNode(node).commentRange = range;
+ return node;
+ }
+ ts.setCommentRange = setCommentRange;
+ function getSyntheticLeadingComments(node) {
+ var _a;
+ return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.leadingComments;
+ }
+ ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
+ function setSyntheticLeadingComments(node, comments) {
+ getOrCreateEmitNode(node).leadingComments = comments;
+ return node;
+ }
+ ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
+ function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
+ return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
+ }
+ ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
+ function getSyntheticTrailingComments(node) {
+ var _a;
+ return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.trailingComments;
+ }
+ ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
+ function setSyntheticTrailingComments(node, comments) {
+ getOrCreateEmitNode(node).trailingComments = comments;
+ return node;
+ }
+ ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
+ function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
+ return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
+ }
+ ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
+ function moveSyntheticComments(node, original) {
+ setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
+ setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
+ var emit = getOrCreateEmitNode(original);
+ emit.leadingComments = undefined;
+ emit.trailingComments = undefined;
+ return node;
+ }
+ ts.moveSyntheticComments = moveSyntheticComments;
+ /**
+ * Gets the constant value to emit for an expression representing an enum.
+ */
+ function getConstantValue(node) {
+ var _a;
+ return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.constantValue;
+ }
+ ts.getConstantValue = getConstantValue;
+ /**
+ * Sets the constant value to emit for an expression.
+ */
+ function setConstantValue(node, value) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.constantValue = value;
+ return node;
+ }
+ ts.setConstantValue = setConstantValue;
+ /**
+ * Adds an EmitHelper to a node.
+ */
+ function addEmitHelper(node, helper) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.helpers = ts.append(emitNode.helpers, helper);
+ return node;
+ }
+ ts.addEmitHelper = addEmitHelper;
+ /**
+ * Add EmitHelpers to a node.
+ */
+ function addEmitHelpers(node, helpers) {
+ if (ts.some(helpers)) {
+ var emitNode = getOrCreateEmitNode(node);
+ for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
+ var helper = helpers_2[_i];
+ emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
+ }
+ }
+ return node;
+ }
+ ts.addEmitHelpers = addEmitHelpers;
+ /**
+ * Removes an EmitHelper from a node.
+ */
+ function removeEmitHelper(node, helper) {
+ var _a;
+ var helpers = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
+ if (helpers) {
+ return ts.orderedRemoveItem(helpers, helper);
+ }
+ return false;
+ }
+ ts.removeEmitHelper = removeEmitHelper;
+ /**
+ * Gets the EmitHelpers of a node.
+ */
+ function getEmitHelpers(node) {
+ var _a;
+ return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
+ }
+ ts.getEmitHelpers = getEmitHelpers;
+ /**
+ * Moves matching emit helpers from a source node to a target node.
+ */
+ function moveEmitHelpers(source, target, predicate) {
+ var sourceEmitNode = source.emitNode;
+ var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
+ if (!ts.some(sourceEmitHelpers))
+ return;
+ var targetEmitNode = getOrCreateEmitNode(target);
+ var helpersRemoved = 0;
+ for (var i = 0; i < sourceEmitHelpers.length; i++) {
+ var helper = sourceEmitHelpers[i];
+ if (predicate(helper)) {
+ helpersRemoved++;
+ targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
+ }
+ else if (helpersRemoved > 0) {
+ sourceEmitHelpers[i - helpersRemoved] = helper;
+ }
+ }
+ if (helpersRemoved > 0) {
+ sourceEmitHelpers.length -= helpersRemoved;
+ }
+ }
+ ts.moveEmitHelpers = moveEmitHelpers;
+ /**
+ * Gets the SnippetElement of a node.
+ */
+ /* @internal */
+ function getSnippetElement(node) {
+ var _a;
+ return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement;
+ }
+ ts.getSnippetElement = getSnippetElement;
+ /**
+ * Sets the SnippetElement of a node.
+ */
+ /* @internal */
+ function setSnippetElement(node, snippet) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.snippetElement = snippet;
+ return node;
+ }
+ ts.setSnippetElement = setSnippetElement;
+ /* @internal */
+ function ignoreSourceNewlines(node) {
+ getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
+ return node;
+ }
+ ts.ignoreSourceNewlines = ignoreSourceNewlines;
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ function createEmitHelperFactory(context) {
+ var factory = context.factory;
+ var immutableTrue = ts.memoize(function () { return ts.setEmitFlags(factory.createTrue(), 268435456 /* Immutable */); });
+ var immutableFalse = ts.memoize(function () { return ts.setEmitFlags(factory.createFalse(), 268435456 /* Immutable */); });
+ return {
+ getUnscopedHelperName: getUnscopedHelperName,
+ // TypeScript Helpers
+ createDecorateHelper: createDecorateHelper,
+ createMetadataHelper: createMetadataHelper,
+ createParamHelper: createParamHelper,
+ // ES2018 Helpers
+ createAssignHelper: createAssignHelper,
+ createAwaitHelper: createAwaitHelper,
+ createAsyncGeneratorHelper: createAsyncGeneratorHelper,
+ createAsyncDelegatorHelper: createAsyncDelegatorHelper,
+ createAsyncValuesHelper: createAsyncValuesHelper,
+ // ES2018 Destructuring Helpers
+ createRestHelper: createRestHelper,
+ // ES2017 Helpers
+ createAwaiterHelper: createAwaiterHelper,
+ // ES2015 Helpers
+ createExtendsHelper: createExtendsHelper,
+ createTemplateObjectHelper: createTemplateObjectHelper,
+ createSpreadArrayHelper: createSpreadArrayHelper,
+ // ES2015 Destructuring Helpers
+ createValuesHelper: createValuesHelper,
+ createReadHelper: createReadHelper,
+ // ES2015 Generator Helpers
+ createGeneratorHelper: createGeneratorHelper,
+ // ES Module Helpers
+ createCreateBindingHelper: createCreateBindingHelper,
+ createImportStarHelper: createImportStarHelper,
+ createImportStarCallbackHelper: createImportStarCallbackHelper,
+ createImportDefaultHelper: createImportDefaultHelper,
+ createExportStarHelper: createExportStarHelper,
+ // Class Fields Helpers
+ createClassPrivateFieldGetHelper: createClassPrivateFieldGetHelper,
+ createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper,
+ createClassPrivateFieldInHelper: createClassPrivateFieldInHelper
+ };
+ /**
+ * Gets an identifier for the name of an *unscoped* emit helper.
+ */
+ function getUnscopedHelperName(name) {
+ return ts.setEmitFlags(factory.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
+ }
+ // TypeScript Helpers
+ function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
+ context.requestEmitHelper(ts.decorateHelper);
+ var argumentsArray = [];
+ argumentsArray.push(factory.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ true));
+ argumentsArray.push(target);
+ if (memberName) {
+ argumentsArray.push(memberName);
+ if (descriptor) {
+ argumentsArray.push(descriptor);
+ }
+ }
+ return factory.createCallExpression(getUnscopedHelperName("__decorate"),
+ /*typeArguments*/ undefined, argumentsArray);
+ }
+ function createMetadataHelper(metadataKey, metadataValue) {
+ context.requestEmitHelper(ts.metadataHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__metadata"),
+ /*typeArguments*/ undefined, [
+ factory.createStringLiteral(metadataKey),
+ metadataValue
+ ]);
+ }
+ function createParamHelper(expression, parameterOffset, location) {
+ context.requestEmitHelper(ts.paramHelper);
+ return ts.setTextRange(factory.createCallExpression(getUnscopedHelperName("__param"),
+ /*typeArguments*/ undefined, [
+ factory.createNumericLiteral(parameterOffset + ""),
+ expression
+ ]), location);
+ }
+ // ES2018 Helpers
+ function createAssignHelper(attributesSegments) {
+ if (ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
+ return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"),
+ /*typeArguments*/ undefined, attributesSegments);
+ }
+ context.requestEmitHelper(ts.assignHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__assign"),
+ /*typeArguments*/ undefined, attributesSegments);
+ }
+ function createAwaitHelper(expression) {
+ context.requestEmitHelper(ts.awaitHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
+ }
+ function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
+ // Mark this node as originally an async function
+ (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
+ return factory.createCallExpression(getUnscopedHelperName("__asyncGenerator"),
+ /*typeArguments*/ undefined, [
+ hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
+ factory.createIdentifier("arguments"),
+ generatorFunc
+ ]);
+ }
+ function createAsyncDelegatorHelper(expression) {
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
+ return factory.createCallExpression(getUnscopedHelperName("__asyncDelegator"),
+ /*typeArguments*/ undefined, [expression]);
+ }
+ function createAsyncValuesHelper(expression) {
+ context.requestEmitHelper(ts.asyncValues);
+ return factory.createCallExpression(getUnscopedHelperName("__asyncValues"),
+ /*typeArguments*/ undefined, [expression]);
+ }
+ // ES2018 Destructuring Helpers
+ /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
+ * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
+ */
+ function createRestHelper(value, elements, computedTempVariables, location) {
+ context.requestEmitHelper(ts.restHelper);
+ var propertyNames = [];
+ var computedTempVariableOffset = 0;
+ for (var i = 0; i < elements.length - 1; i++) {
+ var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
+ if (propertyName) {
+ if (ts.isComputedPropertyName(propertyName)) {
+ ts.Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
+ var temp = computedTempVariables[computedTempVariableOffset];
+ computedTempVariableOffset++;
+ // typeof _tmp === "symbol" ? _tmp : _tmp + ""
+ propertyNames.push(factory.createConditionalExpression(factory.createTypeCheck(temp, "symbol"),
+ /*questionToken*/ undefined, temp,
+ /*colonToken*/ undefined, factory.createAdd(temp, factory.createStringLiteral(""))));
+ }
+ else {
+ propertyNames.push(factory.createStringLiteralFromNode(propertyName));
+ }
+ }
+ }
+ return factory.createCallExpression(getUnscopedHelperName("__rest"),
+ /*typeArguments*/ undefined, [
+ value,
+ ts.setTextRange(factory.createArrayLiteralExpression(propertyNames), location)
+ ]);
+ }
+ // ES2017 Helpers
+ function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
+ context.requestEmitHelper(ts.awaiterHelper);
+ var generatorFunc = factory.createFunctionExpression(
+ /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */),
+ /*name*/ undefined,
+ /*typeParameters*/ undefined,
+ /*parameters*/ [],
+ /*type*/ undefined, body);
+ // Mark this node as originally an async function
+ (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
+ return factory.createCallExpression(getUnscopedHelperName("__awaiter"),
+ /*typeArguments*/ undefined, [
+ hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
+ hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(),
+ promiseConstructor ? ts.createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(),
+ generatorFunc
+ ]);
+ }
+ // ES2015 Helpers
+ function createExtendsHelper(name) {
+ context.requestEmitHelper(ts.extendsHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__extends"),
+ /*typeArguments*/ undefined, [name, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]);
+ }
+ function createTemplateObjectHelper(cooked, raw) {
+ context.requestEmitHelper(ts.templateObjectHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"),
+ /*typeArguments*/ undefined, [cooked, raw]);
+ }
+ function createSpreadArrayHelper(to, from, packFrom) {
+ context.requestEmitHelper(ts.spreadArrayHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__spreadArray"),
+ /*typeArguments*/ undefined, [to, from, packFrom ? immutableTrue() : immutableFalse()]);
+ }
+ // ES2015 Destructuring Helpers
+ function createValuesHelper(expression) {
+ context.requestEmitHelper(ts.valuesHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__values"),
+ /*typeArguments*/ undefined, [expression]);
+ }
+ function createReadHelper(iteratorRecord, count) {
+ context.requestEmitHelper(ts.readHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__read"),
+ /*typeArguments*/ undefined, count !== undefined
+ ? [iteratorRecord, factory.createNumericLiteral(count + "")]
+ : [iteratorRecord]);
+ }
+ // ES2015 Generator Helpers
+ function createGeneratorHelper(body) {
+ context.requestEmitHelper(ts.generatorHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__generator"),
+ /*typeArguments*/ undefined, [factory.createThis(), body]);
+ }
+ // ES Module Helpers
+ function createCreateBindingHelper(module, inputName, outputName) {
+ context.requestEmitHelper(ts.createBindingHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__createBinding"),
+ /*typeArguments*/ undefined, __spreadArray([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : []), true));
+ }
+ function createImportStarHelper(expression) {
+ context.requestEmitHelper(ts.importStarHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__importStar"),
+ /*typeArguments*/ undefined, [expression]);
+ }
+ function createImportStarCallbackHelper() {
+ context.requestEmitHelper(ts.importStarHelper);
+ return getUnscopedHelperName("__importStar");
+ }
+ function createImportDefaultHelper(expression) {
+ context.requestEmitHelper(ts.importDefaultHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__importDefault"),
+ /*typeArguments*/ undefined, [expression]);
+ }
+ function createExportStarHelper(moduleExpression, exportsExpression) {
+ if (exportsExpression === void 0) { exportsExpression = factory.createIdentifier("exports"); }
+ context.requestEmitHelper(ts.exportStarHelper);
+ context.requestEmitHelper(ts.createBindingHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__exportStar"),
+ /*typeArguments*/ undefined, [moduleExpression, exportsExpression]);
+ }
+ // Class Fields Helpers
+ function createClassPrivateFieldGetHelper(receiver, state, kind, f) {
+ context.requestEmitHelper(ts.classPrivateFieldGetHelper);
+ var args;
+ if (!f) {
+ args = [receiver, state, factory.createStringLiteral(kind)];
+ }
+ else {
+ args = [receiver, state, factory.createStringLiteral(kind), f];
+ }
+ return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args);
+ }
+ function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) {
+ context.requestEmitHelper(ts.classPrivateFieldSetHelper);
+ var args;
+ if (!f) {
+ args = [receiver, state, value, factory.createStringLiteral(kind)];
+ }
+ else {
+ args = [receiver, state, value, factory.createStringLiteral(kind), f];
+ }
+ return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args);
+ }
+ function createClassPrivateFieldInHelper(state, receiver) {
+ context.requestEmitHelper(ts.classPrivateFieldInHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /* typeArguments*/ undefined, [state, receiver]);
+ }
+ }
+ ts.createEmitHelperFactory = createEmitHelperFactory;
+ /* @internal */
+ function compareEmitHelpers(x, y) {
+ if (x === y)
+ return 0 /* EqualTo */;
+ if (x.priority === y.priority)
+ return 0 /* EqualTo */;
+ if (x.priority === undefined)
+ return 1 /* GreaterThan */;
+ if (y.priority === undefined)
+ return -1 /* LessThan */;
+ return ts.compareValues(x.priority, y.priority);
+ }
+ ts.compareEmitHelpers = compareEmitHelpers;
+ /**
+ * @param input Template string input strings
+ * @param args Names which need to be made file-level unique
+ */
+ function helperString(input) {
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ return function (uniqueName) {
+ var result = "";
+ for (var i = 0; i < args.length; i++) {
+ result += input[i];
+ result += uniqueName(args[i]);
+ }
+ result += input[input.length - 1];
+ return result;
+ };
+ }
+ ts.helperString = helperString;
+ // TypeScript Helpers
+ ts.decorateHelper = {
+ name: "typescript:decorate",
+ importName: "__decorate",
+ scoped: false,
+ priority: 2,
+ text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
+ };
+ ts.metadataHelper = {
+ name: "typescript:metadata",
+ importName: "__metadata",
+ scoped: false,
+ priority: 3,
+ text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
+ };
+ ts.paramHelper = {
+ name: "typescript:param",
+ importName: "__param",
+ scoped: false,
+ priority: 4,
+ text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
+ };
+ // ES2018 Helpers
+ ts.assignHelper = {
+ name: "typescript:assign",
+ importName: "__assign",
+ scoped: false,
+ priority: 1,
+ 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 };"
+ };
+ ts.awaitHelper = {
+ name: "typescript:await",
+ importName: "__await",
+ scoped: false,
+ text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
+ };
+ ts.asyncGeneratorHelper = {
+ name: "typescript:asyncGenerator",
+ importName: "__asyncGenerator",
+ scoped: false,
+ dependencies: [ts.awaitHelper],
+ text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
+ };
+ ts.asyncDelegator = {
+ name: "typescript:asyncDelegator",
+ importName: "__asyncDelegator",
+ scoped: false,
+ dependencies: [ts.awaitHelper],
+ text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
+ };
+ ts.asyncValues = {
+ name: "typescript:asyncValues",
+ importName: "__asyncValues",
+ scoped: false,
+ text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
+ };
+ // ES2018 Destructuring Helpers
+ ts.restHelper = {
+ name: "typescript:rest",
+ importName: "__rest",
+ scoped: false,
+ text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n };"
+ };
+ // ES2017 Helpers
+ ts.awaiterHelper = {
+ name: "typescript:awaiter",
+ importName: "__awaiter",
+ scoped: false,
+ priority: 5,
+ text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
+ };
+ // ES2015 Helpers
+ ts.extendsHelper = {
+ name: "typescript:extends",
+ importName: "__extends",
+ scoped: false,
+ priority: 0,
+ 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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
+ };
+ ts.templateObjectHelper = {
+ name: "typescript:makeTemplateObject",
+ importName: "__makeTemplateObject",
+ scoped: false,
+ priority: 0,
+ text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };"
+ };
+ ts.readHelper = {
+ name: "typescript:read",
+ importName: "__read",
+ scoped: false,
+ text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
+ };
+ ts.spreadArrayHelper = {
+ name: "typescript:spreadArray",
+ importName: "__spreadArray",
+ scoped: false,
+ text: "\n var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n };"
+ };
+ // ES2015 Destructuring Helpers
+ ts.valuesHelper = {
+ name: "typescript:values",
+ importName: "__values",
+ scoped: false,
+ text: "\n var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n };"
+ };
+ // ES2015 Generator Helpers
+ // The __generator helper is used by down-level transformations to emulate the runtime
+ // semantics of an ES2015 generator function. When called, this helper returns an
+ // object that implements the Iterator protocol, in that it has `next`, `return`, and
+ // `throw` methods that step through the generator when invoked.
+ //
+ // parameters:
+ // @param thisArg The value to use as the `this` binding for the transformed generator body.
+ // @param body A function that acts as the transformed generator body.
+ //
+ // variables:
+ // _ Persistent state for the generator that is shared between the helper and the
+ // generator body. The state object has the following members:
+ // sent() - A method that returns or throws the current completion value.
+ // label - The next point at which to resume evaluation of the generator body.
+ // trys - A stack of protected regions (try/catch/finally blocks).
+ // ops - A stack of pending instructions when inside of a finally block.
+ // f A value indicating whether the generator is executing.
+ // y An iterator to delegate for a yield*.
+ // t A temporary variable that holds one of the following values (note that these
+ // cases do not overlap):
+ // - The completion value when resuming from a `yield` or `yield*`.
+ // - The error value for a catch block.
+ // - The current protected region (array of try/catch/finally/end labels).
+ // - The verb (`next`, `throw`, or `return` method) to delegate to the expression
+ // of a `yield*`.
+ // - The result of evaluating the verb delegated to the expression of a `yield*`.
+ //
+ // functions:
+ // verb(n) Creates a bound callback to the `step` function for opcode `n`.
+ // step(op) Evaluates opcodes in a generator body until execution is suspended or
+ // completed.
+ //
+ // The __generator helper understands a limited set of instructions:
+ // 0: next(value?) - Start or resume the generator with the specified value.
+ // 1: throw(error) - Resume the generator with an exception. If the generator is
+ // suspended inside of one or more protected regions, evaluates
+ // any intervening finally blocks between the current label and
+ // the nearest catch block or function boundary. If uncaught, the
+ // exception is thrown to the caller.
+ // 2: return(value?) - Resume the generator as if with a return. If the generator is
+ // suspended inside of one or more protected regions, evaluates any
+ // intervening finally blocks.
+ // 3: break(label) - Jump to the specified label. If the label is outside of the
+ // current protected region, evaluates any intervening finally
+ // blocks.
+ // 4: yield(value?) - Yield execution to the caller with an optional value. When
+ // resumed, the generator will continue at the next label.
+ // 5: yield*(value) - Delegates evaluation to the supplied iterator. When
+ // delegation completes, the generator will continue at the next
+ // label.
+ // 6: catch(error) - Handles an exception thrown from within the generator body. If
+ // the current label is inside of one or more protected regions,
+ // evaluates any intervening finally blocks between the current
+ // label and the nearest catch block or function boundary. If
+ // uncaught, the exception is thrown to the caller.
+ // 7: endfinally - Ends a finally block, resuming the last instruction prior to
+ // entering a finally block.
+ //
+ // For examples of how these are used, see the comments in ./transformers/generators.ts
+ ts.generatorHelper = {
+ name: "typescript:generator",
+ importName: "__generator",
+ scoped: false,
+ priority: 6,
+ text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };"
+ };
+ // ES Module Helpers
+ ts.createBindingHelper = {
+ name: "typescript:commonjscreatebinding",
+ importName: "__createBinding",
+ scoped: false,
+ priority: 1,
+ text: "\n var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n }) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n }));"
+ };
+ ts.setModuleDefaultHelper = {
+ name: "typescript:commonjscreatevalue",
+ importName: "__setModuleDefault",
+ scoped: false,
+ priority: 1,
+ text: "\n var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });"
+ };
+ // emit helper for `import * as Name from "foo"`
+ ts.importStarHelper = {
+ name: "typescript:commonjsimportstar",
+ importName: "__importStar",
+ scoped: false,
+ dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
+ priority: 2,
+ text: "\n var __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n };"
+ };
+ // emit helper for `import Name from "foo"`
+ ts.importDefaultHelper = {
+ name: "typescript:commonjsimportdefault",
+ importName: "__importDefault",
+ scoped: false,
+ text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };"
+ };
+ ts.exportStarHelper = {
+ name: "typescript:export-star",
+ importName: "__exportStar",
+ scoped: false,
+ dependencies: [ts.createBindingHelper],
+ priority: 2,
+ text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };"
+ };
+ /**
+ * Parameters:
+ * @param receiver â The object from which the private member will be read.
+ * @param state â One of the following:
+ * - A WeakMap used to read a private instance field.
+ * - A WeakSet used as an instance brand for private instance methods and accessors.
+ * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors.
+ * @param kind â (optional pre TS 4.3, required for TS 4.3+) One of the following values:
+ * - undefined â Indicates a private instance field (pre TS 4.3).
+ * - "f" â Indicates a private field (instance or static).
+ * - "m" â Indicates a private method (instance or static).
+ * - "a" â Indicates a private accessor (instance or static).
+ * @param f â (optional pre TS 4.3) Depends on the arguments for state and kind:
+ * - If kind is "m", this should be the function corresponding to the static or instance method.
+ * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined.
+ * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated.
+ * Usage:
+ * This helper will only ever be used by the compiler in the following ways:
+ *
+ * Reading from a private instance field (pre TS 4.3):
+ * __classPrivateFieldGet(, )
+ *
+ * Reading from a private instance field (TS 4.3+):
+ * __classPrivateFieldGet(, , "f")
+ *
+ * Reading from a private instance get accessor (when defined, TS 4.3+):
+ * __classPrivateFieldGet(, , "a", )
+ *
+ * Reading from a private instance get accessor (when not defined, TS 4.3+):
+ * __classPrivateFieldGet(, , "a", void 0)
+ * NOTE: This always results in a runtime error.
+ *
+ * Reading from a private instance method (TS 4.3+):
+ * __classPrivateFieldGet(, , "m", )
+ *
+ * Reading from a private static field (TS 4.3+):
+ * __classPrivateFieldGet(, , "f", <{ value: any }>)
+ *
+ * Reading from a private static get accessor (when defined, TS 4.3+):
+ * __classPrivateFieldGet(, , "a", )
+ *
+ * Reading from a private static get accessor (when not defined, TS 4.3+):
+ * __classPrivateFieldGet(, , "a", void 0)
+ * NOTE: This always results in a runtime error.
+ *
+ * Reading from a private static method (TS 4.3+):
+ * __classPrivateFieldGet(, , "m", )
+ */
+ ts.classPrivateFieldGetHelper = {
+ name: "typescript:classPrivateFieldGet",
+ importName: "__classPrivateFieldGet",
+ scoped: false,
+ text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };"
+ };
+ /**
+ * Parameters:
+ * @param receiver â The object on which the private member will be set.
+ * @param state â One of the following:
+ * - A WeakMap used to store a private instance field.
+ * - A WeakSet used as an instance brand for private instance methods and accessors.
+ * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors.
+ * @param value â The value to set.
+ * @param kind â (optional pre TS 4.3, required for TS 4.3+) One of the following values:
+ * - undefined â Indicates a private instance field (pre TS 4.3).
+ * - "f" â Indicates a private field (instance or static).
+ * - "m" â Indicates a private method (instance or static).
+ * - "a" â Indicates a private accessor (instance or static).
+ * @param f â (optional pre TS 4.3) Depends on the arguments for state and kind:
+ * - If kind is "m", this should be the function corresponding to the static or instance method.
+ * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined.
+ * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated.
+ * Usage:
+ * This helper will only ever be used by the compiler in the following ways:
+ *
+ * Writing to a private instance field (pre TS 4.3):
+ * __classPrivateFieldSet(, , )
+ *
+ * Writing to a private instance field (TS 4.3+):
+ * __classPrivateFieldSet(, , , "f")
+ *
+ * Writing to a private instance set accessor (when defined, TS 4.3+):
+ * __classPrivateFieldSet(, , , "a", )
+ *
+ * Writing to a private instance set accessor (when not defined, TS 4.3+):
+ * __classPrivateFieldSet(, , , "a", void 0)
+ * NOTE: This always results in a runtime error.
+ *
+ * Writing to a private instance method (TS 4.3+):
+ * __classPrivateFieldSet(, , , "m", )
+ * NOTE: This always results in a runtime error.
+ *
+ * Writing to a private static field (TS 4.3+):
+ * __classPrivateFieldSet(, , , "f", <{ value: any }>)
+ *
+ * Writing to a private static set accessor (when defined, TS 4.3+):
+ * __classPrivateFieldSet(, , , "a", )
+ *
+ * Writing to a private static set accessor (when not defined, TS 4.3+):
+ * __classPrivateFieldSet(, , , "a", void 0)
+ * NOTE: This always results in a runtime error.
+ *
+ * Writing to a private static method (TS 4.3+):
+ * __classPrivateFieldSet(, , , "m", )
+ * NOTE: This always results in a runtime error.
+ */
+ ts.classPrivateFieldSetHelper = {
+ name: "typescript:classPrivateFieldSet",
+ importName: "__classPrivateFieldSet",
+ scoped: false,
+ text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };"
+ };
+ /**
+ * Parameters:
+ * @param state â One of the following:
+ * - A WeakMap when the member is a private instance field.
+ * - A WeakSet when the member is a private instance method or accessor.
+ * - A function value that should be the undecorated class constructor when the member is a private static field, method, or accessor.
+ * @param receiver â The object being checked if it has the private member.
+ *
+ * Usage:
+ * This helper is used to transform `#field in expression` to
+ * `__classPrivateFieldIn(, expression)`
+ */
+ ts.classPrivateFieldInHelper = {
+ name: "typescript:classPrivateFieldIn",
+ importName: "__classPrivateFieldIn",
+ scoped: false,
+ text: "\n var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n };"
+ };
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.restHelper,
+ ts.awaiterHelper,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.spreadArrayHelper,
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper,
+ ts.exportStarHelper,
+ ts.classPrivateFieldGetHelper,
+ ts.classPrivateFieldSetHelper,
+ ts.classPrivateFieldInHelper,
+ ts.createBindingHelper,
+ ts.setModuleDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
+ ts.asyncSuperHelper = {
+ name: "typescript:async-super",
+ scoped: true,
+ text: helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex")
+ };
+ ts.advancedAsyncSuperHelper = {
+ name: "typescript:advanced-async-super",
+ scoped: true,
+ text: helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex")
+ };
+ function isCallToHelper(firstSegment, helperName) {
+ return ts.isCallExpression(firstSegment)
+ && ts.isIdentifier(firstSegment.expression)
+ && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) !== 0
+ && firstSegment.expression.escapedText === helperName;
+ }
+ ts.isCallToHelper = isCallToHelper;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ // Literals
+ function isNumericLiteral(node) {
+ return node.kind === 8 /* NumericLiteral */;
+ }
+ ts.isNumericLiteral = isNumericLiteral;
+ function isBigIntLiteral(node) {
+ return node.kind === 9 /* BigIntLiteral */;
+ }
+ ts.isBigIntLiteral = isBigIntLiteral;
+ function isStringLiteral(node) {
+ return node.kind === 10 /* StringLiteral */;
+ }
+ ts.isStringLiteral = isStringLiteral;
+ function isJsxText(node) {
+ return node.kind === 11 /* JsxText */;
+ }
+ ts.isJsxText = isJsxText;
+ function isRegularExpressionLiteral(node) {
+ return node.kind === 13 /* RegularExpressionLiteral */;
+ }
+ ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
+ function isNoSubstitutionTemplateLiteral(node) {
+ return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
+ }
+ ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
+ // Pseudo-literals
+ function isTemplateHead(node) {
+ return node.kind === 15 /* TemplateHead */;
+ }
+ ts.isTemplateHead = isTemplateHead;
+ function isTemplateMiddle(node) {
+ return node.kind === 16 /* TemplateMiddle */;
+ }
+ ts.isTemplateMiddle = isTemplateMiddle;
+ function isTemplateTail(node) {
+ return node.kind === 17 /* TemplateTail */;
+ }
+ ts.isTemplateTail = isTemplateTail;
+ // Punctuation
+ function isDotDotDotToken(node) {
+ return node.kind === 25 /* DotDotDotToken */;
+ }
+ ts.isDotDotDotToken = isDotDotDotToken;
+ /*@internal*/
+ function isCommaToken(node) {
+ return node.kind === 27 /* CommaToken */;
+ }
+ ts.isCommaToken = isCommaToken;
+ function isPlusToken(node) {
+ return node.kind === 39 /* PlusToken */;
+ }
+ ts.isPlusToken = isPlusToken;
+ function isMinusToken(node) {
+ return node.kind === 40 /* MinusToken */;
+ }
+ ts.isMinusToken = isMinusToken;
+ function isAsteriskToken(node) {
+ return node.kind === 41 /* AsteriskToken */;
+ }
+ ts.isAsteriskToken = isAsteriskToken;
+ /*@internal*/
+ function isExclamationToken(node) {
+ return node.kind === 53 /* ExclamationToken */;
+ }
+ ts.isExclamationToken = isExclamationToken;
+ /*@internal*/
+ function isQuestionToken(node) {
+ return node.kind === 57 /* QuestionToken */;
+ }
+ ts.isQuestionToken = isQuestionToken;
+ /*@internal*/
+ function isColonToken(node) {
+ return node.kind === 58 /* ColonToken */;
+ }
+ ts.isColonToken = isColonToken;
+ /*@internal*/
+ function isQuestionDotToken(node) {
+ return node.kind === 28 /* QuestionDotToken */;
+ }
+ ts.isQuestionDotToken = isQuestionDotToken;
+ /*@internal*/
+ function isEqualsGreaterThanToken(node) {
+ return node.kind === 38 /* EqualsGreaterThanToken */;
+ }
+ ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken;
+ // Identifiers
+ function isIdentifier(node) {
+ return node.kind === 79 /* Identifier */;
+ }
+ ts.isIdentifier = isIdentifier;
+ function isPrivateIdentifier(node) {
+ return node.kind === 80 /* PrivateIdentifier */;
+ }
+ ts.isPrivateIdentifier = isPrivateIdentifier;
+ // Reserved Words
+ /* @internal */
+ function isExportModifier(node) {
+ return node.kind === 93 /* ExportKeyword */;
+ }
+ ts.isExportModifier = isExportModifier;
+ /* @internal */
+ function isAsyncModifier(node) {
+ return node.kind === 131 /* AsyncKeyword */;
+ }
+ ts.isAsyncModifier = isAsyncModifier;
+ /* @internal */
+ function isAssertsKeyword(node) {
+ return node.kind === 128 /* AssertsKeyword */;
+ }
+ ts.isAssertsKeyword = isAssertsKeyword;
+ /* @internal */
+ function isAwaitKeyword(node) {
+ return node.kind === 132 /* AwaitKeyword */;
+ }
+ ts.isAwaitKeyword = isAwaitKeyword;
+ /* @internal */
+ function isReadonlyKeyword(node) {
+ return node.kind === 144 /* ReadonlyKeyword */;
+ }
+ ts.isReadonlyKeyword = isReadonlyKeyword;
+ /* @internal */
+ function isStaticModifier(node) {
+ return node.kind === 124 /* StaticKeyword */;
+ }
+ ts.isStaticModifier = isStaticModifier;
+ /* @internal */
+ function isAbstractModifier(node) {
+ return node.kind === 126 /* AbstractKeyword */;
+ }
+ ts.isAbstractModifier = isAbstractModifier;
+ /*@internal*/
+ function isSuperKeyword(node) {
+ return node.kind === 106 /* SuperKeyword */;
+ }
+ ts.isSuperKeyword = isSuperKeyword;
+ /*@internal*/
+ function isImportKeyword(node) {
+ return node.kind === 100 /* ImportKeyword */;
+ }
+ ts.isImportKeyword = isImportKeyword;
+ // Names
+ function isQualifiedName(node) {
+ return node.kind === 160 /* QualifiedName */;
+ }
+ ts.isQualifiedName = isQualifiedName;
+ function isComputedPropertyName(node) {
+ return node.kind === 161 /* ComputedPropertyName */;
+ }
+ ts.isComputedPropertyName = isComputedPropertyName;
+ // Signature elements
+ function isTypeParameterDeclaration(node) {
+ return node.kind === 162 /* TypeParameter */;
+ }
+ ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
+ // TODO(rbuckton): Rename to 'isParameterDeclaration'
+ function isParameter(node) {
+ return node.kind === 163 /* Parameter */;
+ }
+ ts.isParameter = isParameter;
+ function isDecorator(node) {
+ return node.kind === 164 /* Decorator */;
+ }
+ ts.isDecorator = isDecorator;
+ // TypeMember
+ function isPropertySignature(node) {
+ return node.kind === 165 /* PropertySignature */;
+ }
+ ts.isPropertySignature = isPropertySignature;
+ function isPropertyDeclaration(node) {
+ return node.kind === 166 /* PropertyDeclaration */;
+ }
+ ts.isPropertyDeclaration = isPropertyDeclaration;
+ function isMethodSignature(node) {
+ return node.kind === 167 /* MethodSignature */;
+ }
+ ts.isMethodSignature = isMethodSignature;
+ function isMethodDeclaration(node) {
+ return node.kind === 168 /* MethodDeclaration */;
+ }
+ ts.isMethodDeclaration = isMethodDeclaration;
+ function isClassStaticBlockDeclaration(node) {
+ return node.kind === 169 /* ClassStaticBlockDeclaration */;
+ }
+ ts.isClassStaticBlockDeclaration = isClassStaticBlockDeclaration;
+ function isConstructorDeclaration(node) {
+ return node.kind === 170 /* Constructor */;
+ }
+ ts.isConstructorDeclaration = isConstructorDeclaration;
+ function isGetAccessorDeclaration(node) {
+ return node.kind === 171 /* GetAccessor */;
+ }
+ ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
+ function isSetAccessorDeclaration(node) {
+ return node.kind === 172 /* SetAccessor */;
+ }
+ ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
+ function isCallSignatureDeclaration(node) {
+ return node.kind === 173 /* CallSignature */;
+ }
+ ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
+ function isConstructSignatureDeclaration(node) {
+ return node.kind === 174 /* ConstructSignature */;
+ }
+ ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
+ function isIndexSignatureDeclaration(node) {
+ return node.kind === 175 /* IndexSignature */;
+ }
+ ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ // Type
+ function isTypePredicateNode(node) {
+ return node.kind === 176 /* TypePredicate */;
+ }
+ ts.isTypePredicateNode = isTypePredicateNode;
+ function isTypeReferenceNode(node) {
+ return node.kind === 177 /* TypeReference */;
+ }
+ ts.isTypeReferenceNode = isTypeReferenceNode;
+ function isFunctionTypeNode(node) {
+ return node.kind === 178 /* FunctionType */;
+ }
+ ts.isFunctionTypeNode = isFunctionTypeNode;
+ function isConstructorTypeNode(node) {
+ return node.kind === 179 /* ConstructorType */;
+ }
+ ts.isConstructorTypeNode = isConstructorTypeNode;
+ function isTypeQueryNode(node) {
+ return node.kind === 180 /* TypeQuery */;
+ }
+ ts.isTypeQueryNode = isTypeQueryNode;
+ function isTypeLiteralNode(node) {
+ return node.kind === 181 /* TypeLiteral */;
+ }
+ ts.isTypeLiteralNode = isTypeLiteralNode;
+ function isArrayTypeNode(node) {
+ return node.kind === 182 /* ArrayType */;
+ }
+ ts.isArrayTypeNode = isArrayTypeNode;
+ function isTupleTypeNode(node) {
+ return node.kind === 183 /* TupleType */;
+ }
+ ts.isTupleTypeNode = isTupleTypeNode;
+ function isNamedTupleMember(node) {
+ return node.kind === 196 /* NamedTupleMember */;
+ }
+ ts.isNamedTupleMember = isNamedTupleMember;
+ function isOptionalTypeNode(node) {
+ return node.kind === 184 /* OptionalType */;
+ }
+ ts.isOptionalTypeNode = isOptionalTypeNode;
+ function isRestTypeNode(node) {
+ return node.kind === 185 /* RestType */;
+ }
+ ts.isRestTypeNode = isRestTypeNode;
+ function isUnionTypeNode(node) {
+ return node.kind === 186 /* UnionType */;
+ }
+ ts.isUnionTypeNode = isUnionTypeNode;
+ function isIntersectionTypeNode(node) {
+ return node.kind === 187 /* IntersectionType */;
+ }
+ ts.isIntersectionTypeNode = isIntersectionTypeNode;
+ function isConditionalTypeNode(node) {
+ return node.kind === 188 /* ConditionalType */;
+ }
+ ts.isConditionalTypeNode = isConditionalTypeNode;
+ function isInferTypeNode(node) {
+ return node.kind === 189 /* InferType */;
+ }
+ ts.isInferTypeNode = isInferTypeNode;
+ function isParenthesizedTypeNode(node) {
+ return node.kind === 190 /* ParenthesizedType */;
+ }
+ ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
+ function isThisTypeNode(node) {
+ return node.kind === 191 /* ThisType */;
+ }
+ ts.isThisTypeNode = isThisTypeNode;
+ function isTypeOperatorNode(node) {
+ return node.kind === 192 /* TypeOperator */;
+ }
+ ts.isTypeOperatorNode = isTypeOperatorNode;
+ function isIndexedAccessTypeNode(node) {
+ return node.kind === 193 /* IndexedAccessType */;
+ }
+ ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
+ function isMappedTypeNode(node) {
+ return node.kind === 194 /* MappedType */;
+ }
+ ts.isMappedTypeNode = isMappedTypeNode;
+ function isLiteralTypeNode(node) {
+ return node.kind === 195 /* LiteralType */;
+ }
+ ts.isLiteralTypeNode = isLiteralTypeNode;
+ function isImportTypeNode(node) {
+ return node.kind === 199 /* ImportType */;
+ }
+ ts.isImportTypeNode = isImportTypeNode;
+ function isTemplateLiteralTypeSpan(node) {
+ return node.kind === 198 /* TemplateLiteralTypeSpan */;
+ }
+ ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan;
+ function isTemplateLiteralTypeNode(node) {
+ return node.kind === 197 /* TemplateLiteralType */;
+ }
+ ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode;
+ // Binding patterns
+ function isObjectBindingPattern(node) {
+ return node.kind === 200 /* ObjectBindingPattern */;
+ }
+ ts.isObjectBindingPattern = isObjectBindingPattern;
+ function isArrayBindingPattern(node) {
+ return node.kind === 201 /* ArrayBindingPattern */;
+ }
+ ts.isArrayBindingPattern = isArrayBindingPattern;
+ function isBindingElement(node) {
+ return node.kind === 202 /* BindingElement */;
+ }
+ ts.isBindingElement = isBindingElement;
+ // Expression
+ function isArrayLiteralExpression(node) {
+ return node.kind === 203 /* ArrayLiteralExpression */;
+ }
+ ts.isArrayLiteralExpression = isArrayLiteralExpression;
+ function isObjectLiteralExpression(node) {
+ return node.kind === 204 /* ObjectLiteralExpression */;
+ }
+ ts.isObjectLiteralExpression = isObjectLiteralExpression;
+ function isPropertyAccessExpression(node) {
+ return node.kind === 205 /* PropertyAccessExpression */;
+ }
+ ts.isPropertyAccessExpression = isPropertyAccessExpression;
+ function isElementAccessExpression(node) {
+ return node.kind === 206 /* ElementAccessExpression */;
+ }
+ ts.isElementAccessExpression = isElementAccessExpression;
+ function isCallExpression(node) {
+ return node.kind === 207 /* CallExpression */;
+ }
+ ts.isCallExpression = isCallExpression;
+ function isNewExpression(node) {
+ return node.kind === 208 /* NewExpression */;
+ }
+ ts.isNewExpression = isNewExpression;
+ function isTaggedTemplateExpression(node) {
+ return node.kind === 209 /* TaggedTemplateExpression */;
+ }
+ ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
+ function isTypeAssertionExpression(node) {
+ return node.kind === 210 /* TypeAssertionExpression */;
+ }
+ ts.isTypeAssertionExpression = isTypeAssertionExpression;
+ function isParenthesizedExpression(node) {
+ return node.kind === 211 /* ParenthesizedExpression */;
+ }
+ ts.isParenthesizedExpression = isParenthesizedExpression;
+ function isFunctionExpression(node) {
+ return node.kind === 212 /* FunctionExpression */;
+ }
+ ts.isFunctionExpression = isFunctionExpression;
+ function isArrowFunction(node) {
+ return node.kind === 213 /* ArrowFunction */;
+ }
+ ts.isArrowFunction = isArrowFunction;
+ function isDeleteExpression(node) {
+ return node.kind === 214 /* DeleteExpression */;
+ }
+ ts.isDeleteExpression = isDeleteExpression;
+ function isTypeOfExpression(node) {
+ return node.kind === 215 /* TypeOfExpression */;
+ }
+ ts.isTypeOfExpression = isTypeOfExpression;
+ function isVoidExpression(node) {
+ return node.kind === 216 /* VoidExpression */;
+ }
+ ts.isVoidExpression = isVoidExpression;
+ function isAwaitExpression(node) {
+ return node.kind === 217 /* AwaitExpression */;
+ }
+ ts.isAwaitExpression = isAwaitExpression;
+ function isPrefixUnaryExpression(node) {
+ return node.kind === 218 /* PrefixUnaryExpression */;
+ }
+ ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
+ function isPostfixUnaryExpression(node) {
+ return node.kind === 219 /* PostfixUnaryExpression */;
+ }
+ ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
+ function isBinaryExpression(node) {
+ return node.kind === 220 /* BinaryExpression */;
+ }
+ ts.isBinaryExpression = isBinaryExpression;
+ function isConditionalExpression(node) {
+ return node.kind === 221 /* ConditionalExpression */;
+ }
+ ts.isConditionalExpression = isConditionalExpression;
+ function isTemplateExpression(node) {
+ return node.kind === 222 /* TemplateExpression */;
+ }
+ ts.isTemplateExpression = isTemplateExpression;
+ function isYieldExpression(node) {
+ return node.kind === 223 /* YieldExpression */;
+ }
+ ts.isYieldExpression = isYieldExpression;
+ function isSpreadElement(node) {
+ return node.kind === 224 /* SpreadElement */;
+ }
+ ts.isSpreadElement = isSpreadElement;
+ function isClassExpression(node) {
+ return node.kind === 225 /* ClassExpression */;
+ }
+ ts.isClassExpression = isClassExpression;
+ function isOmittedExpression(node) {
+ return node.kind === 226 /* OmittedExpression */;
+ }
+ ts.isOmittedExpression = isOmittedExpression;
+ function isExpressionWithTypeArguments(node) {
+ return node.kind === 227 /* ExpressionWithTypeArguments */;
+ }
+ ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
+ function isAsExpression(node) {
+ return node.kind === 228 /* AsExpression */;
+ }
+ ts.isAsExpression = isAsExpression;
+ function isNonNullExpression(node) {
+ return node.kind === 229 /* NonNullExpression */;
+ }
+ ts.isNonNullExpression = isNonNullExpression;
+ function isMetaProperty(node) {
+ return node.kind === 230 /* MetaProperty */;
+ }
+ ts.isMetaProperty = isMetaProperty;
+ function isSyntheticExpression(node) {
+ return node.kind === 231 /* SyntheticExpression */;
+ }
+ ts.isSyntheticExpression = isSyntheticExpression;
+ function isPartiallyEmittedExpression(node) {
+ return node.kind === 348 /* PartiallyEmittedExpression */;
+ }
+ ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
+ function isCommaListExpression(node) {
+ return node.kind === 349 /* CommaListExpression */;
+ }
+ ts.isCommaListExpression = isCommaListExpression;
+ // Misc
+ function isTemplateSpan(node) {
+ return node.kind === 232 /* TemplateSpan */;
+ }
+ ts.isTemplateSpan = isTemplateSpan;
+ function isSemicolonClassElement(node) {
+ return node.kind === 233 /* SemicolonClassElement */;
+ }
+ ts.isSemicolonClassElement = isSemicolonClassElement;
+ // Elements
+ function isBlock(node) {
+ return node.kind === 234 /* Block */;
+ }
+ ts.isBlock = isBlock;
+ function isVariableStatement(node) {
+ return node.kind === 236 /* VariableStatement */;
+ }
+ ts.isVariableStatement = isVariableStatement;
+ function isEmptyStatement(node) {
+ return node.kind === 235 /* EmptyStatement */;
+ }
+ ts.isEmptyStatement = isEmptyStatement;
+ function isExpressionStatement(node) {
+ return node.kind === 237 /* ExpressionStatement */;
+ }
+ ts.isExpressionStatement = isExpressionStatement;
+ function isIfStatement(node) {
+ return node.kind === 238 /* IfStatement */;
+ }
+ ts.isIfStatement = isIfStatement;
+ function isDoStatement(node) {
+ return node.kind === 239 /* DoStatement */;
+ }
+ ts.isDoStatement = isDoStatement;
+ function isWhileStatement(node) {
+ return node.kind === 240 /* WhileStatement */;
+ }
+ ts.isWhileStatement = isWhileStatement;
+ function isForStatement(node) {
+ return node.kind === 241 /* ForStatement */;
+ }
+ ts.isForStatement = isForStatement;
+ function isForInStatement(node) {
+ return node.kind === 242 /* ForInStatement */;
+ }
+ ts.isForInStatement = isForInStatement;
+ function isForOfStatement(node) {
+ return node.kind === 243 /* ForOfStatement */;
+ }
+ ts.isForOfStatement = isForOfStatement;
+ function isContinueStatement(node) {
+ return node.kind === 244 /* ContinueStatement */;
+ }
+ ts.isContinueStatement = isContinueStatement;
+ function isBreakStatement(node) {
+ return node.kind === 245 /* BreakStatement */;
+ }
+ ts.isBreakStatement = isBreakStatement;
+ function isReturnStatement(node) {
+ return node.kind === 246 /* ReturnStatement */;
+ }
+ ts.isReturnStatement = isReturnStatement;
+ function isWithStatement(node) {
+ return node.kind === 247 /* WithStatement */;
+ }
+ ts.isWithStatement = isWithStatement;
+ function isSwitchStatement(node) {
+ return node.kind === 248 /* SwitchStatement */;
+ }
+ ts.isSwitchStatement = isSwitchStatement;
+ function isLabeledStatement(node) {
+ return node.kind === 249 /* LabeledStatement */;
+ }
+ ts.isLabeledStatement = isLabeledStatement;
+ function isThrowStatement(node) {
+ return node.kind === 250 /* ThrowStatement */;
+ }
+ ts.isThrowStatement = isThrowStatement;
+ function isTryStatement(node) {
+ return node.kind === 251 /* TryStatement */;
+ }
+ ts.isTryStatement = isTryStatement;
+ function isDebuggerStatement(node) {
+ return node.kind === 252 /* DebuggerStatement */;
+ }
+ ts.isDebuggerStatement = isDebuggerStatement;
+ function isVariableDeclaration(node) {
+ return node.kind === 253 /* VariableDeclaration */;
+ }
+ ts.isVariableDeclaration = isVariableDeclaration;
+ function isVariableDeclarationList(node) {
+ return node.kind === 254 /* VariableDeclarationList */;
+ }
+ ts.isVariableDeclarationList = isVariableDeclarationList;
+ function isFunctionDeclaration(node) {
+ return node.kind === 255 /* FunctionDeclaration */;
+ }
+ ts.isFunctionDeclaration = isFunctionDeclaration;
+ function isClassDeclaration(node) {
+ return node.kind === 256 /* ClassDeclaration */;
+ }
+ ts.isClassDeclaration = isClassDeclaration;
+ function isInterfaceDeclaration(node) {
+ return node.kind === 257 /* InterfaceDeclaration */;
+ }
+ ts.isInterfaceDeclaration = isInterfaceDeclaration;
+ function isTypeAliasDeclaration(node) {
+ return node.kind === 258 /* TypeAliasDeclaration */;
+ }
+ ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
+ function isEnumDeclaration(node) {
+ return node.kind === 259 /* EnumDeclaration */;
+ }
+ ts.isEnumDeclaration = isEnumDeclaration;
+ function isModuleDeclaration(node) {
+ return node.kind === 260 /* ModuleDeclaration */;
+ }
+ ts.isModuleDeclaration = isModuleDeclaration;
+ function isModuleBlock(node) {
+ return node.kind === 261 /* ModuleBlock */;
+ }
+ ts.isModuleBlock = isModuleBlock;
+ function isCaseBlock(node) {
+ return node.kind === 262 /* CaseBlock */;
+ }
+ ts.isCaseBlock = isCaseBlock;
+ function isNamespaceExportDeclaration(node) {
+ return node.kind === 263 /* NamespaceExportDeclaration */;
+ }
+ ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
+ function isImportEqualsDeclaration(node) {
+ return node.kind === 264 /* ImportEqualsDeclaration */;
+ }
+ ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
+ function isImportDeclaration(node) {
+ return node.kind === 265 /* ImportDeclaration */;
+ }
+ ts.isImportDeclaration = isImportDeclaration;
+ function isImportClause(node) {
+ return node.kind === 266 /* ImportClause */;
+ }
+ ts.isImportClause = isImportClause;
+ function isAssertClause(node) {
+ return node.kind === 292 /* AssertClause */;
+ }
+ ts.isAssertClause = isAssertClause;
+ function isAssertEntry(node) {
+ return node.kind === 293 /* AssertEntry */;
+ }
+ ts.isAssertEntry = isAssertEntry;
+ function isNamespaceImport(node) {
+ return node.kind === 267 /* NamespaceImport */;
+ }
+ ts.isNamespaceImport = isNamespaceImport;
+ function isNamespaceExport(node) {
+ return node.kind === 273 /* NamespaceExport */;
+ }
+ ts.isNamespaceExport = isNamespaceExport;
+ function isNamedImports(node) {
+ return node.kind === 268 /* NamedImports */;
+ }
+ ts.isNamedImports = isNamedImports;
+ function isImportSpecifier(node) {
+ return node.kind === 269 /* ImportSpecifier */;
+ }
+ ts.isImportSpecifier = isImportSpecifier;
+ function isExportAssignment(node) {
+ return node.kind === 270 /* ExportAssignment */;
+ }
+ ts.isExportAssignment = isExportAssignment;
+ function isExportDeclaration(node) {
+ return node.kind === 271 /* ExportDeclaration */;
+ }
+ ts.isExportDeclaration = isExportDeclaration;
+ function isNamedExports(node) {
+ return node.kind === 272 /* NamedExports */;
+ }
+ ts.isNamedExports = isNamedExports;
+ function isExportSpecifier(node) {
+ return node.kind === 274 /* ExportSpecifier */;
+ }
+ ts.isExportSpecifier = isExportSpecifier;
+ function isMissingDeclaration(node) {
+ return node.kind === 275 /* MissingDeclaration */;
+ }
+ ts.isMissingDeclaration = isMissingDeclaration;
+ function isNotEmittedStatement(node) {
+ return node.kind === 347 /* NotEmittedStatement */;
+ }
+ ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
- ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
+ function isSyntheticReference(node) {
+ return node.kind === 352 /* SyntheticReferenceExpression */;
+ }
+ ts.isSyntheticReference = isSyntheticReference;
+ /* @internal */
+ function isMergeDeclarationMarker(node) {
+ return node.kind === 350 /* MergeDeclarationMarker */;
+ }
+ ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
+ /* @internal */
+ function isEndOfDeclarationMarker(node) {
+ return node.kind === 351 /* EndOfDeclarationMarker */;
+ }
+ ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
+ // Module References
+ function isExternalModuleReference(node) {
+ return node.kind === 276 /* ExternalModuleReference */;
+ }
+ ts.isExternalModuleReference = isExternalModuleReference;
+ // JSX
+ function isJsxElement(node) {
+ return node.kind === 277 /* JsxElement */;
+ }
+ ts.isJsxElement = isJsxElement;
+ function isJsxSelfClosingElement(node) {
+ return node.kind === 278 /* JsxSelfClosingElement */;
+ }
+ ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
+ function isJsxOpeningElement(node) {
+ return node.kind === 279 /* JsxOpeningElement */;
+ }
+ ts.isJsxOpeningElement = isJsxOpeningElement;
+ function isJsxClosingElement(node) {
+ return node.kind === 280 /* JsxClosingElement */;
+ }
+ ts.isJsxClosingElement = isJsxClosingElement;
+ function isJsxFragment(node) {
+ return node.kind === 281 /* JsxFragment */;
+ }
+ ts.isJsxFragment = isJsxFragment;
+ function isJsxOpeningFragment(node) {
+ return node.kind === 282 /* JsxOpeningFragment */;
+ }
+ ts.isJsxOpeningFragment = isJsxOpeningFragment;
+ function isJsxClosingFragment(node) {
+ return node.kind === 283 /* JsxClosingFragment */;
+ }
+ ts.isJsxClosingFragment = isJsxClosingFragment;
+ function isJsxAttribute(node) {
+ return node.kind === 284 /* JsxAttribute */;
+ }
+ ts.isJsxAttribute = isJsxAttribute;
+ function isJsxAttributes(node) {
+ return node.kind === 285 /* JsxAttributes */;
+ }
+ ts.isJsxAttributes = isJsxAttributes;
+ function isJsxSpreadAttribute(node) {
+ return node.kind === 286 /* JsxSpreadAttribute */;
+ }
+ ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
+ function isJsxExpression(node) {
+ return node.kind === 287 /* JsxExpression */;
+ }
+ ts.isJsxExpression = isJsxExpression;
+ // Clauses
+ function isCaseClause(node) {
+ return node.kind === 288 /* CaseClause */;
+ }
+ ts.isCaseClause = isCaseClause;
+ function isDefaultClause(node) {
+ return node.kind === 289 /* DefaultClause */;
+ }
+ ts.isDefaultClause = isDefaultClause;
+ function isHeritageClause(node) {
+ return node.kind === 290 /* HeritageClause */;
+ }
+ ts.isHeritageClause = isHeritageClause;
+ function isCatchClause(node) {
+ return node.kind === 291 /* CatchClause */;
+ }
+ ts.isCatchClause = isCatchClause;
+ // Property assignments
+ function isPropertyAssignment(node) {
+ return node.kind === 294 /* PropertyAssignment */;
+ }
+ ts.isPropertyAssignment = isPropertyAssignment;
+ function isShorthandPropertyAssignment(node) {
+ return node.kind === 295 /* ShorthandPropertyAssignment */;
+ }
+ ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
+ function isSpreadAssignment(node) {
+ return node.kind === 296 /* SpreadAssignment */;
+ }
+ ts.isSpreadAssignment = isSpreadAssignment;
+ // Enum
+ function isEnumMember(node) {
+ return node.kind === 297 /* EnumMember */;
+ }
+ ts.isEnumMember = isEnumMember;
+ // Unparsed
+ // TODO(rbuckton): isUnparsedPrologue
+ function isUnparsedPrepend(node) {
+ return node.kind === 299 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ // TODO(rbuckton): isUnparsedText
+ // TODO(rbuckton): isUnparsedInternalText
+ // TODO(rbuckton): isUnparsedSyntheticReference
+ // Top-level nodes
+ function isSourceFile(node) {
+ return node.kind === 303 /* SourceFile */;
+ }
+ ts.isSourceFile = isSourceFile;
+ function isBundle(node) {
+ return node.kind === 304 /* Bundle */;
+ }
+ ts.isBundle = isBundle;
+ function isUnparsedSource(node) {
+ return node.kind === 305 /* UnparsedSource */;
+ }
+ ts.isUnparsedSource = isUnparsedSource;
+ // TODO(rbuckton): isInputFiles
+ // JSDoc Elements
+ function isJSDocTypeExpression(node) {
+ return node.kind === 307 /* JSDocTypeExpression */;
+ }
+ ts.isJSDocTypeExpression = isJSDocTypeExpression;
+ function isJSDocNameReference(node) {
+ return node.kind === 308 /* JSDocNameReference */;
+ }
+ ts.isJSDocNameReference = isJSDocNameReference;
+ function isJSDocMemberName(node) {
+ return node.kind === 309 /* JSDocMemberName */;
+ }
+ ts.isJSDocMemberName = isJSDocMemberName;
+ function isJSDocLink(node) {
+ return node.kind === 322 /* JSDocLink */;
+ }
+ ts.isJSDocLink = isJSDocLink;
+ function isJSDocLinkCode(node) {
+ return node.kind === 323 /* JSDocLinkCode */;
+ }
+ ts.isJSDocLinkCode = isJSDocLinkCode;
+ function isJSDocLinkPlain(node) {
+ return node.kind === 324 /* JSDocLinkPlain */;
+ }
+ ts.isJSDocLinkPlain = isJSDocLinkPlain;
+ function isJSDocAllType(node) {
+ return node.kind === 310 /* JSDocAllType */;
+ }
+ ts.isJSDocAllType = isJSDocAllType;
+ function isJSDocUnknownType(node) {
+ return node.kind === 311 /* JSDocUnknownType */;
+ }
+ ts.isJSDocUnknownType = isJSDocUnknownType;
+ function isJSDocNullableType(node) {
+ return node.kind === 312 /* JSDocNullableType */;
+ }
+ ts.isJSDocNullableType = isJSDocNullableType;
+ function isJSDocNonNullableType(node) {
+ return node.kind === 313 /* JSDocNonNullableType */;
+ }
+ ts.isJSDocNonNullableType = isJSDocNonNullableType;
+ function isJSDocOptionalType(node) {
+ return node.kind === 314 /* JSDocOptionalType */;
+ }
+ ts.isJSDocOptionalType = isJSDocOptionalType;
+ function isJSDocFunctionType(node) {
+ return node.kind === 315 /* JSDocFunctionType */;
+ }
+ ts.isJSDocFunctionType = isJSDocFunctionType;
+ function isJSDocVariadicType(node) {
+ return node.kind === 316 /* JSDocVariadicType */;
+ }
+ ts.isJSDocVariadicType = isJSDocVariadicType;
+ function isJSDocNamepathType(node) {
+ return node.kind === 317 /* JSDocNamepathType */;
+ }
+ ts.isJSDocNamepathType = isJSDocNamepathType;
+ function isJSDoc(node) {
+ return node.kind === 318 /* JSDocComment */;
+ }
+ ts.isJSDoc = isJSDoc;
+ function isJSDocTypeLiteral(node) {
+ return node.kind === 320 /* JSDocTypeLiteral */;
+ }
+ ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
+ function isJSDocSignature(node) {
+ return node.kind === 321 /* JSDocSignature */;
+ }
+ ts.isJSDocSignature = isJSDocSignature;
+ // JSDoc Tags
+ function isJSDocAugmentsTag(node) {
+ return node.kind === 326 /* JSDocAugmentsTag */;
+ }
+ ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
+ function isJSDocAuthorTag(node) {
+ return node.kind === 328 /* JSDocAuthorTag */;
+ }
+ ts.isJSDocAuthorTag = isJSDocAuthorTag;
+ function isJSDocClassTag(node) {
+ return node.kind === 330 /* JSDocClassTag */;
+ }
+ ts.isJSDocClassTag = isJSDocClassTag;
+ function isJSDocCallbackTag(node) {
+ return node.kind === 336 /* JSDocCallbackTag */;
+ }
+ ts.isJSDocCallbackTag = isJSDocCallbackTag;
+ function isJSDocPublicTag(node) {
+ return node.kind === 331 /* JSDocPublicTag */;
+ }
+ ts.isJSDocPublicTag = isJSDocPublicTag;
+ function isJSDocPrivateTag(node) {
+ return node.kind === 332 /* JSDocPrivateTag */;
+ }
+ ts.isJSDocPrivateTag = isJSDocPrivateTag;
+ function isJSDocProtectedTag(node) {
+ return node.kind === 333 /* JSDocProtectedTag */;
+ }
+ ts.isJSDocProtectedTag = isJSDocProtectedTag;
+ function isJSDocReadonlyTag(node) {
+ return node.kind === 334 /* JSDocReadonlyTag */;
+ }
+ ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
+ function isJSDocOverrideTag(node) {
+ return node.kind === 335 /* JSDocOverrideTag */;
+ }
+ ts.isJSDocOverrideTag = isJSDocOverrideTag;
+ function isJSDocDeprecatedTag(node) {
+ return node.kind === 329 /* JSDocDeprecatedTag */;
+ }
+ ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
+ function isJSDocSeeTag(node) {
+ return node.kind === 344 /* JSDocSeeTag */;
+ }
+ ts.isJSDocSeeTag = isJSDocSeeTag;
+ function isJSDocEnumTag(node) {
+ return node.kind === 337 /* JSDocEnumTag */;
+ }
+ ts.isJSDocEnumTag = isJSDocEnumTag;
+ function isJSDocParameterTag(node) {
+ return node.kind === 338 /* JSDocParameterTag */;
+ }
+ ts.isJSDocParameterTag = isJSDocParameterTag;
+ function isJSDocReturnTag(node) {
+ return node.kind === 339 /* JSDocReturnTag */;
+ }
+ ts.isJSDocReturnTag = isJSDocReturnTag;
+ function isJSDocThisTag(node) {
+ return node.kind === 340 /* JSDocThisTag */;
+ }
+ ts.isJSDocThisTag = isJSDocThisTag;
+ function isJSDocTypeTag(node) {
+ return node.kind === 341 /* JSDocTypeTag */;
+ }
+ ts.isJSDocTypeTag = isJSDocTypeTag;
+ function isJSDocTemplateTag(node) {
+ return node.kind === 342 /* JSDocTemplateTag */;
+ }
+ ts.isJSDocTemplateTag = isJSDocTemplateTag;
+ function isJSDocTypedefTag(node) {
+ return node.kind === 343 /* JSDocTypedefTag */;
+ }
+ ts.isJSDocTypedefTag = isJSDocTypedefTag;
+ function isJSDocUnknownTag(node) {
+ return node.kind === 325 /* JSDocTag */;
+ }
+ ts.isJSDocUnknownTag = isJSDocUnknownTag;
+ function isJSDocPropertyTag(node) {
+ return node.kind === 345 /* JSDocPropertyTag */;
+ }
+ ts.isJSDocPropertyTag = isJSDocPropertyTag;
+ function isJSDocImplementsTag(node) {
+ return node.kind === 327 /* JSDocImplementsTag */;
+ }
+ ts.isJSDocImplementsTag = isJSDocImplementsTag;
+ // Synthesized list
+ /* @internal */
+ function isSyntaxList(n) {
+ return n.kind === 346 /* SyntaxList */;
+ }
+ ts.isSyntaxList = isSyntaxList;
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ // Compound nodes
+ function createEmptyExports(factory) {
+ return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
+ }
+ ts.createEmptyExports = createEmptyExports;
+ function createMemberAccessForPropertyName(factory, target, memberName, location) {
+ if (ts.isComputedPropertyName(memberName)) {
+ return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
+ }
+ else {
+ var expression = ts.setTextRange(ts.isMemberName(memberName)
+ ? factory.createPropertyAccessExpression(target, memberName)
+ : factory.createElementAccessExpression(target, memberName), memberName);
+ ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
+ return expression;
+ }
+ }
+ ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
+ function createReactNamespace(reactNamespace, parent) {
+ // To ensure the emit resolver can properly resolve the namespace, we need to
+ // treat this identifier as if it were a source tree node by clearing the `Synthesized`
+ // flag and setting a parent node.
+ var react = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
+ // Set the parent that is in parse tree
+ // this makes sure that parent chain is intact for checker to traverse complete scope tree
+ ts.setParent(react, ts.getParseTreeNode(parent));
+ return react;
+ }
+ function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
+ if (ts.isQualifiedName(jsxFactory)) {
+ var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
+ var right = factory.createIdentifier(ts.idText(jsxFactory.right));
+ right.escapedText = jsxFactory.right.escapedText;
+ return factory.createPropertyAccessExpression(left, right);
+ }
+ else {
+ return createReactNamespace(ts.idText(jsxFactory), parent);
+ }
+ }
+ function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
+ return jsxFactoryEntity ?
+ createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
+ factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
+ }
+ ts.createJsxFactoryExpression = createJsxFactoryExpression;
+ function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
+ return jsxFragmentFactoryEntity ?
+ createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
+ factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
+ }
+ function createExpressionForJsxElement(factory, callee, tagName, props, children, location) {
+ var argumentsList = [tagName];
+ if (props) {
+ argumentsList.push(props);
+ }
+ if (children && children.length > 0) {
+ if (!props) {
+ argumentsList.push(factory.createNull());
+ }
+ if (children.length > 1) {
+ for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
+ var child = children_3[_i];
+ startOnNewLine(child);
+ argumentsList.push(child);
+ }
+ }
+ else {
+ argumentsList.push(children[0]);
+ }
+ }
+ return ts.setTextRange(factory.createCallExpression(callee,
+ /*typeArguments*/ undefined, argumentsList), location);
+ }
+ ts.createExpressionForJsxElement = createExpressionForJsxElement;
+ function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
+ var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
+ var argumentsList = [tagName, factory.createNull()];
+ if (children && children.length > 0) {
+ if (children.length > 1) {
+ for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
+ var child = children_4[_i];
+ startOnNewLine(child);
+ argumentsList.push(child);
+ }
+ }
+ else {
+ argumentsList.push(children[0]);
+ }
+ }
+ return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement),
+ /*typeArguments*/ undefined, argumentsList), location);
+ }
+ ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
+ // Utilities
+ function createForOfBindingStatement(factory, node, boundValue) {
+ if (ts.isVariableDeclarationList(node)) {
+ var firstDeclaration = ts.first(node.declarations);
+ var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name,
+ /*exclamationToken*/ undefined,
+ /*type*/ undefined, boundValue);
+ return ts.setTextRange(factory.createVariableStatement(
+ /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])),
+ /*location*/ node);
+ }
+ else {
+ var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
+ return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
+ }
+ }
+ ts.createForOfBindingStatement = createForOfBindingStatement;
+ function insertLeadingStatement(factory, dest, source) {
+ if (ts.isBlock(dest)) {
+ return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArray([source], dest.statements, true)), dest.statements));
+ }
+ else {
+ return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
+ }
+ }
+ ts.insertLeadingStatement = insertLeadingStatement;
+ function createExpressionFromEntityName(factory, node) {
+ if (ts.isQualifiedName(node)) {
+ var left = createExpressionFromEntityName(factory, node.left);
+ // TODO(rbuckton): Does this need to be parented?
+ var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
+ return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
+ }
+ else {
+ // TODO(rbuckton): Does this need to be parented?
+ return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
+ }
+ }
+ ts.createExpressionFromEntityName = createExpressionFromEntityName;
+ function createExpressionForPropertyName(factory, memberName) {
+ if (ts.isIdentifier(memberName)) {
+ return factory.createStringLiteralFromNode(memberName);
+ }
+ else if (ts.isComputedPropertyName(memberName)) {
+ // TODO(rbuckton): Does this need to be parented?
+ return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
+ }
+ else {
+ // TODO(rbuckton): Does this need to be parented?
+ return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
+ }
+ }
+ ts.createExpressionForPropertyName = createExpressionForPropertyName;
+ function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
+ var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
+ if (property === firstAccessor) {
+ return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
+ enumerable: factory.createFalse(),
+ configurable: true,
+ get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, getAccessor.parameters,
+ /*type*/ undefined, getAccessor.body // TODO: GH#18217
+ ), getAccessor), getAccessor),
+ set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, setAccessor.parameters,
+ /*type*/ undefined, setAccessor.body // TODO: GH#18217
+ ), setAccessor), setAccessor)
+ }, !multiLine)), firstAccessor);
+ }
+ return undefined;
+ }
+ function createExpressionForPropertyAssignment(factory, property, receiver) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
+ }
+ function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)),
+ /*location*/ property),
+ /*original*/ property);
+ }
+ function createExpressionForMethodDeclaration(factory, method, receiver) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, method.parameters,
+ /*type*/ undefined, method.body // TODO: GH#18217
+ ),
+ /*location*/ method),
+ /*original*/ method)),
+ /*location*/ method),
+ /*original*/ method);
+ }
+ function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
+ if (property.name && ts.isPrivateIdentifier(property.name)) {
+ ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
+ }
+ switch (property.kind) {
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
+ case 294 /* PropertyAssignment */:
+ return createExpressionForPropertyAssignment(factory, property, receiver);
+ case 295 /* ShorthandPropertyAssignment */:
+ return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
+ case 168 /* MethodDeclaration */:
+ return createExpressionForMethodDeclaration(factory, property, receiver);
+ }
+ }
+ ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
+ /**
+ * Expand the read and increment/decrement operations a pre- or post-increment or pre- or post-decrement expression.
+ *
+ * ```ts
+ * // input
+ * ++
+ * // output (if result is not discarded)
+ * var ;
+ * ( = , = ++, )
+ * // output (if result is discarded)
+ * var ;
+ * ( = , ++, )
+ *
+ * // input
+ * ++
+ * // output (if result is not discarded)
+ * var ;
+ * ( = , = ++)
+ * // output (if result is discarded)
+ * var ;
+ * ( = , ++)
+ * ```
+ *
+ * It is up to the caller to supply a temporary variable for `` if one is needed.
+ * The temporary variable `` is injected so that `++` and `--` work uniformly with `number` and `bigint`.
+ * The result of the expression is always the final result of incrementing or decrementing the expression, so that it can be used for storage.
+ *
+ * @param factory {@link NodeFactory} used to create the expanded representation.
+ * @param node The original prefix or postfix unary node.
+ * @param expression The expression to use as the value to increment or decrement
+ * @param resultVariable A temporary variable in which to store the result. Pass `undefined` if the result is discarded, or if the value of `` is the expected result.
+ */
+ function expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, recordTempVariable, resultVariable) {
+ var operator = node.operator;
+ ts.Debug.assert(operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */, "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression");
+ var temp = factory.createTempVariable(recordTempVariable);
+ expression = factory.createAssignment(temp, expression);
+ ts.setTextRange(expression, node.operand);
+ var operation = ts.isPrefixUnaryExpression(node) ?
+ factory.createPrefixUnaryExpression(operator, temp) :
+ factory.createPostfixUnaryExpression(temp, operator);
+ ts.setTextRange(operation, node);
+ if (resultVariable) {
+ operation = factory.createAssignment(resultVariable, operation);
+ ts.setTextRange(operation, node);
+ }
+ expression = factory.createComma(expression, operation);
+ ts.setTextRange(expression, node);
+ if (ts.isPostfixUnaryExpression(node)) {
+ expression = factory.createComma(expression, temp);
+ ts.setTextRange(expression, node);
+ }
+ return expression;
+ }
+ ts.expandPreOrPostfixIncrementOrDecrementExpression = expandPreOrPostfixIncrementOrDecrementExpression;
+ /**
+ * Gets whether an identifier should only be referred to by its internal name.
+ */
+ function isInternalName(node) {
+ return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
+ }
+ ts.isInternalName = isInternalName;
+ /**
+ * Gets whether an identifier should only be referred to by its local name.
+ */
+ function isLocalName(node) {
+ return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
+ }
+ ts.isLocalName = isLocalName;
+ /**
+ * Gets whether an identifier should only be referred to by its export representation if the
+ * name points to an exported symbol.
+ */
+ function isExportName(node) {
+ return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
+ }
+ ts.isExportName = isExportName;
+ function isUseStrictPrologue(node) {
+ return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
+ }
+ function findUseStrictPrologue(statements) {
+ for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
+ var statement = statements_1[_i];
+ if (ts.isPrologueDirective(statement)) {
+ if (isUseStrictPrologue(statement)) {
+ return statement;
+ }
+ }
+ else {
+ break;
+ }
+ }
+ return undefined;
+ }
+ ts.findUseStrictPrologue = findUseStrictPrologue;
+ function startsWithUseStrict(statements) {
+ var firstStatement = ts.firstOrUndefined(statements);
+ return firstStatement !== undefined
+ && ts.isPrologueDirective(firstStatement)
+ && isUseStrictPrologue(firstStatement);
+ }
+ ts.startsWithUseStrict = startsWithUseStrict;
+ function isCommaSequence(node) {
+ return node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
+ node.kind === 349 /* CommaListExpression */;
+ }
+ ts.isCommaSequence = isCommaSequence;
+ function isJSDocTypeAssertion(node) {
+ return ts.isParenthesizedExpression(node)
+ && ts.isInJSFile(node)
+ && !!ts.getJSDocTypeTag(node);
+ }
+ ts.isJSDocTypeAssertion = isJSDocTypeAssertion;
+ function getJSDocTypeAssertionType(node) {
+ var type = ts.getJSDocType(node);
+ ts.Debug.assertIsDefined(type);
+ return type;
+ }
+ ts.getJSDocTypeAssertionType = getJSDocTypeAssertionType;
+ function isOuterExpression(node, kinds) {
+ if (kinds === void 0) { kinds = 15 /* All */; }
+ switch (node.kind) {
+ case 211 /* ParenthesizedExpression */:
+ if (kinds & 16 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) {
+ return false;
+ }
+ return (kinds & 1 /* Parentheses */) !== 0;
+ case 210 /* TypeAssertionExpression */:
+ case 228 /* AsExpression */:
+ return (kinds & 2 /* TypeAssertions */) !== 0;
+ case 229 /* NonNullExpression */:
+ return (kinds & 4 /* NonNullAssertions */) !== 0;
+ case 348 /* PartiallyEmittedExpression */:
+ return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
+ }
+ return false;
+ }
+ ts.isOuterExpression = isOuterExpression;
+ function skipOuterExpressions(node, kinds) {
+ if (kinds === void 0) { kinds = 15 /* All */; }
+ while (isOuterExpression(node, kinds)) {
+ node = node.expression;
+ }
+ return node;
+ }
+ ts.skipOuterExpressions = skipOuterExpressions;
+ function skipAssertions(node) {
+ return skipOuterExpressions(node, 6 /* Assertions */);
+ }
+ ts.skipAssertions = skipAssertions;
+ function startOnNewLine(node) {
+ return ts.setStartsOnNewLine(node, /*newLine*/ true);
+ }
+ ts.startOnNewLine = startOnNewLine;
+ function getExternalHelpersModuleName(node) {
+ var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
+ var emitNode = parseNode && parseNode.emitNode;
+ return emitNode && emitNode.externalHelpersModuleName;
+ }
+ ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
+ function hasRecordedExternalHelpers(sourceFile) {
+ var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
+ var emitNode = parseNode && parseNode.emitNode;
+ return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
+ }
+ ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
+ function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
+ if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
+ var namedBindings = void 0;
+ var moduleKind = ts.getEmitModuleKind(compilerOptions);
+ if ((moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) || sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) {
+ // use named imports
+ var helpers = ts.getEmitHelpers(sourceFile);
+ if (helpers) {
+ var helperNames = [];
+ for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
+ var helper = helpers_3[_i];
+ if (!helper.scoped) {
+ var importName = helper.importName;
+ if (importName) {
+ ts.pushIfUnique(helperNames, importName);
+ }
+ }
+ }
+ if (ts.some(helperNames)) {
+ helperNames.sort(ts.compareStringsCaseSensitive);
+ // Alias the imports if the names are used somewhere in the file.
+ // NOTE: We don't need to care about global import collisions as this is a module.
+ namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
+ ? nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, nodeFactory.createIdentifier(name))
+ : nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
+ var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
+ var emitNode = ts.getOrCreateEmitNode(parseNode);
+ emitNode.externalHelpers = true;
+ }
+ }
+ }
+ else {
+ // use a namespace import
+ var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
+ if (externalHelpersModuleName) {
+ namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
+ }
+ }
+ if (namedBindings) {
+ var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText),
+ /*assertClause*/ undefined);
+ ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
+ return externalHelpersImportDeclaration;
+ }
+ }
+ }
+ ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
+ function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
+ if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
+ var externalHelpersModuleName = getExternalHelpersModuleName(node);
+ if (externalHelpersModuleName) {
+ return externalHelpersModuleName;
+ }
+ var moduleKind = ts.getEmitModuleKind(compilerOptions);
+ var create = (hasExportStarsToExportValues || (ts.getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault))
+ && moduleKind !== ts.ModuleKind.System
+ && (moduleKind < ts.ModuleKind.ES2015 || node.impliedNodeFormat === ts.ModuleKind.CommonJS);
+ if (!create) {
+ var helpers = ts.getEmitHelpers(node);
+ if (helpers) {
+ for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
+ var helper = helpers_4[_i];
+ if (!helper.scoped) {
+ create = true;
+ break;
+ }
+ }
+ }
+ }
+ if (create) {
+ var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
+ var emitNode = ts.getOrCreateEmitNode(parseNode);
+ return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
+ }
+ }
+ }
+ ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
+ /**
+ * Get the name of that target module from an import or export declaration
+ */
+ function getLocalNameForExternalImport(factory, node, sourceFile) {
+ var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
+ if (namespaceDeclaration && !ts.isDefaultImport(node) && !ts.isExportNamespaceAsDefaultDeclaration(node)) {
+ var name = namespaceDeclaration.name;
+ return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
+ }
+ if (node.kind === 265 /* ImportDeclaration */ && node.importClause) {
+ return factory.getGeneratedNameForNode(node);
+ }
+ if (node.kind === 271 /* ExportDeclaration */ && node.moduleSpecifier) {
+ return factory.getGeneratedNameForNode(node);
+ }
+ return undefined;
+ }
+ ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
+ /**
+ * Get the name of a target module from an import/export declaration as should be written in the emitted output.
+ * The emitted output name can be different from the input if:
+ * 1. The module has a ///
+ * 2. --out or --outFile is used, making the name relative to the rootDir
+ * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
+ * Otherwise, a new StringLiteral node representing the module name will be returned.
+ */
+ function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
+ var moduleName = ts.getExternalModuleName(importNode);
+ if (moduleName && ts.isStringLiteral(moduleName)) {
+ return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
+ || tryRenameExternalModule(factory, moduleName, sourceFile)
+ || factory.cloneNode(moduleName);
+ }
+ return undefined;
+ }
+ ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
+ /**
+ * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
+ * Here we check if alternative name was provided for a given moduleName and return it if possible.
+ */
+ function tryRenameExternalModule(factory, moduleName, sourceFile) {
+ var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
+ return rename ? factory.createStringLiteral(rename) : undefined;
+ }
+ /**
+ * Get the name of a module as should be written in the emitted output.
+ * The emitted output name can be different from the input if:
+ * 1. The module has a ///
+ * 2. --out or --outFile is used, making the name relative to the rootDir
+ * Otherwise, a new StringLiteral node representing the module name will be returned.
+ */
+ function tryGetModuleNameFromFile(factory, file, host, options) {
+ if (!file) {
+ return undefined;
+ }
+ if (file.moduleName) {
+ return factory.createStringLiteral(file.moduleName);
+ }
+ if (!file.isDeclarationFile && ts.outFile(options)) {
+ return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
+ }
+ return undefined;
+ }
+ ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
+ function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
+ return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
+ }
+ /**
+ * Gets the initializer of an BindingOrAssignmentElement.
+ */
+ function getInitializerOfBindingOrAssignmentElement(bindingElement) {
+ if (ts.isDeclarationBindingElement(bindingElement)) {
+ // `1` in `let { a = 1 } = ...`
+ // `1` in `let { a: b = 1 } = ...`
+ // `1` in `let { a: {b} = 1 } = ...`
+ // `1` in `let { a: [b] = 1 } = ...`
+ // `1` in `let [a = 1] = ...`
+ // `1` in `let [{a} = 1] = ...`
+ // `1` in `let [[a] = 1] = ...`
+ return bindingElement.initializer;
+ }
+ if (ts.isPropertyAssignment(bindingElement)) {
+ // `1` in `({ a: b = 1 } = ...)`
+ // `1` in `({ a: {b} = 1 } = ...)`
+ // `1` in `({ a: [b] = 1 } = ...)`
+ var initializer = bindingElement.initializer;
+ return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
+ ? initializer.right
+ : undefined;
+ }
+ if (ts.isShorthandPropertyAssignment(bindingElement)) {
+ // `1` in `({ a = 1 } = ...)`
+ return bindingElement.objectAssignmentInitializer;
+ }
+ if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
+ // `1` in `[a = 1] = ...`
+ // `1` in `[{a} = 1] = ...`
+ // `1` in `[[a] = 1] = ...`
+ return bindingElement.right;
+ }
+ if (ts.isSpreadElement(bindingElement)) {
+ // Recovery consistent with existing emit.
+ return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
+ }
+ }
+ ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
+ /**
+ * Gets the name of an BindingOrAssignmentElement.
+ */
+ function getTargetOfBindingOrAssignmentElement(bindingElement) {
+ if (ts.isDeclarationBindingElement(bindingElement)) {
+ // `a` in `let { a } = ...`
+ // `a` in `let { a = 1 } = ...`
+ // `b` in `let { a: b } = ...`
+ // `b` in `let { a: b = 1 } = ...`
+ // `a` in `let { ...a } = ...`
+ // `{b}` in `let { a: {b} } = ...`
+ // `{b}` in `let { a: {b} = 1 } = ...`
+ // `[b]` in `let { a: [b] } = ...`
+ // `[b]` in `let { a: [b] = 1 } = ...`
+ // `a` in `let [a] = ...`
+ // `a` in `let [a = 1] = ...`
+ // `a` in `let [...a] = ...`
+ // `{a}` in `let [{a}] = ...`
+ // `{a}` in `let [{a} = 1] = ...`
+ // `[a]` in `let [[a]] = ...`
+ // `[a]` in `let [[a] = 1] = ...`
+ return bindingElement.name;
+ }
+ if (ts.isObjectLiteralElementLike(bindingElement)) {
+ switch (bindingElement.kind) {
+ case 294 /* PropertyAssignment */:
+ // `b` in `({ a: b } = ...)`
+ // `b` in `({ a: b = 1 } = ...)`
+ // `{b}` in `({ a: {b} } = ...)`
+ // `{b}` in `({ a: {b} = 1 } = ...)`
+ // `[b]` in `({ a: [b] } = ...)`
+ // `[b]` in `({ a: [b] = 1 } = ...)`
+ // `b.c` in `({ a: b.c } = ...)`
+ // `b.c` in `({ a: b.c = 1 } = ...)`
+ // `b[0]` in `({ a: b[0] } = ...)`
+ // `b[0]` in `({ a: b[0] = 1 } = ...)`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
+ case 295 /* ShorthandPropertyAssignment */:
+ // `a` in `({ a } = ...)`
+ // `a` in `({ a = 1 } = ...)`
+ return bindingElement.name;
+ case 296 /* SpreadAssignment */:
+ // `a` in `({ ...a } = ...)`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
+ }
+ // no target
+ return undefined;
+ }
+ if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
+ // `a` in `[a = 1] = ...`
+ // `{a}` in `[{a} = 1] = ...`
+ // `[a]` in `[[a] = 1] = ...`
+ // `a.b` in `[a.b = 1] = ...`
+ // `a[0]` in `[a[0] = 1] = ...`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.left);
+ }
+ if (ts.isSpreadElement(bindingElement)) {
+ // `a` in `[...a] = ...`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
+ }
+ // `a` in `[a] = ...`
+ // `{a}` in `[{a}] = ...`
+ // `[a]` in `[[a]] = ...`
+ // `a.b` in `[a.b] = ...`
+ // `a[0]` in `[a[0]] = ...`
+ return bindingElement;
+ }
+ ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
+ /**
+ * Determines whether an BindingOrAssignmentElement is a rest element.
+ */
+ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
+ switch (bindingElement.kind) {
+ case 163 /* Parameter */:
+ case 202 /* BindingElement */:
+ // `...` in `let [...a] = ...`
+ return bindingElement.dotDotDotToken;
+ case 224 /* SpreadElement */:
+ case 296 /* SpreadAssignment */:
+ // `...` in `[...a] = ...`
+ return bindingElement;
+ }
+ return undefined;
+ }
+ ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
+ /**
+ * Gets the property name of a BindingOrAssignmentElement
+ */
+ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
+ var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
+ ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
+ return propertyName;
+ }
+ ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
+ function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
+ switch (bindingElement.kind) {
+ case 202 /* BindingElement */:
+ // `a` in `let { a: b } = ...`
+ // `[a]` in `let { [a]: b } = ...`
+ // `"a"` in `let { "a": b } = ...`
+ // `1` in `let { 1: b } = ...`
+ if (bindingElement.propertyName) {
+ var propertyName = bindingElement.propertyName;
+ if (ts.isPrivateIdentifier(propertyName)) {
+ return ts.Debug.failBadSyntaxKind(propertyName);
+ }
+ return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
+ ? propertyName.expression
+ : propertyName;
+ }
+ break;
+ case 294 /* PropertyAssignment */:
+ // `a` in `({ a: b } = ...)`
+ // `[a]` in `({ [a]: b } = ...)`
+ // `"a"` in `({ "a": b } = ...)`
+ // `1` in `({ 1: b } = ...)`
+ if (bindingElement.name) {
+ var propertyName = bindingElement.name;
+ if (ts.isPrivateIdentifier(propertyName)) {
+ return ts.Debug.failBadSyntaxKind(propertyName);
+ }
+ return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
+ ? propertyName.expression
+ : propertyName;
+ }
+ break;
+ case 296 /* SpreadAssignment */:
+ // `a` in `({ ...a } = ...)`
+ if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
+ return ts.Debug.failBadSyntaxKind(bindingElement.name);
+ }
+ return bindingElement.name;
+ }
+ var target = getTargetOfBindingOrAssignmentElement(bindingElement);
+ if (target && ts.isPropertyName(target)) {
+ return target;
+ }
+ }
+ ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
+ function isStringOrNumericLiteral(node) {
+ var kind = node.kind;
+ return kind === 10 /* StringLiteral */
+ || kind === 8 /* NumericLiteral */;
+ }
+ /**
+ * Gets the elements of a BindingOrAssignmentPattern
+ */
+ function getElementsOfBindingOrAssignmentPattern(name) {
+ switch (name.kind) {
+ case 200 /* ObjectBindingPattern */:
+ case 201 /* ArrayBindingPattern */:
+ case 203 /* ArrayLiteralExpression */:
+ // `a` in `{a}`
+ // `a` in `[a]`
+ return name.elements;
+ case 204 /* ObjectLiteralExpression */:
+ // `a` in `{a}`
+ return name.properties;
+ }
+ }
+ ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
/* @internal */
- ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
+ function getJSDocTypeAliasName(fullName) {
+ if (fullName) {
+ var rightNode = fullName;
+ while (true) {
+ if (ts.isIdentifier(rightNode) || !rightNode.body) {
+ return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
+ }
+ rightNode = rightNode.body;
+ }
+ }
+ }
+ ts.getJSDocTypeAliasName = getJSDocTypeAliasName;
+ function canHaveModifiers(node) {
+ var kind = node.kind;
+ return kind === 163 /* Parameter */
+ || kind === 165 /* PropertySignature */
+ || kind === 166 /* PropertyDeclaration */
+ || kind === 167 /* MethodSignature */
+ || kind === 168 /* MethodDeclaration */
+ || kind === 170 /* Constructor */
+ || kind === 171 /* GetAccessor */
+ || kind === 172 /* SetAccessor */
+ || kind === 175 /* IndexSignature */
+ || kind === 212 /* FunctionExpression */
+ || kind === 213 /* ArrowFunction */
+ || kind === 225 /* ClassExpression */
+ || kind === 236 /* VariableStatement */
+ || kind === 255 /* FunctionDeclaration */
+ || kind === 256 /* ClassDeclaration */
+ || kind === 257 /* InterfaceDeclaration */
+ || kind === 258 /* TypeAliasDeclaration */
+ || kind === 259 /* EnumDeclaration */
+ || kind === 260 /* ModuleDeclaration */
+ || kind === 264 /* ImportEqualsDeclaration */
+ || kind === 265 /* ImportDeclaration */
+ || kind === 270 /* ExportAssignment */
+ || kind === 271 /* ExportDeclaration */;
+ }
+ ts.canHaveModifiers = canHaveModifiers;
+ ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
+ ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken);
+ ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode);
+ ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken);
+ ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken);
+ ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral);
+ function isLiteralTypeLikeExpression(node) {
+ var kind = node.kind;
+ return kind === 104 /* NullKeyword */
+ || kind === 110 /* TrueKeyword */
+ || kind === 95 /* FalseKeyword */
+ || ts.isLiteralExpression(node)
+ || ts.isPrefixUnaryExpression(node);
+ }
+ ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression;
+ function isExponentiationOperator(kind) {
+ return kind === 42 /* AsteriskAsteriskToken */;
+ }
+ function isMultiplicativeOperator(kind) {
+ return kind === 41 /* AsteriskToken */
+ || kind === 43 /* SlashToken */
+ || kind === 44 /* PercentToken */;
+ }
+ function isMultiplicativeOperatorOrHigher(kind) {
+ return isExponentiationOperator(kind)
+ || isMultiplicativeOperator(kind);
+ }
+ function isAdditiveOperator(kind) {
+ return kind === 39 /* PlusToken */
+ || kind === 40 /* MinusToken */;
+ }
+ function isAdditiveOperatorOrHigher(kind) {
+ return isAdditiveOperator(kind)
+ || isMultiplicativeOperatorOrHigher(kind);
+ }
+ function isShiftOperator(kind) {
+ return kind === 47 /* LessThanLessThanToken */
+ || kind === 48 /* GreaterThanGreaterThanToken */
+ || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */;
+ }
+ function isShiftOperatorOrHigher(kind) {
+ return isShiftOperator(kind)
+ || isAdditiveOperatorOrHigher(kind);
+ }
+ function isRelationalOperator(kind) {
+ return kind === 29 /* LessThanToken */
+ || kind === 32 /* LessThanEqualsToken */
+ || kind === 31 /* GreaterThanToken */
+ || kind === 33 /* GreaterThanEqualsToken */
+ || kind === 102 /* InstanceOfKeyword */
+ || kind === 101 /* InKeyword */;
+ }
+ function isRelationalOperatorOrHigher(kind) {
+ return isRelationalOperator(kind)
+ || isShiftOperatorOrHigher(kind);
+ }
+ function isEqualityOperator(kind) {
+ return kind === 34 /* EqualsEqualsToken */
+ || kind === 36 /* EqualsEqualsEqualsToken */
+ || kind === 35 /* ExclamationEqualsToken */
+ || kind === 37 /* ExclamationEqualsEqualsToken */;
+ }
+ function isEqualityOperatorOrHigher(kind) {
+ return isEqualityOperator(kind)
+ || isRelationalOperatorOrHigher(kind);
+ }
+ function isBitwiseOperator(kind) {
+ return kind === 50 /* AmpersandToken */
+ || kind === 51 /* BarToken */
+ || kind === 52 /* CaretToken */;
+ }
+ function isBitwiseOperatorOrHigher(kind) {
+ return isBitwiseOperator(kind)
+ || isEqualityOperatorOrHigher(kind);
+ }
+ // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator.
+ function isLogicalOperator(kind) {
+ return kind === 55 /* AmpersandAmpersandToken */
+ || kind === 56 /* BarBarToken */;
+ }
+ function isLogicalOperatorOrHigher(kind) {
+ return isLogicalOperator(kind)
+ || isBitwiseOperatorOrHigher(kind);
+ }
+ function isAssignmentOperatorOrHigher(kind) {
+ return kind === 60 /* QuestionQuestionToken */
+ || isLogicalOperatorOrHigher(kind)
+ || ts.isAssignmentOperator(kind);
+ }
+ function isBinaryOperator(kind) {
+ return isAssignmentOperatorOrHigher(kind)
+ || kind === 27 /* CommaToken */;
+ }
+ function isBinaryOperatorToken(node) {
+ return isBinaryOperator(node.kind);
+ }
+ ts.isBinaryOperatorToken = isBinaryOperatorToken;
+ var BinaryExpressionState;
+ (function (BinaryExpressionState) {
+ /**
+ * Handles walking into a `BinaryExpression`.
+ * @param machine State machine handler functions
+ * @param frame The current frame
+ * @returns The new frame
+ */
+ function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) {
+ var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined;
+ ts.Debug.assertEqual(stateStack[stackIndex], enter);
+ userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState);
+ stateStack[stackIndex] = nextState(machine, enter);
+ return stackIndex;
+ }
+ BinaryExpressionState.enter = enter;
+ /**
+ * Handles walking the `left` side of a `BinaryExpression`.
+ * @param machine State machine handler functions
+ * @param frame The current frame
+ * @returns The new frame
+ */
+ function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
+ ts.Debug.assertEqual(stateStack[stackIndex], left);
+ ts.Debug.assertIsDefined(machine.onLeft);
+ stateStack[stackIndex] = nextState(machine, left);
+ var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]);
+ if (nextNode) {
+ checkCircularity(stackIndex, nodeStack, nextNode);
+ return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode);
+ }
+ return stackIndex;
+ }
+ BinaryExpressionState.left = left;
+ /**
+ * Handles walking the `operatorToken` of a `BinaryExpression`.
+ * @param machine State machine handler functions
+ * @param frame The current frame
+ * @returns The new frame
+ */
+ function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
+ ts.Debug.assertEqual(stateStack[stackIndex], operator);
+ ts.Debug.assertIsDefined(machine.onOperator);
+ stateStack[stackIndex] = nextState(machine, operator);
+ machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]);
+ return stackIndex;
+ }
+ BinaryExpressionState.operator = operator;
+ /**
+ * Handles walking the `right` side of a `BinaryExpression`.
+ * @param machine State machine handler functions
+ * @param frame The current frame
+ * @returns The new frame
+ */
+ function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
+ ts.Debug.assertEqual(stateStack[stackIndex], right);
+ ts.Debug.assertIsDefined(machine.onRight);
+ stateStack[stackIndex] = nextState(machine, right);
+ var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]);
+ if (nextNode) {
+ checkCircularity(stackIndex, nodeStack, nextNode);
+ return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode);
+ }
+ return stackIndex;
+ }
+ BinaryExpressionState.right = right;
+ /**
+ * Handles walking out of a `BinaryExpression`.
+ * @param machine State machine handler functions
+ * @param frame The current frame
+ * @returns The new frame
+ */
+ function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) {
+ ts.Debug.assertEqual(stateStack[stackIndex], exit);
+ stateStack[stackIndex] = nextState(machine, exit);
+ var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]);
+ if (stackIndex > 0) {
+ stackIndex--;
+ if (machine.foldState) {
+ var side = stateStack[stackIndex] === exit ? "right" : "left";
+ userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side);
+ }
+ }
+ else {
+ resultHolder.value = result;
+ }
+ return stackIndex;
+ }
+ BinaryExpressionState.exit = exit;
+ /**
+ * Handles a frame that is already done.
+ * @returns The `done` state.
+ */
+ function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) {
+ ts.Debug.assertEqual(stateStack[stackIndex], done);
+ return stackIndex;
+ }
+ BinaryExpressionState.done = done;
+ function nextState(machine, currentState) {
+ switch (currentState) {
+ case enter:
+ if (machine.onLeft)
+ return left;
+ // falls through
+ case left:
+ if (machine.onOperator)
+ return operator;
+ // falls through
+ case operator:
+ if (machine.onRight)
+ return right;
+ // falls through
+ case right: return exit;
+ case exit: return done;
+ case done: return done;
+ default: ts.Debug.fail("Invalid state");
+ }
+ }
+ BinaryExpressionState.nextState = nextState;
+ function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) {
+ stackIndex++;
+ stateStack[stackIndex] = enter;
+ nodeStack[stackIndex] = node;
+ userStateStack[stackIndex] = undefined;
+ return stackIndex;
+ }
+ function checkCircularity(stackIndex, nodeStack, node) {
+ if (ts.Debug.shouldAssert(2 /* Aggressive */)) {
+ while (stackIndex >= 0) {
+ ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected.");
+ stackIndex--;
+ }
+ }
+ }
+ })(BinaryExpressionState || (BinaryExpressionState = {}));
+ /**
+ * Holds state machine handler functions
+ */
+ var BinaryExpressionStateMachine = /** @class */ (function () {
+ function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) {
+ this.onEnter = onEnter;
+ this.onLeft = onLeft;
+ this.onOperator = onOperator;
+ this.onRight = onRight;
+ this.onExit = onExit;
+ this.foldState = foldState;
+ }
+ return BinaryExpressionStateMachine;
+ }());
+ function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) {
+ var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState);
+ return trampoline;
+ function trampoline(node, outerState) {
+ var resultHolder = { value: undefined };
+ var stateStack = [BinaryExpressionState.enter];
+ var nodeStack = [node];
+ var userStateStack = [undefined];
+ var stackIndex = 0;
+ while (stateStack[stackIndex] !== BinaryExpressionState.done) {
+ stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState);
+ }
+ ts.Debug.assertEqual(stackIndex, 0);
+ return resultHolder.value;
+ }
+ }
+ ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ function setTextRange(range, location) {
+ return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range;
+ }
+ ts.setTextRange = setTextRange;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ var SignatureFlags;
+ (function (SignatureFlags) {
+ SignatureFlags[SignatureFlags["None"] = 0] = "None";
+ SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
+ SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
+ SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
+ SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
+ SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
+ })(SignatureFlags || (SignatureFlags = {}));
+ var SpeculationKind;
+ (function (SpeculationKind) {
+ SpeculationKind[SpeculationKind["TryParse"] = 0] = "TryParse";
+ SpeculationKind[SpeculationKind["Lookahead"] = 1] = "Lookahead";
+ SpeculationKind[SpeculationKind["Reparse"] = 2] = "Reparse";
+ })(SpeculationKind || (SpeculationKind = {}));
+ var NodeConstructor;
+ var TokenConstructor;
+ var IdentifierConstructor;
+ var PrivateIdentifierConstructor;
+ var SourceFileConstructor;
+ /**
+ * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/deprecatedCompat/deprecations.ts`.
+ */
/* @internal */
- ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
+ ts.parseBaseNodeFactory = {
+ createBaseSourceFileNode: function (kind) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, -1, -1); },
+ createBaseIdentifierNode: function (kind) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, -1, -1); },
+ createBasePrivateIdentifierNode: function (kind) { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1); },
+ createBaseTokenNode: function (kind) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, -1, -1); },
+ createBaseNode: function (kind) { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, -1, -1); },
+ };
/* @internal */
- ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
- return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
- });
+ ts.parseNodeFactory = ts.createNodeFactory(1 /* NoParenthesizerRules */, ts.parseBaseNodeFactory);
+ function visitNode(cbNode, node) {
+ return node && cbNode(node);
+ }
+ function visitNodes(cbNode, cbNodes, nodes) {
+ if (nodes) {
+ if (cbNodes) {
+ return cbNodes(nodes);
+ }
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
+ var result = cbNode(node);
+ if (result) {
+ return result;
+ }
+ }
+ }
+ }
+ /*@internal*/
+ function isJSDocLikeText(text, start) {
+ 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 <= 159 /* LastToken */) {
+ return;
+ }
+ switch (node.kind) {
+ case 160 /* QualifiedName */:
+ return visitNode(cbNode, node.left) ||
+ visitNode(cbNode, node.right);
+ case 162 /* TypeParameter */:
+ return visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNode(cbNode, node.default) ||
+ visitNode(cbNode, node.expression);
+ case 295 /* ShorthandPropertyAssignment */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.exclamationToken) ||
+ visitNode(cbNode, node.equalsToken) ||
+ visitNode(cbNode, node.objectAssignmentInitializer);
+ case 296 /* SpreadAssignment */:
+ return visitNode(cbNode, node.expression);
+ case 163 /* Parameter */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.dotDotDotToken) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.type) ||
+ visitNode(cbNode, node.initializer);
+ case 166 /* PropertyDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.exclamationToken) ||
+ visitNode(cbNode, node.type) ||
+ visitNode(cbNode, node.initializer);
+ case 165 /* 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 294 /* 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 253 /* 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 202 /* 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 178 /* FunctionType */:
+ case 179 /* ConstructorType */:
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 175 /* 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 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 212 /* FunctionExpression */:
+ case 255 /* FunctionDeclaration */:
+ case 213 /* ArrowFunction */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.asteriskToken) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.exclamationToken) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters) ||
+ visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type) ||
+ visitNode(cbNode, node.equalsGreaterThanToken) ||
+ visitNode(cbNode, node.body);
+ case 169 /* ClassStaticBlockDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.body);
+ case 177 /* TypeReference */:
+ return visitNode(cbNode, node.typeName) ||
+ visitNodes(cbNode, cbNodes, node.typeArguments);
+ case 176 /* TypePredicate */:
+ return visitNode(cbNode, node.assertsModifier) ||
+ visitNode(cbNode, node.parameterName) ||
+ visitNode(cbNode, node.type);
+ case 180 /* TypeQuery */:
+ return visitNode(cbNode, node.exprName);
+ case 181 /* TypeLiteral */:
+ return visitNodes(cbNode, cbNodes, node.members);
+ case 182 /* ArrayType */:
+ return visitNode(cbNode, node.elementType);
+ case 183 /* TupleType */:
+ return visitNodes(cbNode, cbNodes, node.elements);
+ case 186 /* UnionType */:
+ case 187 /* IntersectionType */:
+ return visitNodes(cbNode, cbNodes, node.types);
+ case 188 /* ConditionalType */:
+ return visitNode(cbNode, node.checkType) ||
+ visitNode(cbNode, node.extendsType) ||
+ visitNode(cbNode, node.trueType) ||
+ visitNode(cbNode, node.falseType);
+ case 189 /* InferType */:
+ return visitNode(cbNode, node.typeParameter);
+ case 199 /* ImportType */:
+ return visitNode(cbNode, node.argument) ||
+ visitNode(cbNode, node.qualifier) ||
+ visitNodes(cbNode, cbNodes, node.typeArguments);
+ case 190 /* ParenthesizedType */:
+ case 192 /* TypeOperator */:
+ return visitNode(cbNode, node.type);
+ case 193 /* IndexedAccessType */:
+ return visitNode(cbNode, node.objectType) ||
+ visitNode(cbNode, node.indexType);
+ case 194 /* MappedType */:
+ return visitNode(cbNode, node.readonlyToken) ||
+ visitNode(cbNode, node.typeParameter) ||
+ visitNode(cbNode, node.nameType) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.type) ||
+ visitNodes(cbNode, cbNodes, node.members);
+ case 195 /* LiteralType */:
+ return visitNode(cbNode, node.literal);
+ case 196 /* NamedTupleMember */:
+ return visitNode(cbNode, node.dotDotDotToken) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.type);
+ case 200 /* ObjectBindingPattern */:
+ case 201 /* ArrayBindingPattern */:
+ return visitNodes(cbNode, cbNodes, node.elements);
+ case 203 /* ArrayLiteralExpression */:
+ return visitNodes(cbNode, cbNodes, node.elements);
+ case 204 /* ObjectLiteralExpression */:
+ return visitNodes(cbNode, cbNodes, node.properties);
+ case 205 /* PropertyAccessExpression */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.questionDotToken) ||
+ visitNode(cbNode, node.name);
+ case 206 /* ElementAccessExpression */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.questionDotToken) ||
+ visitNode(cbNode, node.argumentExpression);
+ case 207 /* CallExpression */:
+ case 208 /* NewExpression */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.questionDotToken) ||
+ visitNodes(cbNode, cbNodes, node.typeArguments) ||
+ visitNodes(cbNode, cbNodes, node.arguments);
+ case 209 /* TaggedTemplateExpression */:
+ return visitNode(cbNode, node.tag) ||
+ visitNode(cbNode, node.questionDotToken) ||
+ visitNodes(cbNode, cbNodes, node.typeArguments) ||
+ visitNode(cbNode, node.template);
+ case 210 /* TypeAssertionExpression */:
+ return visitNode(cbNode, node.type) ||
+ visitNode(cbNode, node.expression);
+ case 211 /* ParenthesizedExpression */:
+ return visitNode(cbNode, node.expression);
+ case 214 /* DeleteExpression */:
+ return visitNode(cbNode, node.expression);
+ case 215 /* TypeOfExpression */:
+ return visitNode(cbNode, node.expression);
+ case 216 /* VoidExpression */:
+ return visitNode(cbNode, node.expression);
+ case 218 /* PrefixUnaryExpression */:
+ return visitNode(cbNode, node.operand);
+ case 223 /* YieldExpression */:
+ return visitNode(cbNode, node.asteriskToken) ||
+ visitNode(cbNode, node.expression);
+ case 217 /* AwaitExpression */:
+ return visitNode(cbNode, node.expression);
+ case 219 /* PostfixUnaryExpression */:
+ return visitNode(cbNode, node.operand);
+ case 220 /* BinaryExpression */:
+ return visitNode(cbNode, node.left) ||
+ visitNode(cbNode, node.operatorToken) ||
+ visitNode(cbNode, node.right);
+ case 228 /* AsExpression */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.type);
+ case 229 /* NonNullExpression */:
+ return visitNode(cbNode, node.expression);
+ case 230 /* MetaProperty */:
+ return visitNode(cbNode, node.name);
+ case 221 /* ConditionalExpression */:
+ return visitNode(cbNode, node.condition) ||
+ visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.whenTrue) ||
+ visitNode(cbNode, node.colonToken) ||
+ visitNode(cbNode, node.whenFalse);
+ case 224 /* SpreadElement */:
+ return visitNode(cbNode, node.expression);
+ case 234 /* Block */:
+ case 261 /* ModuleBlock */:
+ return visitNodes(cbNode, cbNodes, node.statements);
+ case 303 /* SourceFile */:
+ return visitNodes(cbNode, cbNodes, node.statements) ||
+ visitNode(cbNode, node.endOfFileToken);
+ case 236 /* VariableStatement */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.declarationList);
+ case 254 /* VariableDeclarationList */:
+ return visitNodes(cbNode, cbNodes, node.declarations);
+ case 237 /* ExpressionStatement */:
+ return visitNode(cbNode, node.expression);
+ case 238 /* IfStatement */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.thenStatement) ||
+ visitNode(cbNode, node.elseStatement);
+ case 239 /* DoStatement */:
+ return visitNode(cbNode, node.statement) ||
+ visitNode(cbNode, node.expression);
+ case 240 /* WhileStatement */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.statement);
+ case 241 /* ForStatement */:
+ return visitNode(cbNode, node.initializer) ||
+ visitNode(cbNode, node.condition) ||
+ visitNode(cbNode, node.incrementor) ||
+ visitNode(cbNode, node.statement);
+ case 242 /* ForInStatement */:
+ return visitNode(cbNode, node.initializer) ||
+ visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.statement);
+ case 243 /* ForOfStatement */:
+ return visitNode(cbNode, node.awaitModifier) ||
+ visitNode(cbNode, node.initializer) ||
+ visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.statement);
+ case 244 /* ContinueStatement */:
+ case 245 /* BreakStatement */:
+ return visitNode(cbNode, node.label);
+ case 246 /* ReturnStatement */:
+ return visitNode(cbNode, node.expression);
+ case 247 /* WithStatement */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.statement);
+ case 248 /* SwitchStatement */:
+ return visitNode(cbNode, node.expression) ||
+ visitNode(cbNode, node.caseBlock);
+ case 262 /* CaseBlock */:
+ return visitNodes(cbNode, cbNodes, node.clauses);
+ case 288 /* CaseClause */:
+ return visitNode(cbNode, node.expression) ||
+ visitNodes(cbNode, cbNodes, node.statements);
+ case 289 /* DefaultClause */:
+ return visitNodes(cbNode, cbNodes, node.statements);
+ case 249 /* LabeledStatement */:
+ return visitNode(cbNode, node.label) ||
+ visitNode(cbNode, node.statement);
+ case 250 /* ThrowStatement */:
+ return visitNode(cbNode, node.expression);
+ case 251 /* TryStatement */:
+ return visitNode(cbNode, node.tryBlock) ||
+ visitNode(cbNode, node.catchClause) ||
+ visitNode(cbNode, node.finallyBlock);
+ case 291 /* CatchClause */:
+ return visitNode(cbNode, node.variableDeclaration) ||
+ visitNode(cbNode, node.block);
+ case 164 /* Decorator */:
+ return visitNode(cbNode, node.expression);
+ case 256 /* ClassDeclaration */:
+ case 225 /* 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 257 /* 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 258 /* 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 259 /* EnumDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.name) ||
+ visitNodes(cbNode, cbNodes, node.members);
+ case 297 /* EnumMember */:
+ return visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.initializer);
+ case 260 /* ModuleDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.body);
+ case 264 /* ImportEqualsDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.moduleReference);
+ case 265 /* ImportDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.importClause) ||
+ visitNode(cbNode, node.moduleSpecifier) ||
+ visitNode(cbNode, node.assertClause);
+ case 266 /* ImportClause */:
+ return visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.namedBindings);
+ case 292 /* AssertClause */:
+ return visitNodes(cbNode, cbNodes, node.elements);
+ case 293 /* AssertEntry */:
+ return visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.value);
+ case 263 /* NamespaceExportDeclaration */:
+ return visitNode(cbNode, node.name);
+ case 267 /* NamespaceImport */:
+ return visitNode(cbNode, node.name);
+ case 273 /* NamespaceExport */:
+ return visitNode(cbNode, node.name);
+ case 268 /* NamedImports */:
+ case 272 /* NamedExports */:
+ return visitNodes(cbNode, cbNodes, node.elements);
+ case 271 /* ExportDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.exportClause) ||
+ visitNode(cbNode, node.moduleSpecifier) ||
+ visitNode(cbNode, node.assertClause);
+ case 269 /* ImportSpecifier */:
+ case 274 /* ExportSpecifier */:
+ return visitNode(cbNode, node.propertyName) ||
+ visitNode(cbNode, node.name);
+ case 270 /* ExportAssignment */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNode(cbNode, node.expression);
+ case 222 /* TemplateExpression */:
+ return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
+ case 232 /* TemplateSpan */:
+ return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
+ case 197 /* TemplateLiteralType */:
+ return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
+ case 198 /* TemplateLiteralTypeSpan */:
+ return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal);
+ case 161 /* ComputedPropertyName */:
+ return visitNode(cbNode, node.expression);
+ case 290 /* HeritageClause */:
+ return visitNodes(cbNode, cbNodes, node.types);
+ case 227 /* ExpressionWithTypeArguments */:
+ return visitNode(cbNode, node.expression) ||
+ visitNodes(cbNode, cbNodes, node.typeArguments);
+ case 276 /* ExternalModuleReference */:
+ return visitNode(cbNode, node.expression);
+ case 275 /* MissingDeclaration */:
+ return visitNodes(cbNode, cbNodes, node.decorators);
+ case 349 /* CommaListExpression */:
+ return visitNodes(cbNode, cbNodes, node.elements);
+ case 277 /* JsxElement */:
+ return visitNode(cbNode, node.openingElement) ||
+ visitNodes(cbNode, cbNodes, node.children) ||
+ visitNode(cbNode, node.closingElement);
+ case 281 /* JsxFragment */:
+ return visitNode(cbNode, node.openingFragment) ||
+ visitNodes(cbNode, cbNodes, node.children) ||
+ visitNode(cbNode, node.closingFragment);
+ case 278 /* JsxSelfClosingElement */:
+ case 279 /* JsxOpeningElement */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNodes(cbNode, cbNodes, node.typeArguments) ||
+ visitNode(cbNode, node.attributes);
+ case 285 /* JsxAttributes */:
+ return visitNodes(cbNode, cbNodes, node.properties);
+ case 284 /* JsxAttribute */:
+ return visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.initializer);
+ case 286 /* JsxSpreadAttribute */:
+ return visitNode(cbNode, node.expression);
+ case 287 /* JsxExpression */:
+ return visitNode(cbNode, node.dotDotDotToken) ||
+ visitNode(cbNode, node.expression);
+ case 280 /* JsxClosingElement */:
+ return visitNode(cbNode, node.tagName);
+ case 184 /* OptionalType */:
+ case 185 /* RestType */:
+ case 307 /* JSDocTypeExpression */:
+ case 313 /* JSDocNonNullableType */:
+ case 312 /* JSDocNullableType */:
+ case 314 /* JSDocOptionalType */:
+ case 316 /* JSDocVariadicType */:
+ return visitNode(cbNode, node.type);
+ case 315 /* JSDocFunctionType */:
+ return visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type);
+ case 318 /* JSDocComment */:
+ return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))
+ || visitNodes(cbNode, cbNodes, node.tags);
+ case 344 /* JSDocSeeTag */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.name) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 308 /* JSDocNameReference */:
+ return visitNode(cbNode, node.name);
+ case 309 /* JSDocMemberName */:
+ return visitNode(cbNode, node.left) ||
+ visitNode(cbNode, node.right);
+ case 338 /* JSDocParameterTag */:
+ case 345 /* JSDocPropertyTag */:
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)));
+ case 328 /* JSDocAuthorTag */:
+ return visitNode(cbNode, node.tagName) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 327 /* JSDocImplementsTag */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 326 /* JSDocAugmentsTag */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 342 /* JSDocTemplateTag */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 343 /* JSDocTypedefTag */:
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 307 /* JSDocTypeExpression */
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)));
+ case 336 /* JSDocCallbackTag */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 339 /* JSDocReturnTag */:
+ case 341 /* JSDocTypeTag */:
+ case 340 /* JSDocThisTag */:
+ case 337 /* JSDocEnumTag */:
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression) ||
+ (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 321 /* JSDocSignature */:
+ return ts.forEach(node.typeParameters, cbNode) ||
+ ts.forEach(node.parameters, cbNode) ||
+ visitNode(cbNode, node.type);
+ case 322 /* JSDocLink */:
+ case 323 /* JSDocLinkCode */:
+ case 324 /* JSDocLinkPlain */:
+ return visitNode(cbNode, node.name);
+ case 320 /* JSDocTypeLiteral */:
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 325 /* JSDocTag */:
+ case 330 /* JSDocClassTag */:
+ case 331 /* JSDocPublicTag */:
+ case 332 /* JSDocPrivateTag */:
+ case 333 /* JSDocProtectedTag */:
+ case 334 /* JSDocReadonlyTag */:
+ case 329 /* JSDocDeprecatedTag */:
+ return visitNode(cbNode, node.tagName)
+ || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
+ case 348 /* PartiallyEmittedExpression */:
+ return visitNode(cbNode, node.expression);
+ }
+ }
+ ts.forEachChild = forEachChild;
+ /** @internal */
+ /**
+ * 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; additionally,
+ * unlike `forEachChild`, 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 Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
+ * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
+ */
+ function forEachChildRecursively(rootNode, cbNode, cbNodes) {
+ var queue = gatherPossibleChildren(rootNode);
+ var parents = []; // tracks parent references for elements in queue
+ while (parents.length < queue.length) {
+ parents.push(rootNode);
+ }
+ while (queue.length !== 0) {
+ var current = queue.pop();
+ var parent = parents.pop();
+ if (ts.isArray(current)) {
+ if (cbNodes) {
+ var res = cbNodes(current, parent);
+ if (res) {
+ if (res === "skip")
+ continue;
+ return res;
+ }
+ }
+ for (var i = current.length - 1; i >= 0; --i) {
+ queue.push(current[i]);
+ parents.push(parent);
+ }
+ }
+ else {
+ var res = cbNode(current, parent);
+ if (res) {
+ if (res === "skip")
+ continue;
+ return res;
+ }
+ if (current.kind >= 160 /* FirstNode */) {
+ // add children in reverse order to the queue, so popping gives the first child
+ for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) {
+ var child = _a[_i];
+ queue.push(child);
+ parents.push(current);
+ }
+ }
+ }
+ }
+ }
+ ts.forEachChildRecursively = forEachChildRecursively;
+ function gatherPossibleChildren(node) {
+ var children = [];
+ forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
+ return children;
+ function addWorkItem(n) {
+ children.unshift(n);
+ }
+ }
+ function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
+ if (setParentNodes === void 0) { setParentNodes = false; }
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true);
+ ts.performance.mark("beforeParse");
+ var result;
+ ts.perfLogger.logStartParseSourceFile(fileName);
+ if (languageVersion === 100 /* JSON */) {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ }
+ ts.perfLogger.logStopParseSourceFile();
+ ts.performance.mark("afterParse");
+ ts.performance.measure("Parse", "beforeParse", "afterParse");
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
+ return result;
+ }
+ ts.createSourceFile = createSourceFile;
+ function parseIsolatedEntityName(text, languageVersion) {
+ 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);
+ // 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 & 3145728 /* PermanentlySetIncrementalFlags */);
+ return newSourceFile;
+ }
+ ts.updateSourceFile = updateSourceFile;
/* @internal */
- ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
- return ts.hasProperty(option, "transpileOptionValue");
- });
+ 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 */
- ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
- {
- name: "verbose",
- shortName: "v",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Enable_verbose_logging,
- type: "boolean"
- },
- {
- name: "dry",
- shortName: "d",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
- type: "boolean"
- },
- {
- name: "force",
- shortName: "f",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
- type: "boolean"
- },
- {
- name: "clean",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
- type: "boolean"
+ // 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) {
+ // 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(99 /* Latest */, /*skipTrivia*/ true);
+ var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
+ // capture constructors in 'initializeState' to avoid null checks
+ // tslint:disable variable-name
+ var NodeConstructor;
+ var TokenConstructor;
+ var IdentifierConstructor;
+ var PrivateIdentifierConstructor;
+ var SourceFileConstructor;
+ // tslint:enable variable-name
+ function countNode(node) {
+ nodeCount++;
+ return node;
+ }
+ // Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
+ // constructors above, which are reset each time `initializeState` is called.
+ var baseNodeFactory = {
+ createBaseSourceFileNode: function (kind) { return countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
+ createBaseIdentifierNode: function (kind) { return countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
+ createBasePrivateIdentifierNode: function (kind) { return countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
+ createBaseTokenNode: function (kind) { return countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
+ createBaseNode: function (kind) { return countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)); }
+ };
+ var factory = ts.createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
+ var fileName;
+ var sourceFlags;
+ var sourceText;
+ var languageVersion;
+ var scriptKind;
+ var languageVariant;
+ var parseDiagnostics;
+ var jsDocDiagnostics;
+ var syntaxCursor;
+ var currentToken;
+ var nodeCount;
+ var identifiers;
+ var privateIdentifiers;
+ var identifierCount;
+ var parsingContext;
+ var notParenthesizedArrow;
+ // 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;
+ // Indicates whether we are currently parsing top-level statements.
+ var topLevel = true;
+ // 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) {
+ var _a;
+ if (setParentNodes === void 0) { setParentNodes = false; }
+ scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6 /* JSON */) {
+ var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ result_3.referencedFiles = ts.emptyArray;
+ result_3.typeReferenceDirectives = ts.emptyArray;
+ result_3.libReferenceDirectives = ts.emptyArray;
+ result_3.amdDependencies = ts.emptyArray;
+ result_3.hasNoDefaultLib = false;
+ result_3.pragmas = ts.emptyMap;
+ return result_3;
+ }
+ initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
+ var result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
+ clearState();
+ return result;
+ }
+ Parser.parseSourceFile = parseSourceFile;
+ function parseIsolatedEntityName(content, languageVersion) {
+ // Choice of `isDeclarationFile` should be arbitrary
+ initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
+ // Prime the scanner.
+ nextToken();
+ 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 /* ES2015 */; }
+ if (setParentNodes === void 0) { setParentNodes = false; }
+ initializeState(fileName, sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
+ sourceFlags = contextFlags;
+ // Prime the scanner.
+ nextToken();
+ var pos = getNodePos();
+ var statements, endOfFileToken;
+ if (token() === 1 /* EndOfFileToken */) {
+ statements = createNodeArray([], pos, pos);
+ endOfFileToken = parseTokenNode();
+ }
+ else {
+ // Loop and synthesize an ArrayLiteralExpression if there are more than
+ // one top-level expressions to ensure all input text is consumed.
+ var expressions = void 0;
+ while (token() !== 1 /* EndOfFileToken */) {
+ var expression_1 = void 0;
+ switch (token()) {
+ case 22 /* OpenBracketToken */:
+ expression_1 = parseArrayLiteralExpression();
+ break;
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ case 104 /* NullKeyword */:
+ expression_1 = parseTokenNode();
+ break;
+ case 40 /* MinusToken */:
+ if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
+ expression_1 = parsePrefixUnaryExpression();
+ }
+ else {
+ expression_1 = parseObjectLiteralExpression();
+ }
+ break;
+ case 8 /* NumericLiteral */:
+ case 10 /* StringLiteral */:
+ if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
+ expression_1 = parseLiteralNode();
+ break;
+ }
+ // falls through
+ default:
+ expression_1 = parseObjectLiteralExpression();
+ break;
+ }
+ // Error recovery: collect multiple top-level expressions
+ if (expressions && ts.isArray(expressions)) {
+ expressions.push(expression_1);
+ }
+ else if (expressions) {
+ expressions = [expressions, expression_1];
+ }
+ else {
+ expressions = expression_1;
+ if (token() !== 1 /* EndOfFileToken */) {
+ parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token);
+ }
+ }
+ }
+ var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions);
+ var statement = factory.createExpressionStatement(expression);
+ finishNode(statement, pos);
+ statements = createNodeArray([statement], pos);
+ endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
+ }
+ // Set source file so that errors will be reported with this file name
+ var sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
+ }
+ sourceFile.nodeCount = nodeCount;
+ sourceFile.identifierCount = identifierCount;
+ sourceFile.identifiers = identifiers;
+ sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
+ if (jsDocDiagnostics) {
+ sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
+ }
+ var result = sourceFile;
+ clearState();
+ return result;
+ }
+ Parser.parseJsonText = parseJsonText;
+ function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) {
+ NodeConstructor = ts.objectAllocator.getNodeConstructor();
+ TokenConstructor = ts.objectAllocator.getTokenConstructor();
+ IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
+ PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
+ SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
+ fileName = ts.normalizePath(_fileName);
+ sourceText = _sourceText;
+ languageVersion = _languageVersion;
+ syntaxCursor = _syntaxCursor;
+ scriptKind = _scriptKind;
+ languageVariant = ts.getLanguageVariant(_scriptKind);
+ parseDiagnostics = [];
+ parsingContext = 0;
+ identifiers = new ts.Map();
+ privateIdentifiers = new ts.Map();
+ identifierCount = 0;
+ nodeCount = 0;
+ sourceFlags = 0;
+ topLevel = true;
+ switch (scriptKind) {
+ case 1 /* JS */:
+ case 2 /* JSX */:
+ contextFlags = 131072 /* JavaScriptFile */;
+ break;
+ case 6 /* JSON */:
+ contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
+ break;
+ default:
+ 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(languageVariant);
+ }
+ function clearState() {
+ // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
+ scanner.clearCommentDirectives();
+ scanner.setText("");
+ scanner.setOnError(undefined);
+ // Clear any data. We don't want to accidentally hold onto it for too long.
+ sourceText = undefined;
+ languageVersion = undefined;
+ syntaxCursor = undefined;
+ scriptKind = undefined;
+ languageVariant = undefined;
+ sourceFlags = 0;
+ parseDiagnostics = undefined;
+ jsDocDiagnostics = undefined;
+ parsingContext = 0;
+ identifiers = undefined;
+ notParenthesizedArrow = undefined;
+ topLevel = true;
+ }
+ function parseSourceFileWorker(languageVersion, setParentNodes, scriptKind) {
+ var isDeclarationFile = isDeclarationFileName(fileName);
+ if (isDeclarationFile) {
+ contextFlags |= 8388608 /* Ambient */;
+ }
+ sourceFlags = contextFlags;
+ // Prime the scanner.
+ nextToken();
+ var statements = parseList(0 /* SourceElements */, parseStatement);
+ ts.Debug.assert(token() === 1 /* EndOfFileToken */);
+ var endOfFileToken = addJSDocComment(parseTokenNode());
+ var sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags);
+ // 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.commentDirectives = scanner.getCommentDirectives();
+ sourceFile.nodeCount = nodeCount;
+ sourceFile.identifierCount = identifierCount;
+ sourceFile.identifiers = identifiers;
+ sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
+ if (jsDocDiagnostics) {
+ sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
+ }
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
+ }
+ return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, pos, end, diagnostic));
+ }
+ }
+ function withJSDoc(node, hasJSDoc) {
+ return hasJSDoc ? addJSDocComment(node) : node;
+ }
+ var hasDeprecatedTag = false;
+ function addJSDocComment(node) {
+ ts.Debug.assert(!node.jsDoc); // Should only be called once per node
+ var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceText), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
+ if (jsDoc.length)
+ node.jsDoc = jsDoc;
+ if (hasDeprecatedTag) {
+ hasDeprecatedTag = false;
+ node.flags |= 134217728 /* Deprecated */;
+ }
+ return node;
+ }
+ function reparseTopLevelAwait(sourceFile) {
+ var savedSyntaxCursor = syntaxCursor;
+ var baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
+ syntaxCursor = { currentNode: currentNode };
+ var statements = [];
+ var savedParseDiagnostics = parseDiagnostics;
+ parseDiagnostics = [];
+ var pos = 0;
+ var start = findNextStatementWithAwait(sourceFile.statements, 0);
+ var _loop_3 = function () {
+ // append all statements between pos and start
+ var prevStatement = sourceFile.statements[pos];
+ var nextStatement = sourceFile.statements[start];
+ ts.addRange(statements, sourceFile.statements, pos, start);
+ pos = findNextStatementWithoutAwait(sourceFile.statements, start);
+ // append all diagnostics associated with the copied range
+ var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement.pos; });
+ var diagnosticEnd = diagnosticStart >= 0 ? ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= nextStatement.pos; }, diagnosticStart) : -1;
+ if (diagnosticStart >= 0) {
+ ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined);
+ }
+ // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
+ speculationHelper(function () {
+ var savedContextFlags = contextFlags;
+ contextFlags |= 32768 /* AwaitContext */;
+ scanner.setTextPos(nextStatement.pos);
+ nextToken();
+ while (token() !== 1 /* EndOfFileToken */) {
+ var startPos = scanner.getStartPos();
+ var statement = parseListElement(0 /* SourceElements */, parseStatement);
+ statements.push(statement);
+ if (startPos === scanner.getStartPos()) {
+ nextToken();
+ }
+ if (pos >= 0) {
+ var nonAwaitStatement = sourceFile.statements[pos];
+ if (statement.end === nonAwaitStatement.pos) {
+ // done reparsing this section
+ break;
+ }
+ if (statement.end > nonAwaitStatement.pos) {
+ // we ate into the next statement, so we must reparse it.
+ pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
+ }
+ }
+ }
+ contextFlags = savedContextFlags;
+ }, 2 /* Reparse */);
+ // find the next statement containing an `await`
+ start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
+ };
+ while (start !== -1) {
+ _loop_3();
+ }
+ // append all statements between pos and the end of the list
+ if (pos >= 0) {
+ var prevStatement_1 = sourceFile.statements[pos];
+ ts.addRange(statements, sourceFile.statements, pos);
+ // append all diagnostics associated with the copied range
+ var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement_1.pos; });
+ if (diagnosticStart >= 0) {
+ ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
+ }
+ }
+ syntaxCursor = savedSyntaxCursor;
+ return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements));
+ function containsPossibleTopLevelAwait(node) {
+ return !(node.flags & 32768 /* AwaitContext */)
+ && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */);
+ }
+ function findNextStatementWithAwait(statements, start) {
+ for (var i = start; i < statements.length; i++) {
+ if (containsPossibleTopLevelAwait(statements[i])) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ function findNextStatementWithoutAwait(statements, start) {
+ for (var i = start; i < statements.length; i++) {
+ if (!containsPossibleTopLevelAwait(statements[i])) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ function currentNode(position) {
+ var node = baseSyntaxCursor.currentNode(position);
+ if (topLevel && node && containsPossibleTopLevelAwait(node)) {
+ node.intersectsChange = true;
+ }
+ 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.
+ ts.setParentRecursive(rootNode, /*incremental*/ true);
+ }
+ Parser.fixupParentReferences = fixupParentReferences;
+ function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, flags) {
+ // 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 = factory.createSourceFile(statements, endOfFileToken, flags);
+ ts.setTextRangePosWidth(sourceFile, 0, sourceText.length);
+ setExternalModuleIndicator(sourceFile);
+ // If we parsed this as an external module, it may contain top-level await
+ if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) {
+ sourceFile = reparseTopLevelAwait(sourceFile);
+ }
+ sourceFile.text = sourceText;
+ sourceFile.bindDiagnostics = [];
+ sourceFile.bindSuggestionDiagnostics = undefined;
+ sourceFile.languageVersion = languageVersion;
+ sourceFile.fileName = fileName;
+ sourceFile.languageVariant = ts.getLanguageVariant(scriptKind);
+ sourceFile.isDeclarationFile = isDeclarationFile;
+ sourceFile.scriptKind = scriptKind;
+ return sourceFile;
+ }
+ function setContextFlag(val, flag) {
+ if (val) {
+ contextFlags |= flag;
+ }
+ else {
+ contextFlags &= ~flag;
+ }
+ }
+ function setDisallowInContext(val) {
+ setContextFlag(val, 4096 /* DisallowInContext */);
+ }
+ function setYieldContext(val) {
+ setContextFlag(val, 8192 /* YieldContext */);
+ }
+ function setDecoratorContext(val) {
+ setContextFlag(val, 16384 /* DecoratorContext */);
+ }
+ function setAwaitContext(val) {
+ setContextFlag(val, 32768 /* 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) {
+ // clear the requested context flags
+ setContextFlag(/*val*/ false, contextFlagsToClear);
+ var result = func();
+ // 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) {
+ // set the requested context flags
+ setContextFlag(/*val*/ true, contextFlagsToSet);
+ var result = func();
+ // 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(4096 /* DisallowInContext */, func);
+ }
+ function disallowInAnd(func) {
+ return doInsideOfContext(4096 /* DisallowInContext */, func);
+ }
+ function doInYieldContext(func) {
+ return doInsideOfContext(8192 /* YieldContext */, func);
+ }
+ function doInDecoratorContext(func) {
+ return doInsideOfContext(16384 /* DecoratorContext */, func);
+ }
+ function doInAwaitContext(func) {
+ return doInsideOfContext(32768 /* AwaitContext */, func);
+ }
+ function doOutsideOfAwaitContext(func) {
+ return doOutsideOfContext(32768 /* AwaitContext */, func);
+ }
+ function doInYieldAndAwaitContext(func) {
+ return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
+ }
+ function doOutsideOfYieldAndAwaitContext(func) {
+ return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
+ }
+ function inContext(flags) {
+ return (contextFlags & flags) !== 0;
+ }
+ function inYieldContext() {
+ return inContext(8192 /* YieldContext */);
+ }
+ function inDisallowInContext() {
+ return inContext(4096 /* DisallowInContext */);
+ }
+ function inDecoratorContext() {
+ return inContext(16384 /* DecoratorContext */);
+ }
+ function inAwaitContext() {
+ return inContext(32768 /* 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.createDetachedDiagnostic(fileName, 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) {
+ parseErrorAtPosition(start, end - start, message, arg0);
+ }
+ function parseErrorAtRange(range, message, arg0) {
+ parseErrorAt(range.pos, range.end, message, arg0);
+ }
+ function scanError(message, length) {
+ parseErrorAtPosition(scanner.getTextPos(), length, message);
+ }
+ function getNodePos() {
+ return scanner.getStartPos();
+ }
+ function hasPrecedingJSDocComment() {
+ return scanner.hasPrecedingJSDocComment();
+ }
+ // 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;
+ }
+ function nextTokenWithoutCheck() {
+ return currentToken = scanner.scan();
+ }
+ function nextTokenAnd(func) {
+ nextToken();
+ return func();
+ }
+ function nextToken() {
+ // if the keyword had an escape
+ if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
+ // issue a parse error for the escape
+ parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
+ }
+ return nextTokenWithoutCheck();
+ }
+ function nextTokenJSDoc() {
+ return currentToken = scanner.scanJsDocToken();
+ }
+ function reScanGreaterToken() {
+ return currentToken = scanner.reScanGreaterToken();
+ }
+ function reScanSlashToken() {
+ return currentToken = scanner.reScanSlashToken();
+ }
+ function reScanTemplateToken(isTaggedTemplate) {
+ return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
+ }
+ function reScanTemplateHeadOrNoSubstitutionTemplate() {
+ return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
+ }
+ function reScanLessThanToken() {
+ return currentToken = scanner.reScanLessThanToken();
+ }
+ function reScanHashToken() {
+ return currentToken = scanner.reScanHashToken();
+ }
+ function scanJsxIdentifier() {
+ return currentToken = scanner.scanJsxIdentifier();
+ }
+ function scanJsxText() {
+ return currentToken = scanner.scanJsxToken();
+ }
+ function scanJsxAttributeValue() {
+ return currentToken = scanner.scanJsxAttributeValue();
+ }
+ function speculationHelper(callback, speculationKind) {
+ // 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 = speculationKind !== 0 /* TryParse */
+ ? 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 || speculationKind !== 0 /* TryParse */) {
+ currentToken = saveToken;
+ if (speculationKind !== 2 /* Reparse */) {
+ parseDiagnostics.length = saveParseDiagnosticsLength;
+ }
+ parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
+ }
+ 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, 1 /* Lookahead */);
+ }
+ /** 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, 0 /* TryParse */);
+ }
+ function isBindingIdentifier() {
+ if (token() === 79 /* Identifier */) {
+ return true;
+ }
+ // `let await`/`let yield` in [Yield] or [Await] are allowed here and disallowed in the binder.
+ return token() > 116 /* LastReservedWord */;
+ }
+ // Ignore strict mode flag because we will report an error in type checker instead.
+ function isIdentifier() {
+ if (token() === 79 /* Identifier */) {
+ return true;
+ }
+ // 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() === 125 /* YieldKeyword */ && inYieldContext()) {
+ return false;
+ }
+ // 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() === 132 /* AwaitKeyword */ && inAwaitContext()) {
+ return false;
+ }
+ return token() > 116 /* LastReservedWord */;
+ }
+ function parseExpected(kind, diagnosticMessage, shouldAdvance) {
+ if (shouldAdvance === void 0) { shouldAdvance = true; }
+ if (token() === kind) {
+ if (shouldAdvance) {
+ nextToken();
+ }
+ return true;
+ }
+ // Report specific message if provided with one. Otherwise, report generic fallback message.
+ if (diagnosticMessage) {
+ parseErrorAtCurrentToken(diagnosticMessage);
+ }
+ else {
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
+ }
+ return false;
+ }
+ var viableKeywordSuggestions = Object.keys(ts.textToKeywordObj).filter(function (keyword) { return keyword.length > 2; });
+ /**
+ * Provides a better error message than the generic "';' expected" if possible for
+ * known common variants of a missing semicolon, such as from a mispelled names.
+ *
+ * @param node Node preceding the expected semicolon location.
+ */
+ function parseErrorForMissingSemicolonAfter(node) {
+ var _a;
+ // Tagged template literals are sometimes used in places where only simple strings are allowed, i.e.:
+ // module `M1` {
+ // ^^^^^^^^^^^ This block is parsed as a template literal like module`M1`.
+ if (ts.isTaggedTemplateExpression(node)) {
+ parseErrorAt(ts.skipTrivia(sourceText, node.template.pos), node.template.end, ts.Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings);
+ return;
+ }
+ // Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message.
+ var expressionText = ts.isIdentifier(node) ? ts.idText(node) : undefined;
+ if (!expressionText || !ts.isIdentifierText(expressionText, languageVersion)) {
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(26 /* SemicolonToken */));
+ return;
+ }
+ var pos = ts.skipTrivia(sourceText, node.pos);
+ // Some known keywords are likely signs of syntax being used improperly.
+ switch (expressionText) {
+ case "const":
+ case "let":
+ case "var":
+ parseErrorAt(pos, node.end, ts.Diagnostics.Variable_declaration_not_allowed_at_this_location);
+ return;
+ case "declare":
+ // If a declared node failed to parse, it would have emitted a diagnostic already.
+ return;
+ case "interface":
+ parseErrorForInvalidName(ts.Diagnostics.Interface_name_cannot_be_0, ts.Diagnostics.Interface_must_be_given_a_name, 18 /* OpenBraceToken */);
+ return;
+ case "is":
+ parseErrorAt(pos, scanner.getTextPos(), ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
+ return;
+ case "module":
+ case "namespace":
+ parseErrorForInvalidName(ts.Diagnostics.Namespace_name_cannot_be_0, ts.Diagnostics.Namespace_must_be_given_a_name, 18 /* OpenBraceToken */);
+ return;
+ case "type":
+ parseErrorForInvalidName(ts.Diagnostics.Type_alias_name_cannot_be_0, ts.Diagnostics.Type_alias_must_be_given_a_name, 63 /* EqualsToken */);
+ return;
+ }
+ // The user alternatively might have misspelled or forgotten to add a space after a common keyword.
+ var suggestion = (_a = ts.getSpellingSuggestion(expressionText, viableKeywordSuggestions, function (n) { return n; })) !== null && _a !== void 0 ? _a : getSpaceSuggestion(expressionText);
+ if (suggestion) {
+ parseErrorAt(pos, node.end, ts.Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion);
+ return;
+ }
+ // Unknown tokens are handled with their own errors in the scanner
+ if (token() === 0 /* Unknown */) {
+ return;
+ }
+ // Otherwise, we know this some kind of unknown word, not just a missing expected semicolon.
+ parseErrorAt(pos, node.end, ts.Diagnostics.Unexpected_keyword_or_identifier);
+ }
+ /**
+ * Reports a diagnostic error for the current token being an invalid name.
+ *
+ * @param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
+ * @param nameDiagnostic Diagnostic to report for all other cases.
+ * @param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
+ */
+ function parseErrorForInvalidName(nameDiagnostic, blankDiagnostic, tokenIfBlankName) {
+ if (token() === tokenIfBlankName) {
+ parseErrorAtCurrentToken(blankDiagnostic);
+ }
+ else {
+ parseErrorAtCurrentToken(nameDiagnostic, scanner.getTokenValue());
+ }
+ }
+ function getSpaceSuggestion(expressionText) {
+ for (var _i = 0, viableKeywordSuggestions_1 = viableKeywordSuggestions; _i < viableKeywordSuggestions_1.length; _i++) {
+ var keyword = viableKeywordSuggestions_1[_i];
+ if (expressionText.length > keyword.length + 2 && ts.startsWith(expressionText, keyword)) {
+ return "".concat(keyword, " ").concat(expressionText.slice(keyword.length));
+ }
+ }
+ return undefined;
+ }
+ function parseSemicolonAfterPropertyName(name, type, initializer) {
+ if (token() === 59 /* AtToken */ && !scanner.hasPrecedingLineBreak()) {
+ parseErrorAtCurrentToken(ts.Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations);
+ return;
+ }
+ if (token() === 20 /* OpenParenToken */) {
+ parseErrorAtCurrentToken(ts.Diagnostics.Cannot_start_a_function_call_in_a_type_annotation);
+ nextToken();
+ return;
+ }
+ if (type && !canParseSemicolon()) {
+ if (initializer) {
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(26 /* SemicolonToken */));
+ }
+ else {
+ parseErrorAtCurrentToken(ts.Diagnostics.Expected_for_property_initializer);
+ }
+ return;
+ }
+ if (tryParseSemicolon()) {
+ return;
+ }
+ // If an initializer was parsed but there is still an error in finding the next semicolon,
+ // we generally know there was an error already reported in the initializer...
+ // class Example { a = new Map([), ) }
+ // ~
+ if (initializer) {
+ // ...unless we've found the start of a block after a property declaration, in which
+ // case we can know that regardless of the initializer we should complain on the block.
+ // class Example { a = 0 {} }
+ // ~
+ if (token() === 18 /* OpenBraceToken */) {
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(26 /* SemicolonToken */));
+ }
+ return;
+ }
+ parseErrorForMissingSemicolonAfter(name);
+ }
+ function parseExpectedJSDoc(kind) {
+ if (token() === kind) {
+ nextTokenJSDoc();
+ return true;
+ }
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
+ return false;
+ }
+ function parseOptional(t) {
+ if (token() === t) {
+ nextToken();
+ return true;
+ }
+ return false;
+ }
+ function parseOptionalToken(t) {
+ if (token() === t) {
+ return parseTokenNode();
+ }
+ return undefined;
+ }
+ function parseOptionalTokenJSDoc(t) {
+ if (token() === t) {
+ return parseTokenNodeJSDoc();
+ }
+ return undefined;
+ }
+ function parseExpectedToken(t, diagnosticMessage, arg0) {
+ return parseOptionalToken(t) ||
+ createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
+ }
+ function parseExpectedTokenJSDoc(t) {
+ return parseOptionalTokenJSDoc(t) ||
+ createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
+ }
+ function parseTokenNode() {
+ var pos = getNodePos();
+ var kind = token();
+ nextToken();
+ return finishNode(factory.createToken(kind), pos);
+ }
+ function parseTokenNodeJSDoc() {
+ var pos = getNodePos();
+ var kind = token();
+ nextTokenJSDoc();
+ return finishNode(factory.createToken(kind), pos);
+ }
+ function canParseSemicolon() {
+ // If there's a real semicolon, then we can always parse it out.
+ if (token() === 26 /* SemicolonToken */) {
+ return true;
+ }
+ // We can parse out an optional semicolon in ASI cases in the following cases.
+ return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
+ }
+ function tryParseSemicolon() {
+ if (!canParseSemicolon()) {
+ return false;
+ }
+ if (token() === 26 /* SemicolonToken */) {
+ // consume the semicolon if it was explicitly provided.
+ nextToken();
+ }
+ return true;
+ }
+ function parseSemicolon() {
+ return tryParseSemicolon() || parseExpected(26 /* SemicolonToken */);
+ }
+ function createNodeArray(elements, pos, end, hasTrailingComma) {
+ var array = factory.createNodeArray(elements, hasTrailingComma);
+ ts.setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
+ return array;
+ }
+ function finishNode(node, pos, end) {
+ ts.setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
+ 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 |= 65536 /* ThisNodeHasError */;
+ }
+ return node;
+ }
+ function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
+ if (reportAtCurrentPosition) {
+ parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
+ }
+ else if (diagnosticMessage) {
+ parseErrorAtCurrentToken(diagnosticMessage, arg0);
+ }
+ var pos = getNodePos();
+ var result = kind === 79 /* Identifier */ ? factory.createIdentifier("", /*typeArguments*/ undefined, /*originalKeywordKind*/ undefined) :
+ ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
+ kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
+ kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
+ kind === 275 /* MissingDeclaration */ ? factory.createMissingDeclaration() :
+ factory.createToken(kind);
+ return finishNode(result, pos);
+ }
+ function internIdentifier(text) {
+ var identifier = identifiers.get(text);
+ if (identifier === undefined) {
+ identifiers.set(text, identifier = text);
+ }
+ 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, privateIdentifierDiagnosticMessage) {
+ if (isIdentifier) {
+ identifierCount++;
+ var pos = getNodePos();
+ // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
+ var originalKeywordKind = token();
+ var text = internIdentifier(scanner.getTokenValue());
+ nextTokenWithoutCheck();
+ return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos);
+ }
+ if (token() === 80 /* PrivateIdentifier */) {
+ parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
+ return createIdentifier(/*isIdentifier*/ true);
+ }
+ if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 79 /* Identifier */; })) {
+ // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser.
+ return createIdentifier(/*isIdentifier*/ true);
+ }
+ identifierCount++;
+ // Only for end of file because the error gets reported incorrectly on embedded script tags.
+ var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
+ var isReservedWord = scanner.isReservedWord();
+ var msgArg = scanner.getTokenText();
+ var defaultMessage = isReservedWord ?
+ ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
+ ts.Diagnostics.Identifier_expected;
+ return createMissingNode(79 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
+ }
+ function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
+ return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
+ }
+ function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
+ return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
+ }
+ function parseIdentifierName(diagnosticMessage) {
+ return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
+ }
+ function isLiteralPropertyName() {
+ return ts.tokenIsIdentifierOrKeyword(token()) ||
+ token() === 10 /* StringLiteral */ ||
+ token() === 8 /* NumericLiteral */;
+ }
+ function isAssertionKey() {
+ return ts.tokenIsIdentifierOrKeyword(token()) ||
+ token() === 10 /* StringLiteral */;
+ }
+ function parsePropertyNameWorker(allowComputedPropertyNames) {
+ if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
+ var node = parseLiteralNode();
+ node.text = internIdentifier(node.text);
+ return node;
+ }
+ if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
+ return parseComputedPropertyName();
+ }
+ if (token() === 80 /* PrivateIdentifier */) {
+ return parsePrivateIdentifier();
+ }
+ return parseIdentifierName();
+ }
+ function parsePropertyName() {
+ return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
+ }
+ function parseComputedPropertyName() {
+ // PropertyName [Yield]:
+ // LiteralPropertyName
+ // ComputedPropertyName[?Yield]
+ var pos = getNodePos();
+ parseExpected(22 /* 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.
+ var expression = allowInAnd(parseExpression);
+ parseExpected(23 /* CloseBracketToken */);
+ return finishNode(factory.createComputedPropertyName(expression), pos);
+ }
+ function internPrivateIdentifier(text) {
+ var privateIdentifier = privateIdentifiers.get(text);
+ if (privateIdentifier === undefined) {
+ privateIdentifiers.set(text, privateIdentifier = text);
+ }
+ return privateIdentifier;
+ }
+ function parsePrivateIdentifier() {
+ var pos = getNodePos();
+ var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText()));
+ nextToken();
+ return finishNode(node, pos);
+ }
+ function parseContextualModifier(t) {
+ return token() === t && tryParse(nextTokenCanFollowModifier);
+ }
+ function nextTokenIsOnSameLineAndCanFollowModifier() {
+ nextToken();
+ if (scanner.hasPrecedingLineBreak()) {
+ return false;
+ }
+ return canFollowModifier();
+ }
+ function nextTokenCanFollowModifier() {
+ switch (token()) {
+ case 85 /* ConstKeyword */:
+ // 'const' is only a modifier if followed by 'enum'.
+ return nextToken() === 92 /* EnumKeyword */;
+ case 93 /* ExportKeyword */:
+ nextToken();
+ if (token() === 88 /* DefaultKeyword */) {
+ return lookAhead(nextTokenCanFollowDefaultKeyword);
+ }
+ if (token() === 151 /* TypeKeyword */) {
+ return lookAhead(nextTokenCanFollowExportModifier);
+ }
+ return canFollowExportModifier();
+ case 88 /* DefaultKeyword */:
+ return nextTokenCanFollowDefaultKeyword();
+ case 124 /* StaticKeyword */:
+ case 136 /* GetKeyword */:
+ case 148 /* SetKeyword */:
+ nextToken();
+ return canFollowModifier();
+ default:
+ return nextTokenIsOnSameLineAndCanFollowModifier();
+ }
+ }
+ function canFollowExportModifier() {
+ return token() !== 41 /* AsteriskToken */
+ && token() !== 127 /* AsKeyword */
+ && token() !== 18 /* OpenBraceToken */
+ && canFollowModifier();
+ }
+ function nextTokenCanFollowExportModifier() {
+ nextToken();
+ return canFollowExportModifier();
+ }
+ function parseAnyContextualModifier() {
+ return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
+ }
+ function canFollowModifier() {
+ return token() === 22 /* OpenBracketToken */
+ || token() === 18 /* OpenBraceToken */
+ || token() === 41 /* AsteriskToken */
+ || token() === 25 /* DotDotDotToken */
+ || isLiteralPropertyName();
+ }
+ function nextTokenCanFollowDefaultKeyword() {
+ nextToken();
+ return token() === 84 /* ClassKeyword */ || token() === 98 /* FunctionKeyword */ ||
+ token() === 118 /* InterfaceKeyword */ ||
+ (token() === 126 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
+ (token() === 131 /* 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 /* 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() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
+ case 2 /* SwitchClauses */:
+ return token() === 82 /* CaseKeyword */ || token() === 88 /* DefaultKeyword */;
+ case 4 /* TypeMembers */:
+ return lookAhead(isTypeMemberStart);
+ 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() === 26 /* 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() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
+ case 12 /* ObjectLiteralMembers */:
+ switch (token()) {
+ case 22 /* OpenBracketToken */:
+ case 41 /* AsteriskToken */:
+ case 25 /* DotDotDotToken */:
+ case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
+ return true;
+ default:
+ return isLiteralPropertyName();
+ }
+ case 18 /* RestProperties */:
+ return isLiteralPropertyName();
+ case 9 /* ObjectBindingElements */:
+ return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
+ case 24 /* AssertEntries */:
+ return isAssertionKey();
+ 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() === 18 /* 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 /* VariableDeclarations */:
+ return isBindingIdentifierOrPrivateIdentifierOrPattern();
+ case 10 /* ArrayBindingElements */:
+ return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
+ case 19 /* TypeParameters */:
+ return isIdentifier();
+ case 15 /* ArrayLiteralMembers */:
+ switch (token()) {
+ case 27 /* CommaToken */:
+ case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
+ return true;
+ }
+ // falls through
+ case 11 /* ArgumentExpressions */:
+ return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
+ case 16 /* Parameters */:
+ return isStartOfParameter(/*isJSDocParameter*/ false);
+ case 17 /* JSDocParameters */:
+ return isStartOfParameter(/*isJSDocParameter*/ true);
+ case 20 /* TypeArguments */:
+ case 21 /* TupleElementTypes */:
+ return token() === 27 /* CommaToken */ || isStartOfType();
+ case 22 /* HeritageClauses */:
+ return isHeritageClause();
+ case 23 /* ImportOrExportSpecifiers */:
+ return ts.tokenIsIdentifierOrKeyword(token());
+ case 13 /* JsxAttributes */:
+ return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
+ case 14 /* JsxChildren */:
+ return true;
+ }
+ return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
+ }
+ function isValidHeritageClauseObjectLiteral() {
+ ts.Debug.assert(token() === 18 /* OpenBraceToken */);
+ if (nextToken() === 19 /* 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 === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 94 /* ExtendsKeyword */ || next === 117 /* ImplementsKeyword */;
+ }
+ return true;
+ }
+ function nextTokenIsIdentifier() {
+ nextToken();
+ return isIdentifier();
+ }
+ function nextTokenIsIdentifierOrKeyword() {
+ nextToken();
+ return ts.tokenIsIdentifierOrKeyword(token());
+ }
+ function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
+ nextToken();
+ return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
+ }
+ function isHeritageClauseExtendsOrImplementsKeyword() {
+ if (token() === 117 /* ImplementsKeyword */ ||
+ token() === 94 /* ExtendsKeyword */) {
+ return lookAhead(nextTokenIsStartOfExpression);
+ }
+ return false;
+ }
+ function nextTokenIsStartOfExpression() {
+ nextToken();
+ return isStartOfExpression();
+ }
+ function nextTokenIsStartOfType() {
+ nextToken();
+ return isStartOfType();
+ }
+ // True if positioned at a list terminator
+ function isListTerminator(kind) {
+ if (token() === 1 /* EndOfFileToken */) {
+ // Being at the end of the file ends all lists.
+ return true;
+ }
+ switch (kind) {
+ case 1 /* BlockStatements */:
+ case 2 /* SwitchClauses */:
+ case 4 /* TypeMembers */:
+ case 5 /* ClassMembers */:
+ case 6 /* EnumMembers */:
+ case 12 /* ObjectLiteralMembers */:
+ case 9 /* ObjectBindingElements */:
+ case 23 /* ImportOrExportSpecifiers */:
+ case 24 /* AssertEntries */:
+ return token() === 19 /* CloseBraceToken */;
+ case 3 /* SwitchClauseStatements */:
+ return token() === 19 /* CloseBraceToken */ || token() === 82 /* CaseKeyword */ || token() === 88 /* DefaultKeyword */;
+ case 7 /* HeritageClauseElement */:
+ return token() === 18 /* OpenBraceToken */ || token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */;
+ case 8 /* VariableDeclarations */:
+ return isVariableDeclaratorListTerminator();
+ case 19 /* TypeParameters */:
+ // Tokens other than '>' are here for better error recovery
+ return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */;
+ case 11 /* ArgumentExpressions */:
+ // Tokens other than ')' are here for better error recovery
+ return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
+ case 15 /* ArrayLiteralMembers */:
+ case 21 /* TupleElementTypes */:
+ case 10 /* ArrayBindingElements */:
+ return token() === 23 /* CloseBracketToken */;
+ case 17 /* JSDocParameters */:
+ case 16 /* Parameters */:
+ case 18 /* RestProperties */:
+ // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
+ return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
+ case 20 /* TypeArguments */:
+ // All other tokens should cause the type-argument to terminate except comma token
+ return token() !== 27 /* CommaToken */;
+ case 22 /* HeritageClauses */:
+ return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
+ case 13 /* JsxAttributes */:
+ return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
+ case 14 /* JsxChildren */:
+ return token() === 29 /* 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;
+ }
+ // 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() === 38 /* 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 < 25 /* Count */; kind++) {
+ if (parsingContext & (1 << 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, /*inErrorRecovery*/ false)) {
+ list.push(parseListElement(kind, parseElement));
+ continue;
+ }
+ if (abortParsingListOrMoveToNextToken(kind)) {
+ break;
+ }
+ }
+ parsingContext = saveParsingContext;
+ return createNodeArray(list, listPos);
+ }
+ function parseListElement(parsingContext, parseElement) {
+ var node = currentNode(parsingContext);
+ if (node) {
+ return consumeNode(node);
+ }
+ return parseElement();
+ }
+ function currentNode(parsingContext) {
+ // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
+ //
+ // 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 (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
+ return undefined;
+ }
+ var node = syntaxCursor.currentNode(scanner.getStartPos());
+ // Can't reuse a missing node.
+ // Can't reuse a node that intersected the change range.
+ // 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.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
+ return undefined;
+ }
+ // 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 & 25358336 /* 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 isReusableParsingContext(parsingContext) {
+ switch (parsingContext) {
+ case 5 /* ClassMembers */:
+ case 2 /* SwitchClauses */:
+ case 0 /* SourceElements */:
+ case 1 /* BlockStatements */:
+ case 3 /* SwitchClauseStatements */:
+ case 6 /* EnumMembers */:
+ case 4 /* TypeMembers */:
+ case 8 /* VariableDeclarations */:
+ case 17 /* JSDocParameters */:
+ case 16 /* Parameters */:
+ return true;
+ }
+ return false;
+ }
+ function canReuseNode(node, parsingContext) {
+ switch (parsingContext) {
+ case 5 /* ClassMembers */:
+ return isReusableClassMember(node);
+ case 2 /* SwitchClauses */:
+ return isReusableSwitchClause(node);
+ case 0 /* SourceElements */:
+ case 1 /* BlockStatements */:
+ case 3 /* SwitchClauseStatements */:
+ return isReusableStatement(node);
+ case 6 /* EnumMembers */:
+ return isReusableEnumMember(node);
+ case 4 /* TypeMembers */:
+ return isReusableTypeMember(node);
+ case 8 /* VariableDeclarations */:
+ return isReusableVariableDeclaration(node);
+ case 17 /* JSDocParameters */:
+ case 16 /* Parameters */:
+ return isReusableParameter(node);
+ // 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 ParsingContext.HeritageClauses:
+ // This would probably be safe to reuse. There is no speculative parsing with
+ // heritage clauses.
+ // case ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.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 ParsingContext.JsxAttributes:
+ // case ParsingContext.JsxChildren:
+ }
+ return false;
+ }
+ function isReusableClassMember(node) {
+ if (node) {
+ switch (node.kind) {
+ case 170 /* Constructor */:
+ case 175 /* IndexSignature */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 166 /* PropertyDeclaration */:
+ case 233 /* SemicolonClassElement */:
+ return true;
+ case 168 /* 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 === 79 /* Identifier */ &&
+ methodDeclaration.name.originalKeywordKind === 134 /* ConstructorKeyword */;
+ return !nameIsConstructor;
+ }
+ }
+ return false;
+ }
+ function isReusableSwitchClause(node) {
+ if (node) {
+ switch (node.kind) {
+ case 288 /* CaseClause */:
+ case 289 /* DefaultClause */:
+ return true;
+ }
+ }
+ return false;
+ }
+ function isReusableStatement(node) {
+ if (node) {
+ switch (node.kind) {
+ case 255 /* FunctionDeclaration */:
+ case 236 /* VariableStatement */:
+ case 234 /* Block */:
+ case 238 /* IfStatement */:
+ case 237 /* ExpressionStatement */:
+ case 250 /* ThrowStatement */:
+ case 246 /* ReturnStatement */:
+ case 248 /* SwitchStatement */:
+ case 245 /* BreakStatement */:
+ case 244 /* ContinueStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ case 241 /* ForStatement */:
+ case 240 /* WhileStatement */:
+ case 247 /* WithStatement */:
+ case 235 /* EmptyStatement */:
+ case 251 /* TryStatement */:
+ case 249 /* LabeledStatement */:
+ case 239 /* DoStatement */:
+ case 252 /* DebuggerStatement */:
+ case 265 /* ImportDeclaration */:
+ case 264 /* ImportEqualsDeclaration */:
+ case 271 /* ExportDeclaration */:
+ case 270 /* ExportAssignment */:
+ case 260 /* ModuleDeclaration */:
+ case 256 /* ClassDeclaration */:
+ case 257 /* InterfaceDeclaration */:
+ case 259 /* EnumDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ return true;
+ }
+ }
+ return false;
+ }
+ function isReusableEnumMember(node) {
+ return node.kind === 297 /* EnumMember */;
+ }
+ function isReusableTypeMember(node) {
+ if (node) {
+ switch (node.kind) {
+ case 174 /* ConstructSignature */:
+ case 167 /* MethodSignature */:
+ case 175 /* IndexSignature */:
+ case 165 /* PropertySignature */:
+ case 173 /* CallSignature */:
+ return true;
+ }
+ }
+ return false;
+ }
+ function isReusableVariableDeclaration(node) {
+ if (node.kind !== 253 /* 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);
+ }
+ function getExpectedCommaDiagnostic(kind) {
+ return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
+ }
+ function createMissingList() {
+ var list = createNodeArray([], getNodePos());
+ list.isMissingList = true;
+ return list;
+ }
+ function isMissingList(arr) {
+ return !!arr.isMissingList;
+ }
+ function parseBracketedList(kind, parseElement, open, close) {
+ if (parseExpected(open)) {
+ var result = parseDelimitedList(kind, parseElement);
+ parseExpected(close);
+ return result;
+ }
+ return createMissingList();
+ }
+ function parseEntityName(allowReservedWords, diagnosticMessage) {
+ var pos = getNodePos();
+ var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
+ var dotPos = getNodePos();
+ while (parseOptional(24 /* DotToken */)) {
+ if (token() === 29 /* LessThanToken */) {
+ // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
+ entity.jsdocDotPos = dotPos;
+ break;
+ }
+ dotPos = getNodePos();
+ entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
+ }
+ return entity;
+ }
+ function createQualifiedName(entity, name) {
+ return finishNode(factory.createQualifiedName(entity, name), entity.pos);
+ }
+ function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
+ // 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) {
+ // 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(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
+ }
+ }
+ if (token() === 80 /* PrivateIdentifier */) {
+ var node = parsePrivateIdentifier();
+ return allowPrivateIdentifiers ? node : createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
+ }
+ return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
+ }
+ function parseTemplateSpans(isTaggedTemplate) {
+ var pos = getNodePos();
+ var list = [];
+ var node;
+ do {
+ node = parseTemplateSpan(isTaggedTemplate);
+ list.push(node);
+ } while (node.literal.kind === 16 /* TemplateMiddle */);
+ return createNodeArray(list, pos);
+ }
+ function parseTemplateExpression(isTaggedTemplate) {
+ var pos = getNodePos();
+ return finishNode(factory.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos);
+ }
+ function parseTemplateType() {
+ var pos = getNodePos();
+ return finishNode(factory.createTemplateLiteralType(parseTemplateHead(/*isTaggedTemplate*/ false), parseTemplateTypeSpans()), pos);
+ }
+ function parseTemplateTypeSpans() {
+ var pos = getNodePos();
+ var list = [];
+ var node;
+ do {
+ node = parseTemplateTypeSpan();
+ list.push(node);
+ } while (node.literal.kind === 16 /* TemplateMiddle */);
+ return createNodeArray(list, pos);
+ }
+ function parseTemplateTypeSpan() {
+ var pos = getNodePos();
+ return finishNode(factory.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false)), pos);
+ }
+ function parseLiteralOfTemplateSpan(isTaggedTemplate) {
+ if (token() === 19 /* CloseBraceToken */) {
+ reScanTemplateToken(isTaggedTemplate);
+ return parseTemplateMiddleOrTemplateTail();
+ }
+ else {
+ // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly?
+ return parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
+ }
+ }
+ function parseTemplateSpan(isTaggedTemplate) {
+ var pos = getNodePos();
+ return finishNode(factory.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos);
+ }
+ function parseLiteralNode() {
+ return parseLiteralLikeNode(token());
+ }
+ function parseTemplateHead(isTaggedTemplate) {
+ if (isTaggedTemplate) {
+ reScanTemplateHeadOrNoSubstitutionTemplate();
+ }
+ var fragment = parseLiteralLikeNode(token());
+ ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
+ return fragment;
+ }
+ function parseTemplateMiddleOrTemplateTail() {
+ var fragment = parseLiteralLikeNode(token());
+ ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
+ return fragment;
+ }
+ function getTemplateLiteralRawText(kind) {
+ var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
+ var tokenText = scanner.getTokenText();
+ return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
+ }
+ function parseLiteralLikeNode(kind) {
+ var pos = getNodePos();
+ var node = ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */) :
+ // 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.
+ kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
+ kind === 10 /* StringLiteral */ ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
+ ts.isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
+ ts.Debug.fail();
+ if (scanner.hasExtendedUnicodeEscape()) {
+ node.hasExtendedUnicodeEscape = true;
+ }
+ if (scanner.isUnterminated()) {
+ node.isUnterminated = true;
+ }
+ nextToken();
+ return finishNode(node, pos);
+ }
+ // TYPES
+ function parseEntityNameOfTypeReference() {
+ return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
+ }
+ function parseTypeArgumentsOfTypeReference() {
+ if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
+ return parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
+ }
+ }
+ function parseTypeReference() {
+ var pos = getNodePos();
+ return finishNode(factory.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos);
+ }
+ // If true, we should abort parsing an error function.
+ function typeHasArrowFunctionBlockingParseError(node) {
+ switch (node.kind) {
+ case 177 /* TypeReference */:
+ return ts.nodeIsMissing(node.typeName);
+ case 178 /* FunctionType */:
+ case 179 /* ConstructorType */: {
+ var _a = node, parameters = _a.parameters, type = _a.type;
+ return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
+ }
+ case 190 /* ParenthesizedType */:
+ return typeHasArrowFunctionBlockingParseError(node.type);
+ default:
+ return false;
+ }
+ }
+ function parseThisTypePredicate(lhs) {
+ nextToken();
+ return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos);
+ }
+ function parseThisTypeNode() {
+ var pos = getNodePos();
+ nextToken();
+ return finishNode(factory.createThisTypeNode(), pos);
+ }
+ function parseJSDocAllType() {
+ var pos = getNodePos();
+ nextToken();
+ return finishNode(factory.createJSDocAllType(), pos);
+ }
+ function parseJSDocNonNullableType() {
+ var pos = getNodePos();
+ nextToken();
+ return finishNode(factory.createJSDocNonNullableType(parseNonArrayType()), pos);
+ }
+ function parseJSDocUnknownOrNullableType() {
+ var pos = getNodePos();
+ // skip the ?
+ nextToken();
+ // 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() === 27 /* CommaToken */ ||
+ token() === 19 /* CloseBraceToken */ ||
+ token() === 21 /* CloseParenToken */ ||
+ token() === 31 /* GreaterThanToken */ ||
+ token() === 63 /* EqualsToken */ ||
+ token() === 51 /* BarToken */) {
+ return finishNode(factory.createJSDocUnknownType(), pos);
+ }
+ else {
+ return finishNode(factory.createJSDocNullableType(parseType()), pos);
+ }
+ }
+ function parseJSDocFunctionType() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ if (lookAhead(nextTokenIsOpenParen)) {
+ nextToken();
+ var parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
+ }
+ return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos);
+ }
+ function parseJSDocParameter() {
+ var pos = getNodePos();
+ var name;
+ if (token() === 108 /* ThisKeyword */ || token() === 103 /* NewKeyword */) {
+ name = parseIdentifierName();
+ parseExpected(58 /* ColonToken */);
+ }
+ return finishNode(factory.createParameterDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined,
+ // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
+ name,
+ /*questionToken*/ undefined, parseJSDocType(),
+ /*initializer*/ undefined), pos);
+ }
+ function parseJSDocType() {
+ scanner.setInJSDocType(true);
+ var pos = getNodePos();
+ if (parseOptional(141 /* ModuleKeyword */)) {
+ // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here?
+ var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined);
+ terminate: while (true) {
+ switch (token()) {
+ case 19 /* CloseBraceToken */:
+ case 1 /* EndOfFileToken */:
+ case 27 /* CommaToken */:
+ case 5 /* WhitespaceTrivia */:
+ break terminate;
+ default:
+ nextTokenJSDoc();
+ }
+ }
+ scanner.setInJSDocType(false);
+ return finishNode(moduleTag, pos);
+ }
+ var hasDotDotDot = parseOptional(25 /* DotDotDotToken */);
+ var type = parseTypeOrTypePredicate();
+ scanner.setInJSDocType(false);
+ if (hasDotDotDot) {
+ type = finishNode(factory.createJSDocVariadicType(type), pos);
+ }
+ if (token() === 63 /* EqualsToken */) {
+ nextToken();
+ return finishNode(factory.createJSDocOptionalType(type), pos);
+ }
+ return type;
+ }
+ function parseTypeQuery() {
+ var pos = getNodePos();
+ parseExpected(112 /* TypeOfKeyword */);
+ return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
+ }
+ function parseTypeParameter() {
+ var pos = getNodePos();
+ var name = parseIdentifier();
+ var constraint;
+ var expression;
+ if (parseOptional(94 /* 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()) {
+ 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 "".
+ expression = parseUnaryExpressionOrHigher();
+ }
+ }
+ var defaultType = parseOptional(63 /* EqualsToken */) ? parseType() : undefined;
+ var node = factory.createTypeParameterDeclaration(name, constraint, defaultType);
+ node.expression = expression;
+ return finishNode(node, pos);
+ }
+ function parseTypeParameters() {
+ if (token() === 29 /* LessThanToken */) {
+ return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
+ }
+ }
+ function isStartOfParameter(isJSDocParameter) {
+ return token() === 25 /* DotDotDotToken */ ||
+ isBindingIdentifierOrPrivateIdentifierOrPattern() ||
+ ts.isModifierKind(token()) ||
+ token() === 59 /* AtToken */ ||
+ isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
+ }
+ function parseNameOfParameter(modifiers) {
+ // FormalParameter [Yield,Await]:
+ // BindingElement[?Yield,?Await]
+ var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
+ if (ts.getFullWidth(name) === 0 && !ts.some(modifiers) && 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();
+ }
+ return name;
+ }
+ function parseParameterInOuterAwaitContext() {
+ return parseParameterWorker(/*inOuterAwaitContext*/ true);
+ }
+ function parseParameter() {
+ return parseParameterWorker(/*inOuterAwaitContext*/ false);
+ }
+ function parseParameterWorker(inOuterAwaitContext) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ // FormalParameter [Yield,Await]:
+ // BindingElement[?Yield,?Await]
+ // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
+ var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators();
+ if (token() === 108 /* ThisKeyword */) {
+ var node_1 = factory.createParameterDeclaration(decorators,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true),
+ /*questionToken*/ undefined, parseTypeAnnotation(),
+ /*initializer*/ undefined);
+ if (decorators) {
+ parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters);
+ }
+ return withJSDoc(finishNode(node_1, pos), hasJSDoc);
+ }
+ var savedTopLevel = topLevel;
+ topLevel = false;
+ var modifiers = parseModifiers();
+ var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, parseOptionalToken(25 /* DotDotDotToken */), parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc);
+ topLevel = savedTopLevel;
+ return node;
+ }
+ function parseReturnType(returnToken, isType) {
+ if (shouldParseReturnType(returnToken, isType)) {
+ return parseTypeOrTypePredicate();
+ }
+ }
+ function shouldParseReturnType(returnToken, isType) {
+ if (returnToken === 38 /* EqualsGreaterThanToken */) {
+ parseExpected(returnToken);
+ return true;
+ }
+ else if (parseOptional(58 /* ColonToken */)) {
+ return true;
+ }
+ else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
+ // This is easy to get backward, especially in type contexts, so parse the type anyway
+ parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
+ nextToken();
+ return true;
+ }
+ return false;
+ }
+ function parseParametersWorker(flags) {
+ // 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
+ var savedYieldContext = inYieldContext();
+ var savedAwaitContext = inAwaitContext();
+ setYieldContext(!!(flags & 1 /* Yield */));
+ setAwaitContext(!!(flags & 2 /* Await */));
+ var parameters = flags & 32 /* JSDoc */ ?
+ parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
+ parseDelimitedList(16 /* Parameters */, savedAwaitContext ? parseParameterInOuterAwaitContext : parseParameter);
+ setYieldContext(savedYieldContext);
+ setAwaitContext(savedAwaitContext);
+ return parameters;
+ }
+ function parseParameters(flags) {
+ // 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(20 /* OpenParenToken */)) {
+ return createMissingList();
+ }
+ var parameters = parseParametersWorker(flags);
+ parseExpected(21 /* CloseParenToken */);
+ return parameters;
+ }
+ function parseTypeMemberSemicolon() {
+ // 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(27 /* CommaToken */)) {
+ return;
+ }
+ // Didn't have a comma. We must have a (possible ASI) semicolon.
+ parseSemicolon();
+ }
+ function parseSignatureMember(kind) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ if (kind === 174 /* ConstructSignature */) {
+ parseExpected(103 /* NewKeyword */);
+ }
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(4 /* Type */);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
+ parseTypeMemberSemicolon();
+ var node = kind === 173 /* CallSignature */
+ ? factory.createCallSignature(typeParameters, parameters, type)
+ : factory.createConstructSignature(typeParameters, parameters, type);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function isIndexSignature() {
+ return token() === 22 /* 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() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
+ return true;
+ }
+ if (ts.isModifierKind(token())) {
+ nextToken();
+ if (isIdentifier()) {
+ return true;
+ }
+ }
+ else if (!isIdentifier()) {
+ return false;
+ }
+ else {
+ // Skip the identifier
+ nextToken();
+ }
+ // 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() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
+ return true;
+ }
+ // Question mark could be an indexer with an optional property,
+ // or it could be a conditional expression in a computed property.
+ if (token() !== 57 /* 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() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
+ }
+ function parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ var parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
+ var type = parseTypeAnnotation();
+ parseTypeMemberSemicolon();
+ var node = factory.createIndexSignature(decorators, modifiers, parameters, type);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
+ var name = parsePropertyName();
+ var questionToken = parseOptionalToken(57 /* QuestionToken */);
+ var node;
+ if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
+ // Method signatures don't exist in expression contexts. So they have neither
+ // [Yield] nor [Await]
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(4 /* Type */);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
+ node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
+ }
+ else {
+ var type = parseTypeAnnotation();
+ node = factory.createPropertySignature(modifiers, name, questionToken, type);
+ // 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.
+ if (token() === 63 /* EqualsToken */)
+ node.initializer = parseInitializer();
+ }
+ parseTypeMemberSemicolon();
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function isTypeMemberStart() {
+ // Return true if we have the start of a signature member
+ if (token() === 20 /* OpenParenToken */ ||
+ token() === 29 /* LessThanToken */ ||
+ token() === 136 /* GetKeyword */ ||
+ token() === 148 /* SetKeyword */) {
+ 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();
+ }
+ // Index signatures and computed property names are type members
+ if (token() === 22 /* 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() === 20 /* OpenParenToken */ ||
+ token() === 29 /* LessThanToken */ ||
+ token() === 57 /* QuestionToken */ ||
+ token() === 58 /* ColonToken */ ||
+ token() === 27 /* CommaToken */ ||
+ canParseSemicolon();
+ }
+ return false;
+ }
+ function parseTypeMember() {
+ if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
+ return parseSignatureMember(173 /* CallSignature */);
+ }
+ if (token() === 103 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
+ return parseSignatureMember(174 /* ConstructSignature */);
+ }
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var modifiers = parseModifiers();
+ if (parseContextualModifier(136 /* GetKeyword */)) {
+ return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 171 /* GetAccessor */);
+ }
+ if (parseContextualModifier(148 /* SetKeyword */)) {
+ return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SetAccessor */);
+ }
+ if (isIndexSignature()) {
+ return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers);
+ }
+ return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
+ }
+ function nextTokenIsOpenParenOrLessThan() {
+ nextToken();
+ return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
+ }
+ function nextTokenIsDot() {
+ return nextToken() === 24 /* DotToken */;
+ }
+ function nextTokenIsOpenParenOrLessThanOrDot() {
+ switch (nextToken()) {
+ case 20 /* OpenParenToken */:
+ case 29 /* LessThanToken */:
+ case 24 /* DotToken */:
+ return true;
+ }
+ return false;
+ }
+ function parseTypeLiteral() {
+ var pos = getNodePos();
+ return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos);
+ }
+ function parseObjectTypeMembers() {
+ var members;
+ if (parseExpected(18 /* OpenBraceToken */)) {
+ members = parseList(4 /* TypeMembers */, parseTypeMember);
+ parseExpected(19 /* CloseBraceToken */);
+ }
+ else {
+ members = createMissingList();
+ }
+ return members;
+ }
+ function isStartOfMappedType() {
+ nextToken();
+ if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
+ return nextToken() === 144 /* ReadonlyKeyword */;
+ }
+ if (token() === 144 /* ReadonlyKeyword */) {
+ nextToken();
+ }
+ return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 101 /* InKeyword */;
+ }
+ function parseMappedTypeParameter() {
+ var pos = getNodePos();
+ var name = parseIdentifierName();
+ parseExpected(101 /* InKeyword */);
+ var type = parseType();
+ return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos);
+ }
+ function parseMappedType() {
+ var pos = getNodePos();
+ parseExpected(18 /* OpenBraceToken */);
+ var readonlyToken;
+ if (token() === 144 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
+ readonlyToken = parseTokenNode();
+ if (readonlyToken.kind !== 144 /* ReadonlyKeyword */) {
+ parseExpected(144 /* ReadonlyKeyword */);
+ }
+ }
+ parseExpected(22 /* OpenBracketToken */);
+ var typeParameter = parseMappedTypeParameter();
+ var nameType = parseOptional(127 /* AsKeyword */) ? parseType() : undefined;
+ parseExpected(23 /* CloseBracketToken */);
+ var questionToken;
+ if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
+ questionToken = parseTokenNode();
+ if (questionToken.kind !== 57 /* QuestionToken */) {
+ parseExpected(57 /* QuestionToken */);
+ }
+ }
+ var type = parseTypeAnnotation();
+ parseSemicolon();
+ var members = parseList(4 /* TypeMembers */, parseTypeMember);
+ parseExpected(19 /* CloseBraceToken */);
+ return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos);
+ }
+ function parseTupleElementType() {
+ var pos = getNodePos();
+ if (parseOptional(25 /* DotDotDotToken */)) {
+ return finishNode(factory.createRestTypeNode(parseType()), pos);
+ }
+ var type = parseType();
+ if (ts.isJSDocNullableType(type) && type.pos === type.type.pos) {
+ var node = factory.createOptionalTypeNode(type.type);
+ ts.setTextRange(node, type);
+ node.flags = type.flags;
+ return node;
+ }
+ return type;
+ }
+ function isNextTokenColonOrQuestionColon() {
+ return nextToken() === 58 /* ColonToken */ || (token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */);
+ }
+ function isTupleElementName() {
+ if (token() === 25 /* DotDotDotToken */) {
+ return ts.tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
+ }
+ return ts.tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
+ }
+ function parseTupleElementNameOrTupleElementType() {
+ if (lookAhead(isTupleElementName)) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
+ var name = parseIdentifierName();
+ var questionToken = parseOptionalToken(57 /* QuestionToken */);
+ parseExpected(58 /* ColonToken */);
+ var type = parseTupleElementType();
+ var node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ return parseTupleElementType();
+ }
+ function parseTupleType() {
+ var pos = getNodePos();
+ return finishNode(factory.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */)), pos);
+ }
+ function parseParenthesizedType() {
+ var pos = getNodePos();
+ parseExpected(20 /* OpenParenToken */);
+ var type = parseType();
+ parseExpected(21 /* CloseParenToken */);
+ return finishNode(factory.createParenthesizedType(type), pos);
+ }
+ function parseModifiersForConstructorType() {
+ var modifiers;
+ if (token() === 126 /* AbstractKeyword */) {
+ var pos = getNodePos();
+ nextToken();
+ var modifier = finishNode(factory.createToken(126 /* AbstractKeyword */), pos);
+ modifiers = createNodeArray([modifier], pos);
+ }
+ return modifiers;
+ }
+ function parseFunctionOrConstructorType() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var modifiers = parseModifiersForConstructorType();
+ var isConstructorType = parseOptional(103 /* NewKeyword */);
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(4 /* Type */);
+ var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
+ var node = isConstructorType
+ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type)
+ : factory.createFunctionTypeNode(typeParameters, parameters, type);
+ if (!isConstructorType)
+ node.modifiers = modifiers;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseKeywordAndNoDot() {
+ var node = parseTokenNode();
+ return token() === 24 /* DotToken */ ? undefined : node;
+ }
+ function parseLiteralTypeNode(negative) {
+ var pos = getNodePos();
+ if (negative) {
+ nextToken();
+ }
+ var expression = token() === 110 /* TrueKeyword */ || token() === 95 /* FalseKeyword */ || token() === 104 /* NullKeyword */ ?
+ parseTokenNode() :
+ parseLiteralLikeNode(token());
+ if (negative) {
+ expression = finishNode(factory.createPrefixUnaryExpression(40 /* MinusToken */, expression), pos);
+ }
+ return finishNode(factory.createLiteralTypeNode(expression), pos);
+ }
+ function isStartOfTypeOfImportType() {
+ nextToken();
+ return token() === 100 /* ImportKeyword */;
+ }
+ function parseImportType() {
+ sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
+ var pos = getNodePos();
+ var isTypeOf = parseOptional(112 /* TypeOfKeyword */);
+ parseExpected(100 /* ImportKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var type = parseType();
+ parseExpected(21 /* CloseParenToken */);
+ var qualifier = parseOptional(24 /* DotToken */) ? parseEntityNameOfTypeReference() : undefined;
+ var typeArguments = parseTypeArgumentsOfTypeReference();
+ return finishNode(factory.createImportTypeNode(type, qualifier, typeArguments, isTypeOf), pos);
+ }
+ function nextTokenIsNumericOrBigIntLiteral() {
+ nextToken();
+ return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
+ }
+ function parseNonArrayType() {
+ switch (token()) {
+ case 130 /* AnyKeyword */:
+ case 154 /* UnknownKeyword */:
+ case 149 /* StringKeyword */:
+ case 146 /* NumberKeyword */:
+ case 157 /* BigIntKeyword */:
+ case 150 /* SymbolKeyword */:
+ case 133 /* BooleanKeyword */:
+ case 152 /* UndefinedKeyword */:
+ case 143 /* NeverKeyword */:
+ case 147 /* ObjectKeyword */:
+ // If these are followed by a dot, then parse these out as a dotted type reference instead.
+ return tryParse(parseKeywordAndNoDot) || parseTypeReference();
+ case 66 /* AsteriskEqualsToken */:
+ // If there is '*=', treat it as * followed by postfix =
+ scanner.reScanAsteriskEqualsToken();
+ // falls through
+ case 41 /* AsteriskToken */:
+ return parseJSDocAllType();
+ case 60 /* QuestionQuestionToken */:
+ // If there is '??', treat it as prefix-'?' in JSDoc type.
+ scanner.reScanQuestionToken();
+ // falls through
+ case 57 /* QuestionToken */:
+ return parseJSDocUnknownOrNullableType();
+ case 98 /* FunctionKeyword */:
+ return parseJSDocFunctionType();
+ case 53 /* ExclamationToken */:
+ return parseJSDocNonNullableType();
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 10 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ case 104 /* NullKeyword */:
+ return parseLiteralTypeNode();
+ case 40 /* MinusToken */:
+ return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
+ case 114 /* VoidKeyword */:
+ return parseTokenNode();
+ case 108 /* ThisKeyword */: {
+ var thisKeyword = parseThisTypeNode();
+ if (token() === 139 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
+ return parseThisTypePredicate(thisKeyword);
+ }
+ else {
+ return thisKeyword;
+ }
+ }
+ case 112 /* TypeOfKeyword */:
+ return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
+ case 18 /* OpenBraceToken */:
+ return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
+ case 22 /* OpenBracketToken */:
+ return parseTupleType();
+ case 20 /* OpenParenToken */:
+ return parseParenthesizedType();
+ case 100 /* ImportKeyword */:
+ return parseImportType();
+ case 128 /* AssertsKeyword */:
+ return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
+ case 15 /* TemplateHead */:
+ return parseTemplateType();
+ default:
+ return parseTypeReference();
+ }
+ }
+ function isStartOfType(inStartOfParameter) {
+ switch (token()) {
+ case 130 /* AnyKeyword */:
+ case 154 /* UnknownKeyword */:
+ case 149 /* StringKeyword */:
+ case 146 /* NumberKeyword */:
+ case 157 /* BigIntKeyword */:
+ case 133 /* BooleanKeyword */:
+ case 144 /* ReadonlyKeyword */:
+ case 150 /* SymbolKeyword */:
+ case 153 /* UniqueKeyword */:
+ case 114 /* VoidKeyword */:
+ case 152 /* UndefinedKeyword */:
+ case 104 /* NullKeyword */:
+ case 108 /* ThisKeyword */:
+ case 112 /* TypeOfKeyword */:
+ case 143 /* NeverKeyword */:
+ case 18 /* OpenBraceToken */:
+ case 22 /* OpenBracketToken */:
+ case 29 /* LessThanToken */:
+ case 51 /* BarToken */:
+ case 50 /* AmpersandToken */:
+ case 103 /* NewKeyword */:
+ case 10 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ case 147 /* ObjectKeyword */:
+ case 41 /* AsteriskToken */:
+ case 57 /* QuestionToken */:
+ case 53 /* ExclamationToken */:
+ case 25 /* DotDotDotToken */:
+ case 137 /* InferKeyword */:
+ case 100 /* ImportKeyword */:
+ case 128 /* AssertsKeyword */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 15 /* TemplateHead */:
+ return true;
+ case 98 /* FunctionKeyword */:
+ return !inStartOfParameter;
+ case 40 /* MinusToken */:
+ return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
+ case 20 /* 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();
+ }
+ }
+ function isStartOfParenthesizedOrFunctionType() {
+ nextToken();
+ return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
+ }
+ function parsePostfixTypeOrHigher() {
+ var pos = getNodePos();
+ var type = parseNonArrayType();
+ while (!scanner.hasPrecedingLineBreak()) {
+ switch (token()) {
+ case 53 /* ExclamationToken */:
+ nextToken();
+ type = finishNode(factory.createJSDocNonNullableType(type), pos);
+ break;
+ case 57 /* QuestionToken */:
+ // If next token is start of a type we have a conditional type
+ if (lookAhead(nextTokenIsStartOfType)) {
+ return type;
+ }
+ nextToken();
+ type = finishNode(factory.createJSDocNullableType(type), pos);
+ break;
+ case 22 /* OpenBracketToken */:
+ parseExpected(22 /* OpenBracketToken */);
+ if (isStartOfType()) {
+ var indexType = parseType();
+ parseExpected(23 /* CloseBracketToken */);
+ type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
+ }
+ else {
+ parseExpected(23 /* CloseBracketToken */);
+ type = finishNode(factory.createArrayTypeNode(type), pos);
+ }
+ break;
+ default:
+ return type;
+ }
+ }
+ return type;
+ }
+ function parseTypeOperator(operator) {
+ var pos = getNodePos();
+ parseExpected(operator);
+ return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
+ }
+ function parseTypeParameterOfInferType() {
+ var pos = getNodePos();
+ return finishNode(factory.createTypeParameterDeclaration(parseIdentifier(),
+ /*constraint*/ undefined,
+ /*defaultType*/ undefined), pos);
+ }
+ function parseInferType() {
+ var pos = getNodePos();
+ parseExpected(137 /* InferKeyword */);
+ return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos);
+ }
+ function parseTypeOperatorOrHigher() {
+ var operator = token();
+ switch (operator) {
+ case 140 /* KeyOfKeyword */:
+ case 153 /* UniqueKeyword */:
+ case 144 /* ReadonlyKeyword */:
+ return parseTypeOperator(operator);
+ case 137 /* InferKeyword */:
+ return parseInferType();
+ }
+ return parsePostfixTypeOrHigher();
+ }
+ function parseFunctionOrConstructorTypeToError(isInUnionType) {
+ // the function type and constructor type shorthand notation
+ // are not allowed directly in unions and intersections, but we'll
+ // try to parse them gracefully and issue a helpful message.
+ if (isStartOfFunctionTypeOrConstructorType()) {
+ var type = parseFunctionOrConstructorType();
+ var diagnostic = void 0;
+ if (ts.isFunctionTypeNode(type)) {
+ diagnostic = isInUnionType
+ ? ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type
+ : ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
+ }
+ else {
+ diagnostic = isInUnionType
+ ? ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type
+ : ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
+ }
+ parseErrorAtRange(type, diagnostic);
+ return type;
+ }
+ return undefined;
+ }
+ function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
+ var pos = getNodePos();
+ var isUnionType = operator === 51 /* BarToken */;
+ var hasLeadingOperator = parseOptional(operator);
+ var type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType)
+ || parseConstituentType();
+ if (token() === operator || hasLeadingOperator) {
+ var types = [type];
+ while (parseOptional(operator)) {
+ types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
+ }
+ type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
+ }
+ return type;
+ }
+ function parseIntersectionTypeOrHigher() {
+ return parseUnionOrIntersectionType(50 /* AmpersandToken */, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode);
+ }
+ function parseUnionTypeOrHigher() {
+ return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
+ }
+ function nextTokenIsNewKeyword() {
+ nextToken();
+ return token() === 103 /* NewKeyword */;
+ }
+ function isStartOfFunctionTypeOrConstructorType() {
+ if (token() === 29 /* LessThanToken */) {
+ return true;
+ }
+ if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
+ return true;
+ }
+ return token() === 103 /* NewKeyword */ ||
+ token() === 126 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword);
+ }
+ function skipParameterStart() {
+ if (ts.isModifierKind(token())) {
+ // Skip modifiers
+ parseModifiers();
+ }
+ if (isIdentifier() || token() === 108 /* ThisKeyword */) {
+ nextToken();
+ return true;
+ }
+ if (token() === 22 /* OpenBracketToken */ || token() === 18 /* 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;
+ }
+ return false;
+ }
+ function isUnambiguouslyStartOfFunctionType() {
+ nextToken();
+ if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
+ // ( )
+ // ( ...
+ return true;
+ }
+ if (skipParameterStart()) {
+ // 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() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
+ token() === 57 /* QuestionToken */ || token() === 63 /* EqualsToken */) {
+ // ( xxx :
+ // ( xxx ,
+ // ( xxx ?
+ // ( xxx =
+ return true;
+ }
+ if (token() === 21 /* CloseParenToken */) {
+ nextToken();
+ if (token() === 38 /* EqualsGreaterThanToken */) {
+ // ( xxx ) =>
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ function parseTypeOrTypePredicate() {
+ var pos = getNodePos();
+ var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
+ var type = parseType();
+ if (typePredicateVariable) {
+ return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos);
+ }
+ else {
+ return type;
+ }
+ }
+ function parseTypePredicatePrefix() {
+ var id = parseIdentifier();
+ if (token() === 139 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
+ nextToken();
+ return id;
+ }
+ }
+ function parseAssertsTypePredicate() {
+ var pos = getNodePos();
+ var assertsModifier = parseExpectedToken(128 /* AssertsKeyword */);
+ var parameterName = token() === 108 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
+ var type = parseOptional(139 /* IsKeyword */) ? parseType() : undefined;
+ return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos);
+ }
+ function parseType() {
+ // 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(40960 /* TypeExcludesFlags */, parseTypeWorker);
+ }
+ function parseTypeWorker(noConditionalTypes) {
+ if (isStartOfFunctionTypeOrConstructorType()) {
+ return parseFunctionOrConstructorType();
+ }
+ var pos = getNodePos();
+ var type = parseUnionTypeOrHigher();
+ if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(94 /* ExtendsKeyword */)) {
+ // The type following 'extends' is not permitted to be another conditional type
+ var extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
+ parseExpected(57 /* QuestionToken */);
+ var trueType = parseTypeWorker();
+ parseExpected(58 /* ColonToken */);
+ var falseType = parseTypeWorker();
+ return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
+ }
+ return type;
+ }
+ function parseTypeAnnotation() {
+ return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
+ }
+ // EXPRESSIONS
+ function isStartOfLeftHandSideExpression() {
+ switch (token()) {
+ case 108 /* ThisKeyword */:
+ case 106 /* SuperKeyword */:
+ case 104 /* NullKeyword */:
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 15 /* TemplateHead */:
+ case 20 /* OpenParenToken */:
+ case 22 /* OpenBracketToken */:
+ case 18 /* OpenBraceToken */:
+ case 98 /* FunctionKeyword */:
+ case 84 /* ClassKeyword */:
+ case 103 /* NewKeyword */:
+ case 43 /* SlashToken */:
+ case 68 /* SlashEqualsToken */:
+ case 79 /* Identifier */:
+ return true;
+ case 100 /* ImportKeyword */:
+ return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
+ default:
+ return isIdentifier();
+ }
+ }
+ function isStartOfExpression() {
+ if (isStartOfLeftHandSideExpression()) {
+ return true;
+ }
+ switch (token()) {
+ case 39 /* PlusToken */:
+ case 40 /* MinusToken */:
+ case 54 /* TildeToken */:
+ case 53 /* ExclamationToken */:
+ case 89 /* DeleteKeyword */:
+ case 112 /* TypeOfKeyword */:
+ case 114 /* VoidKeyword */:
+ case 45 /* PlusPlusToken */:
+ case 46 /* MinusMinusToken */:
+ case 29 /* LessThanToken */:
+ case 132 /* AwaitKeyword */:
+ case 125 /* YieldKeyword */:
+ case 80 /* PrivateIdentifier */:
+ // 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;
+ }
+ return isIdentifier();
+ }
+ }
+ function isStartOfExpressionStatement() {
+ // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
+ return token() !== 18 /* OpenBraceToken */ &&
+ token() !== 98 /* FunctionKeyword */ &&
+ token() !== 84 /* ClassKeyword */ &&
+ token() !== 59 /* 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(/*val*/ false);
+ }
+ var pos = getNodePos();
+ var expr = parseAssignmentExpressionOrHigher();
+ var operatorToken;
+ while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
+ expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos);
+ }
+ if (saveDecoratorContext) {
+ setDecoratorContext(/*val*/ true);
+ }
+ return expr;
+ }
+ function parseInitializer() {
+ return parseOptional(63 /* 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;
+ }
+ // 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 pos = getNodePos();
+ var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
+ // 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 === 79 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
+ return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined);
+ }
+ // 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(), pos);
+ }
+ // It wasn't an assignment or a lambda. This is a conditional expression:
+ return parseConditionalExpressionRest(expr, pos);
+ }
+ function isYieldExpression() {
+ if (token() === 125 /* 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;
+ }
+ function nextTokenIsIdentifierOnSameLine() {
+ nextToken();
+ return !scanner.hasPrecedingLineBreak() && isIdentifier();
+ }
+ function parseYieldExpression() {
+ var pos = getNodePos();
+ // 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() === 41 /* AsteriskToken */ || isStartOfExpression())) {
+ return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */), parseAssignmentExpressionOrHigher()), pos);
+ }
+ 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(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos);
+ }
+ }
+ function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) {
+ ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
+ var parameter = factory.createParameterDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, identifier,
+ /*questionToken*/ undefined,
+ /*type*/ undefined,
+ /*initializer*/ undefined);
+ finishNode(parameter, identifier.pos);
+ var parameters = createNodeArray([parameter], parameter.pos, parameter.end);
+ var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
+ var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
+ var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body);
+ return addJSDocComment(finishNode(node, pos));
+ }
+ function tryParseParenthesizedArrowFunctionExpression() {
+ var triState = isParenthesizedArrowFunctionExpression();
+ if (triState === 0 /* False */) {
+ // It's definitely not a parenthesized arrow function expression.
+ return undefined;
+ }
+ // 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.
+ return triState === 1 /* True */ ?
+ parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) :
+ tryParse(parsePossibleParenthesizedArrowFunctionExpression);
+ }
+ // 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() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 131 /* AsyncKeyword */) {
+ return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
+ }
+ if (token() === 38 /* 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 */;
+ }
+ // Definitely not a parenthesized arrow function.
+ return 0 /* False */;
+ }
+ function isParenthesizedArrowFunctionExpressionWorker() {
+ if (token() === 131 /* AsyncKeyword */) {
+ nextToken();
+ if (scanner.hasPrecedingLineBreak()) {
+ return 0 /* False */;
+ }
+ if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
+ return 0 /* False */;
+ }
+ }
+ var first = token();
+ var second = nextToken();
+ if (first === 20 /* OpenParenToken */) {
+ if (second === 21 /* 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 38 /* EqualsGreaterThanToken */:
+ case 58 /* ColonToken */:
+ case 18 /* OpenBraceToken */:
+ return 1 /* True */;
+ default:
+ return 0 /* False */;
+ }
+ }
+ // If encounter "([" or "({", this could be the start of a binding pattern.
+ // Examples:
+ // ([ x ]) => { }
+ // ({ x }) => { }
+ // ([ x ])
+ // ({ x })
+ if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
+ return 2 /* Unknown */;
+ }
+ // Simple case: "(..."
+ // This is an arrow function with a rest parameter.
+ if (second === 25 /* DotDotDotToken */) {
+ return 1 /* True */;
+ }
+ // 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 !== 131 /* 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. "this" is not
+ // valid, but we want to parse it and then give a semantic error.
+ if (!isIdentifier() && second !== 108 /* ThisKeyword */) {
+ return 0 /* False */;
+ }
+ switch (nextToken()) {
+ case 58 /* ColonToken */:
+ // If we have something like "(a:", then we must have a
+ // type-annotated parameter in an arrow function expression.
+ return 1 /* True */;
+ case 57 /* QuestionToken */:
+ nextToken();
+ // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
+ if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 63 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
+ return 1 /* True */;
+ }
+ // Otherwise it is definitely not a lambda.
+ return 0 /* False */;
+ case 27 /* CommaToken */:
+ case 63 /* EqualsToken */:
+ case 21 /* CloseParenToken */:
+ // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
+ return 2 /* Unknown */;
+ }
+ // It is definitely not an arrow function
+ return 0 /* False */;
+ }
+ else {
+ ts.Debug.assert(first === 29 /* LessThanToken */);
+ // If we have "<" not followed by an identifier,
+ // then this definitely is not an arrow function.
+ if (!isIdentifier()) {
+ return 0 /* False */;
+ }
+ // JSX overrides
+ if (languageVariant === 1 /* JSX */) {
+ var isArrowFunctionInJsx = lookAhead(function () {
+ var third = nextToken();
+ if (third === 94 /* ExtendsKeyword */) {
+ var fourth = nextToken();
+ switch (fourth) {
+ case 63 /* EqualsToken */:
+ case 31 /* GreaterThanToken */:
+ return false;
+ default:
+ return true;
+ }
+ }
+ else if (third === 27 /* CommaToken */) {
+ return true;
+ }
+ return false;
+ });
+ if (isArrowFunctionInJsx) {
+ return 1 /* True */;
+ }
+ return 0 /* False */;
+ }
+ // This *could* be a parenthesized arrow function.
+ return 2 /* Unknown */;
+ }
+ }
+ function parsePossibleParenthesizedArrowFunctionExpression() {
+ var tokenPos = scanner.getTokenPos();
+ if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) {
+ return undefined;
+ }
+ var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false);
+ if (!result) {
+ (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos);
+ }
+ return result;
+ }
+ function tryParseAsyncSimpleArrowFunctionExpression() {
+ // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
+ if (token() === 131 /* AsyncKeyword */) {
+ if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
+ var pos = getNodePos();
+ var asyncModifier = parseModifiersForArrowFunction();
+ var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
+ return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier);
+ }
+ }
+ return undefined;
+ }
+ function isUnParenthesizedAsyncArrowFunctionWorker() {
+ // AsyncArrowFunctionExpression:
+ // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
+ // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
+ if (token() === 131 /* AsyncKeyword */) {
+ nextToken();
+ // 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() === 38 /* EqualsGreaterThanToken */) {
+ return 0 /* False */;
+ }
+ // Check for un-parenthesized AsyncArrowFunction
+ var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
+ if (!scanner.hasPrecedingLineBreak() && expr.kind === 79 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
+ return 1 /* True */;
+ }
+ }
+ return 0 /* False */;
+ }
+ function parseParenthesizedArrowFunctionExpression(allowAmbiguity) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var modifiers = parseModifiersForArrowFunction();
+ var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 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.
+ var typeParameters = parseTypeParameters();
+ var parameters;
+ if (!parseExpected(20 /* OpenParenToken */)) {
+ if (!allowAmbiguity) {
+ return undefined;
+ }
+ parameters = createMissingList();
+ }
+ else {
+ parameters = parseParametersWorker(isAsync);
+ if (!parseExpected(21 /* CloseParenToken */) && !allowAmbiguity) {
+ return undefined;
+ }
+ }
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
+ return undefined;
+ }
+ // 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.
+ // - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
+ //
+ // So we need just a bit of lookahead to ensure that it can only be a signature.
+ var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type);
+ if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
+ // Returning undefined here will cause our caller to rewind to where we started from.
+ return undefined;
+ }
+ // 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();
+ var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
+ var body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
+ ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier))
+ : parseIdentifier();
+ var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseArrowFunctionExpressionBody(isAsync) {
+ if (token() === 18 /* OpenBraceToken */) {
+ return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
+ }
+ if (token() !== 26 /* SemicolonToken */ &&
+ token() !== 98 /* FunctionKeyword */ &&
+ token() !== 84 /* ClassKeyword */ &&
+ isStartOfStatement() &&
+ !isStartOfExpressionStatement()) {
+ // 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 */));
+ }
+ var savedTopLevel = topLevel;
+ topLevel = false;
+ var node = isAsync
+ ? doInAwaitContext(parseAssignmentExpressionOrHigher)
+ : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
+ topLevel = savedTopLevel;
+ return node;
+ }
+ function parseConditionalExpressionRest(leftOperand, pos) {
+ // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
+ var questionToken = parseOptionalToken(57 /* QuestionToken */);
+ if (!questionToken) {
+ return leftOperand;
+ }
+ // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
+ // we do not that for the 'whenFalse' part.
+ var colonToken;
+ return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* ColonToken */), ts.nodeIsPresent(colonToken)
+ ? parseAssignmentExpressionOrHigher()
+ : createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */))), pos);
+ }
+ function parseBinaryExpressionOrHigher(precedence) {
+ var pos = getNodePos();
+ var leftOperand = parseUnaryExpressionOrHigher();
+ return parseBinaryExpressionRest(precedence, leftOperand, pos);
+ }
+ function isInOrOfKeyword(t) {
+ return t === 101 /* InKeyword */ || t === 159 /* OfKeyword */;
+ }
+ function parseBinaryExpressionRest(precedence, leftOperand, pos) {
+ 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());
+ // 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() === 42 /* AsteriskAsteriskToken */ ?
+ newPrecedence >= precedence :
+ newPrecedence > precedence;
+ if (!consumeCurrentOperator) {
+ break;
+ }
+ if (token() === 101 /* InKeyword */ && inDisallowInContext()) {
+ break;
+ }
+ if (token() === 127 /* 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;
+ }
+ else {
+ nextToken();
+ leftOperand = makeAsExpression(leftOperand, parseType());
+ }
+ }
+ else {
+ leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
+ }
+ }
+ return leftOperand;
+ }
+ function isBinaryOperator() {
+ if (inDisallowInContext() && token() === 101 /* InKeyword */) {
+ return false;
+ }
+ return ts.getBinaryOperatorPrecedence(token()) > 0;
+ }
+ function makeBinaryExpression(left, operatorToken, right, pos) {
+ return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
+ }
+ function makeAsExpression(left, right) {
+ return finishNode(factory.createAsExpression(left, right), left.pos);
+ }
+ function parsePrefixUnaryExpression() {
+ var pos = getNodePos();
+ return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
+ }
+ function parseDeleteExpression() {
+ var pos = getNodePos();
+ return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
+ }
+ function parseTypeOfExpression() {
+ var pos = getNodePos();
+ return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
+ }
+ function parseVoidExpression() {
+ var pos = getNodePos();
+ return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
+ }
+ function isAwaitExpression() {
+ if (token() === 132 /* AwaitKeyword */) {
+ if (inAwaitContext()) {
+ return true;
+ }
+ // here we are using similar heuristics as 'isYieldExpression'
+ return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
+ }
+ return false;
+ }
+ function parseAwaitExpression() {
+ var pos = getNodePos();
+ return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
+ }
+ /**
+ * 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 pos = getNodePos();
+ var updateExpression = parseUpdateExpression();
+ return token() === 42 /* AsteriskAsteriskToken */ ?
+ parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression, pos) :
+ 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() === 42 /* AsteriskAsteriskToken */) {
+ var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
+ var end = simpleUnaryExpression.end;
+ if (simpleUnaryExpression.kind === 210 /* 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 {
+ parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator));
+ }
+ }
+ 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 39 /* PlusToken */:
+ case 40 /* MinusToken */:
+ case 54 /* TildeToken */:
+ case 53 /* ExclamationToken */:
+ return parsePrefixUnaryExpression();
+ case 89 /* DeleteKeyword */:
+ return parseDeleteExpression();
+ case 112 /* TypeOfKeyword */:
+ return parseTypeOfExpression();
+ case 114 /* VoidKeyword */:
+ return parseVoidExpression();
+ case 29 /* LessThanToken */:
+ // This is modified UnaryExpression grammar in TypeScript
+ // UnaryExpression (modified):
+ // < type > UnaryExpression
+ return parseTypeAssertion();
+ case 132 /* 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 39 /* PlusToken */:
+ case 40 /* MinusToken */:
+ case 54 /* TildeToken */:
+ case 53 /* ExclamationToken */:
+ case 89 /* DeleteKeyword */:
+ case 112 /* TypeOfKeyword */:
+ case 114 /* VoidKeyword */:
+ case 132 /* AwaitKeyword */:
+ return false;
+ case 29 /* LessThanToken */:
+ // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
+ if (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() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
+ var pos = getNodePos();
+ return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
+ }
+ else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
+ // JSXElement is part of primaryExpression
+ return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
+ }
+ var expression = parseLeftHandSideExpressionOrHigher();
+ ts.Debug.assert(ts.isLeftHandSideExpression(expression));
+ if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
+ var operator = token();
+ nextToken();
+ return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos);
+ }
+ 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 pos = getNodePos();
+ var expression;
+ if (token() === 100 /* ImportKeyword */) {
+ if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
+ // 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
+ sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
+ expression = parseTokenNode();
+ }
+ else if (lookAhead(nextTokenIsDot)) {
+ // This is an 'import.*' metaproperty (i.e. 'import.meta')
+ nextToken(); // advance past the 'import'
+ nextToken(); // advance past the dot
+ expression = finishNode(factory.createMetaProperty(100 /* ImportKeyword */, parseIdentifierName()), pos);
+ sourceFlags |= 2097152 /* PossiblyContainsImportMeta */;
+ }
+ else {
+ expression = parseMemberExpressionOrHigher();
+ }
+ }
+ else {
+ expression = token() === 106 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
+ }
+ // Now, we *may* be complete. However, we might have consumed the start of a
+ // CallExpression or OptionalExpression. As such, we need to consume the rest
+ // of it here to be complete.
+ return parseCallExpressionRest(pos, 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 pos = getNodePos();
+ var expression = parsePrimaryExpression();
+ return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
+ }
+ function parseSuperExpression() {
+ var pos = getNodePos();
+ var expression = parseTokenNode();
+ if (token() === 29 /* LessThanToken */) {
+ var startPos = getNodePos();
+ var typeArguments = tryParse(parseTypeArgumentsInExpression);
+ if (typeArguments !== undefined) {
+ parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
+ }
+ }
+ if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
+ return expression;
+ }
+ // 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.
+ parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
+ // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
+ return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
+ }
+ function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition, openingTag) {
+ var pos = getNodePos();
+ var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
+ var result;
+ if (opening.kind === 279 /* JsxOpeningElement */) {
+ var children = parseJsxChildren(opening);
+ var closingElement = void 0;
+ var lastChild = children[children.length - 1];
+ if ((lastChild === null || lastChild === void 0 ? void 0 : lastChild.kind) === 277 /* JsxElement */
+ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName)
+ && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) {
+ // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement,
+ // restructure ((......
)) --> ((......>)
)
+ // (no need to error; the parent will error)
+ var end = lastChild.children.end;
+ var newLast = finishNode(factory.createJsxElement(lastChild.openingElement, lastChild.children, finishNode(factory.createJsxClosingElement(finishNode(factory.createIdentifier(""), end, end)), end, end)), lastChild.openingElement.pos, end);
+ children = createNodeArray(__spreadArray(__spreadArray([], children.slice(0, children.length - 1), true), [newLast], false), children.pos, end);
+ closingElement = lastChild.closingElement;
+ }
+ else {
+ closingElement = parseJsxClosingElement(opening, inExpressionContext);
+ if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
+ if (openingTag && ts.isJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.tagName, openingTag.tagName)) {
+ // opening incorrectly matched with its parent's closing -- put error on opening
+ parseErrorAtRange(opening.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
+ }
+ else {
+ // other opening/closing mismatches -- put error on closing
+ parseErrorAtRange(closingElement.tagName, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
+ }
+ }
+ }
+ result = finishNode(factory.createJsxElement(opening, children, closingElement), pos);
+ }
+ else if (opening.kind === 282 /* JsxOpeningFragment */) {
+ result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
+ }
+ else {
+ ts.Debug.assert(opening.kind === 278 /* JsxSelfClosingElement */);
+ // Nothing else to do for self-closing elements
+ result = opening;
+ }
+ // 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() === 29 /* LessThanToken */) {
+ var topBadPos_1 = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
+ var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos_1); });
+ if (invalidElement) {
+ var operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
+ ts.setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
+ parseErrorAt(ts.skipTrivia(sourceText, topBadPos_1), invalidElement.end, ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
+ return finishNode(factory.createBinaryExpression(result, operatorToken, invalidElement), pos);
+ }
+ }
+ return result;
+ }
+ function parseJsxText() {
+ var pos = getNodePos();
+ var node = factory.createJsxText(scanner.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */);
+ currentToken = scanner.scanJsxToken();
+ return finishNode(node, pos);
+ }
+ function parseJsxChild(openingTag, token) {
+ switch (token) {
+ 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);
+ }
+ else {
+ // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
+ // or to cover only 'Foo' in < Foo >
+ var tag = openingTag.tagName;
+ var start = ts.skipTrivia(sourceText, tag.pos);
+ parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
+ }
+ return undefined;
+ case 30 /* LessThanSlashToken */:
+ case 7 /* ConflictMarkerTrivia */:
+ return undefined;
+ case 11 /* JsxText */:
+ case 12 /* JsxTextAllWhiteSpaces */:
+ return parseJsxText();
+ case 18 /* OpenBraceToken */:
+ return parseJsxExpression(/*inExpressionContext*/ false);
+ case 29 /* LessThanToken */:
+ return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false, /*topInvalidNodePosition*/ undefined, openingTag);
+ default:
+ return ts.Debug.assertNever(token);
+ }
+ }
+ function parseJsxChildren(openingTag) {
+ var list = [];
+ var listPos = getNodePos();
+ var saveParsingContext = parsingContext;
+ parsingContext |= 1 << 14 /* JsxChildren */;
+ while (true) {
+ var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
+ if (!child)
+ break;
+ list.push(child);
+ if (ts.isJsxOpeningElement(openingTag)
+ && (child === null || child === void 0 ? void 0 : child.kind) === 277 /* JsxElement */
+ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName)
+ && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) {
+ // stop after parsing a mismatched child like ...(
) in order to reattach the higher
+ break;
+ }
+ }
+ parsingContext = saveParsingContext;
+ return createNodeArray(list, listPos);
+ }
+ function parseJsxAttributes() {
+ var pos = getNodePos();
+ return finishNode(factory.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
+ }
+ function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
+ var pos = getNodePos();
+ parseExpected(29 /* LessThanToken */);
+ if (token() === 31 /* GreaterThanToken */) {
+ // See below for explanation of scanJsxText
+ scanJsxText();
+ return finishNode(factory.createJsxOpeningFragment(), pos);
+ }
+ var tagName = parseJsxElementName();
+ var typeArguments = (contextFlags & 131072 /* JavaScriptFile */) === 0 ? tryParseTypeArguments() : undefined;
+ var attributes = parseJsxAttributes();
+ var node;
+ if (token() === 31 /* 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
+ scanJsxText();
+ node = factory.createJsxOpeningElement(tagName, typeArguments, attributes);
+ }
+ else {
+ parseExpected(43 /* SlashToken */);
+ if (parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
+ // manually advance the scanner in order to look for jsx text inside jsx
+ if (inExpressionContext) {
+ nextToken();
+ }
+ else {
+ scanJsxText();
+ }
+ }
+ node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes);
+ }
+ return finishNode(node, pos);
+ }
+ function parseJsxElementName() {
+ var pos = getNodePos();
+ scanJsxIdentifier();
+ // 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() === 108 /* ThisKeyword */ ?
+ parseTokenNode() : parseIdentifierName();
+ while (parseOptional(24 /* DotToken */)) {
+ expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos);
+ }
+ return expression;
+ }
+ function parseJsxExpression(inExpressionContext) {
+ var pos = getNodePos();
+ if (!parseExpected(18 /* OpenBraceToken */)) {
+ return undefined;
+ }
+ var dotDotDotToken;
+ var expression;
+ if (token() !== 19 /* CloseBraceToken */) {
+ dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
+ // Only an AssignmentExpression is valid here per the JSX spec,
+ // but we can unambiguously parse a comma sequence and provide
+ // a better error message in grammar checking.
+ expression = parseExpression();
+ }
+ if (inExpressionContext) {
+ parseExpected(19 /* CloseBraceToken */);
+ }
+ else {
+ if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
+ scanJsxText();
+ }
+ }
+ return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos);
+ }
+ function parseJsxAttribute() {
+ if (token() === 18 /* OpenBraceToken */) {
+ return parseJsxSpreadAttribute();
+ }
+ scanJsxIdentifier();
+ var pos = getNodePos();
+ return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* EqualsToken */ ? undefined :
+ scanJsxAttributeValue() === 10 /* StringLiteral */ ? parseLiteralNode() :
+ parseJsxExpression(/*inExpressionContext*/ true)), pos);
+ }
+ function parseJsxSpreadAttribute() {
+ var pos = getNodePos();
+ parseExpected(18 /* OpenBraceToken */);
+ parseExpected(25 /* DotDotDotToken */);
+ var expression = parseExpression();
+ parseExpected(19 /* CloseBraceToken */);
+ return finishNode(factory.createJsxSpreadAttribute(expression), pos);
+ }
+ function parseJsxClosingElement(open, inExpressionContext) {
+ var pos = getNodePos();
+ parseExpected(30 /* LessThanSlashToken */);
+ var tagName = parseJsxElementName();
+ if (parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
+ // manually advance the scanner in order to look for jsx text inside jsx
+ if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) {
+ nextToken();
+ }
+ else {
+ scanJsxText();
+ }
+ }
+ return finishNode(factory.createJsxClosingElement(tagName), pos);
+ }
+ function parseJsxClosingFragment(inExpressionContext) {
+ var pos = getNodePos();
+ parseExpected(30 /* LessThanSlashToken */);
+ if (ts.tokenIsIdentifierOrKeyword(token())) {
+ parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
+ }
+ if (parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
+ // manually advance the scanner in order to look for jsx text inside jsx
+ if (inExpressionContext) {
+ nextToken();
+ }
+ else {
+ scanJsxText();
+ }
+ }
+ return finishNode(factory.createJsxJsxClosingFragment(), pos);
+ }
+ function parseTypeAssertion() {
+ var pos = getNodePos();
+ parseExpected(29 /* LessThanToken */);
+ var type = parseType();
+ parseExpected(31 /* GreaterThanToken */);
+ var expression = parseSimpleUnaryExpression();
+ return finishNode(factory.createTypeAssertion(type, expression), pos);
+ }
+ function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
+ nextToken();
+ return ts.tokenIsIdentifierOrKeyword(token())
+ || token() === 22 /* OpenBracketToken */
+ || isTemplateStartOfTaggedTemplate();
+ }
+ function isStartOfOptionalPropertyOrElementAccessChain() {
+ return token() === 28 /* QuestionDotToken */
+ && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
+ }
+ function tryReparseOptionalChain(node) {
+ if (node.flags & 32 /* OptionalChain */) {
+ return true;
+ }
+ // check for an optional chain in a non-null expression
+ if (ts.isNonNullExpression(node)) {
+ var expr = node.expression;
+ while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
+ expr = expr.expression;
+ }
+ if (expr.flags & 32 /* OptionalChain */) {
+ // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
+ while (ts.isNonNullExpression(node)) {
+ node.flags |= 32 /* OptionalChain */;
+ node = node.expression;
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+ function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
+ var name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
+ var isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
+ var propertyAccess = isOptionalChain ?
+ factory.createPropertyAccessChain(expression, questionDotToken, name) :
+ factory.createPropertyAccessExpression(expression, name);
+ if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) {
+ parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
+ }
+ return finishNode(propertyAccess, pos);
+ }
+ function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
+ var argumentExpression;
+ if (token() === 23 /* CloseBracketToken */) {
+ argumentExpression = createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
+ }
+ else {
+ var argument = allowInAnd(parseExpression);
+ if (ts.isStringOrNumericLiteralLike(argument)) {
+ argument.text = internIdentifier(argument.text);
+ }
+ argumentExpression = argument;
+ }
+ parseExpected(23 /* CloseBracketToken */);
+ var indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
+ factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
+ factory.createElementAccessExpression(expression, argumentExpression);
+ return finishNode(indexedAccess, pos);
+ }
+ function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
+ while (true) {
+ var questionDotToken = void 0;
+ var isPropertyAccess = false;
+ if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
+ questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
+ isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
+ }
+ else {
+ isPropertyAccess = parseOptional(24 /* DotToken */);
+ }
+ if (isPropertyAccess) {
+ expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
+ continue;
+ }
+ if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
+ nextToken();
+ expression = finishNode(factory.createNonNullExpression(expression), pos);
+ continue;
+ }
+ // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
+ if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
+ expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
+ continue;
+ }
+ if (isTemplateStartOfTaggedTemplate()) {
+ expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
+ continue;
+ }
+ return expression;
+ }
+ }
+ function isTemplateStartOfTaggedTemplate() {
+ return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
+ }
+ function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
+ var tagExpression = factory.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ?
+ (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) :
+ parseTemplateExpression(/*isTaggedTemplate*/ true));
+ if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
+ tagExpression.flags |= 32 /* OptionalChain */;
+ }
+ tagExpression.questionDotToken = questionDotToken;
+ return finishNode(tagExpression, pos);
+ }
+ function parseCallExpressionRest(pos, expression) {
+ while (true) {
+ expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
+ var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
+ // handle 'foo<()'
+ // parse template arguments only in TypeScript files (not in JavaScript files).
+ if ((contextFlags & 131072 /* JavaScriptFile */) === 0 && (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */)) {
+ // 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) {
+ if (isTemplateStartOfTaggedTemplate()) {
+ expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
+ continue;
+ }
+ var argumentList = parseArgumentList();
+ var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
+ factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
+ factory.createCallExpression(expression, typeArguments, argumentList);
+ expression = finishNode(callExpr, pos);
+ continue;
+ }
+ }
+ else if (token() === 20 /* OpenParenToken */) {
+ var argumentList = parseArgumentList();
+ var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
+ factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
+ factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
+ expression = finishNode(callExpr, pos);
+ continue;
+ }
+ if (questionDotToken) {
+ // We failed to parse anything, so report a missing identifier here.
+ var name = createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
+ expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
+ }
+ break;
+ }
+ return expression;
+ }
+ function parseArgumentList() {
+ parseExpected(20 /* OpenParenToken */);
+ var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
+ parseExpected(21 /* CloseParenToken */);
+ return result;
+ }
+ function parseTypeArgumentsInExpression() {
+ if ((contextFlags & 131072 /* JavaScriptFile */) !== 0) {
+ // TypeArguments must not be parsed in JavaScript files to avoid ambiguity with binary operators.
+ return undefined;
+ }
+ if (reScanLessThanToken() !== 29 /* LessThanToken */) {
+ return undefined;
+ }
+ nextToken();
+ var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
+ if (!parseExpected(31 /* 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 20 /* OpenParenToken */: // foo(
+ case 14 /* NoSubstitutionTemplateLiteral */: // foo `...`
+ case 15 /* 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.
+ // falls through
+ case 24 /* DotToken */: // foo.
+ case 21 /* CloseParenToken */: // foo)
+ case 23 /* CloseBracketToken */: // foo]
+ case 58 /* ColonToken */: // foo:
+ case 26 /* SemicolonToken */: // foo;
+ case 57 /* QuestionToken */: // foo?
+ case 34 /* EqualsEqualsToken */: // foo ==
+ case 36 /* EqualsEqualsEqualsToken */: // foo ===
+ case 35 /* ExclamationEqualsToken */: // foo !=
+ case 37 /* ExclamationEqualsEqualsToken */: // foo !==
+ case 55 /* AmpersandAmpersandToken */: // foo &&
+ case 56 /* BarBarToken */: // foo ||
+ case 60 /* QuestionQuestionToken */: // foo ??
+ case 52 /* CaretToken */: // foo ^
+ case 50 /* AmpersandToken */: // foo &
+ case 51 /* BarToken */: // foo |
+ case 19 /* 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 27 /* CommaToken */: // foo,
+ case 18 /* 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.
+ // falls through
+ default:
+ // Anything else treat as an expression.
+ return false;
+ }
+ }
+ function parsePrimaryExpression() {
+ switch (token()) {
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ return parseLiteralNode();
+ case 108 /* ThisKeyword */:
+ case 106 /* SuperKeyword */:
+ case 104 /* NullKeyword */:
+ case 110 /* TrueKeyword */:
+ case 95 /* FalseKeyword */:
+ return parseTokenNode();
+ case 20 /* OpenParenToken */:
+ return parseParenthesizedExpression();
+ case 22 /* OpenBracketToken */:
+ return parseArrayLiteralExpression();
+ case 18 /* OpenBraceToken */:
+ return parseObjectLiteralExpression();
+ case 131 /* 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 84 /* ClassKeyword */:
+ return parseClassExpression();
+ case 98 /* FunctionKeyword */:
+ return parseFunctionExpression();
+ case 103 /* NewKeyword */:
+ return parseNewExpressionOrNewDotTarget();
+ case 43 /* SlashToken */:
+ case 68 /* SlashEqualsToken */:
+ if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
+ return parseLiteralNode();
+ }
+ break;
+ case 15 /* TemplateHead */:
+ return parseTemplateExpression(/* isTaggedTemplate */ false);
+ case 80 /* PrivateIdentifier */:
+ return parsePrivateIdentifier();
+ }
+ return parseIdentifier(ts.Diagnostics.Expression_expected);
+ }
+ function parseParenthesizedExpression() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(20 /* OpenParenToken */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* CloseParenToken */);
+ return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
+ }
+ function parseSpreadElement() {
+ var pos = getNodePos();
+ parseExpected(25 /* DotDotDotToken */);
+ var expression = parseAssignmentExpressionOrHigher();
+ return finishNode(factory.createSpreadElement(expression), pos);
+ }
+ function parseArgumentOrArrayLiteralElement() {
+ return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
+ token() === 27 /* CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) :
+ parseAssignmentExpressionOrHigher();
+ }
+ function parseArgumentExpression() {
+ return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
+ }
+ function parseArrayLiteralExpression() {
+ var pos = getNodePos();
+ parseExpected(22 /* OpenBracketToken */);
+ var multiLine = scanner.hasPrecedingLineBreak();
+ var elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
+ parseExpected(23 /* CloseBracketToken */);
+ return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
+ }
+ function parseObjectLiteralElement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ if (parseOptionalToken(25 /* DotDotDotToken */)) {
+ var expression = parseAssignmentExpressionOrHigher();
+ return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc);
+ }
+ var decorators = parseDecorators();
+ var modifiers = parseModifiers();
+ if (parseContextualModifier(136 /* GetKeyword */)) {
+ return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 171 /* GetAccessor */);
+ }
+ if (parseContextualModifier(148 /* SetKeyword */)) {
+ return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SetAccessor */);
+ }
+ var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
+ var tokenIsIdentifier = isIdentifier();
+ var name = parsePropertyName();
+ // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
+ var questionToken = parseOptionalToken(57 /* QuestionToken */);
+ var exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
+ if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
+ return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken);
+ }
+ // 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 node;
+ var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
+ if (isShorthandPropertyAssignment) {
+ var equalsToken = parseOptionalToken(63 /* EqualsToken */);
+ var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined;
+ node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
+ // Save equals token for error reporting.
+ // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful.
+ node.equalsToken = equalsToken;
+ }
+ else {
+ parseExpected(58 /* ColonToken */);
+ var initializer = allowInAnd(parseAssignmentExpressionOrHigher);
+ node = factory.createPropertyAssignment(name, initializer);
+ }
+ // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker
+ node.decorators = decorators;
+ node.modifiers = modifiers;
+ node.questionToken = questionToken;
+ node.exclamationToken = exclamationToken;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseObjectLiteralExpression() {
+ var pos = getNodePos();
+ var openBracePosition = scanner.getTokenPos();
+ parseExpected(18 /* OpenBraceToken */);
+ var multiLine = scanner.hasPrecedingLineBreak();
+ var properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
+ if (!parseExpected(19 /* CloseBraceToken */)) {
+ var lastError = ts.lastOrUndefined(parseDiagnostics);
+ if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
+ ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
+ }
+ }
+ return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
+ }
+ function parseFunctionExpression() {
+ // GeneratorExpression:
+ // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
+ //
+ // FunctionExpression:
+ // function BindingIdentifier[opt](FormalParameters){ FunctionBody }
+ var savedDecoratorContext = inDecoratorContext();
+ setDecoratorContext(/*val*/ false);
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var modifiers = parseModifiers();
+ parseExpected(98 /* FunctionKeyword */);
+ var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
+ var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
+ var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
+ var name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
+ isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
+ isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
+ parseOptionalBindingIdentifier();
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(isGenerator | isAsync);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ var body = parseFunctionBlock(isGenerator | isAsync);
+ setDecoratorContext(savedDecoratorContext);
+ var node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseOptionalBindingIdentifier() {
+ return isBindingIdentifier() ? parseBindingIdentifier() : undefined;
+ }
+ function parseNewExpressionOrNewDotTarget() {
+ var pos = getNodePos();
+ parseExpected(103 /* NewKeyword */);
+ if (parseOptional(24 /* DotToken */)) {
+ var name = parseIdentifierName();
+ return finishNode(factory.createMetaProperty(103 /* NewKeyword */, name), pos);
+ }
+ var expressionPos = getNodePos();
+ var expression = parsePrimaryExpression();
+ var typeArguments;
+ while (true) {
+ expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
+ typeArguments = tryParse(parseTypeArgumentsInExpression);
+ if (isTemplateStartOfTaggedTemplate()) {
+ ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
+ expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
+ typeArguments = undefined;
+ }
+ break;
+ }
+ var argumentsArray;
+ if (token() === 20 /* OpenParenToken */) {
+ argumentsArray = parseArgumentList();
+ }
+ else if (typeArguments) {
+ parseErrorAt(pos, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
+ }
+ return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
+ }
+ // STATEMENTS
+ function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var openBracePosition = scanner.getTokenPos();
+ if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
+ var multiLine = scanner.hasPrecedingLineBreak();
+ var statements = parseList(1 /* BlockStatements */, parseStatement);
+ if (!parseExpected(19 /* CloseBraceToken */)) {
+ var lastError = ts.lastOrUndefined(parseDiagnostics);
+ if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
+ ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
+ }
+ }
+ var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc);
+ if (token() === 63 /* EqualsToken */) {
+ parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses);
+ nextToken();
+ }
+ return result;
+ }
+ else {
+ var statements = createMissingList();
+ return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc);
+ }
+ }
+ function parseFunctionBlock(flags, diagnosticMessage) {
+ var savedYieldContext = inYieldContext();
+ setYieldContext(!!(flags & 1 /* Yield */));
+ var savedAwaitContext = inAwaitContext();
+ setAwaitContext(!!(flags & 2 /* Await */));
+ var savedTopLevel = topLevel;
+ topLevel = false;
+ // 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(/*val*/ false);
+ }
+ var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
+ if (saveDecoratorContext) {
+ setDecoratorContext(/*val*/ true);
+ }
+ topLevel = savedTopLevel;
+ setYieldContext(savedYieldContext);
+ setAwaitContext(savedAwaitContext);
+ return block;
+ }
+ function parseEmptyStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(26 /* SemicolonToken */);
+ return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc);
+ }
+ function parseIfStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(99 /* IfKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* CloseParenToken */);
+ var thenStatement = parseStatement();
+ var elseStatement = parseOptional(91 /* ElseKeyword */) ? parseStatement() : undefined;
+ return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc);
+ }
+ function parseDoStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(90 /* DoKeyword */);
+ var statement = parseStatement();
+ parseExpected(115 /* WhileKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* 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(26 /* SemicolonToken */);
+ return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc);
+ }
+ function parseWhileStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(115 /* WhileKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* CloseParenToken */);
+ var statement = parseStatement();
+ return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc);
+ }
+ function parseForOrForInOrForOfStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(97 /* ForKeyword */);
+ var awaitToken = parseOptionalToken(132 /* AwaitKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var initializer;
+ if (token() !== 26 /* SemicolonToken */) {
+ if (token() === 113 /* VarKeyword */ || token() === 119 /* LetKeyword */ || token() === 85 /* ConstKeyword */) {
+ initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
+ }
+ else {
+ initializer = disallowInAnd(parseExpression);
+ }
+ }
+ var node;
+ if (awaitToken ? parseExpected(159 /* OfKeyword */) : parseOptional(159 /* OfKeyword */)) {
+ var expression = allowInAnd(parseAssignmentExpressionOrHigher);
+ parseExpected(21 /* CloseParenToken */);
+ node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
+ }
+ else if (parseOptional(101 /* InKeyword */)) {
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* CloseParenToken */);
+ node = factory.createForInStatement(initializer, expression, parseStatement());
+ }
+ else {
+ parseExpected(26 /* SemicolonToken */);
+ var condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */
+ ? allowInAnd(parseExpression)
+ : undefined;
+ parseExpected(26 /* SemicolonToken */);
+ var incrementor = token() !== 21 /* CloseParenToken */
+ ? allowInAnd(parseExpression)
+ : undefined;
+ parseExpected(21 /* CloseParenToken */);
+ node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
+ }
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseBreakOrContinueStatement(kind) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(kind === 245 /* BreakStatement */ ? 81 /* BreakKeyword */ : 86 /* ContinueKeyword */);
+ var label = canParseSemicolon() ? undefined : parseIdentifier();
+ parseSemicolon();
+ var node = kind === 245 /* BreakStatement */
+ ? factory.createBreakStatement(label)
+ : factory.createContinueStatement(label);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseReturnStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(105 /* ReturnKeyword */);
+ var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression);
+ parseSemicolon();
+ return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc);
+ }
+ function parseWithStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(116 /* WithKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* CloseParenToken */);
+ var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
+ return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc);
+ }
+ function parseCaseClause() {
+ var pos = getNodePos();
+ parseExpected(82 /* CaseKeyword */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(58 /* ColonToken */);
+ var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
+ return finishNode(factory.createCaseClause(expression, statements), pos);
+ }
+ function parseDefaultClause() {
+ var pos = getNodePos();
+ parseExpected(88 /* DefaultKeyword */);
+ parseExpected(58 /* ColonToken */);
+ var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
+ return finishNode(factory.createDefaultClause(statements), pos);
+ }
+ function parseCaseOrDefaultClause() {
+ return token() === 82 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
+ }
+ function parseCaseBlock() {
+ var pos = getNodePos();
+ parseExpected(18 /* OpenBraceToken */);
+ var clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
+ parseExpected(19 /* CloseBraceToken */);
+ return finishNode(factory.createCaseBlock(clauses), pos);
+ }
+ function parseSwitchStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(107 /* SwitchKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var expression = allowInAnd(parseExpression);
+ parseExpected(21 /* CloseParenToken */);
+ var caseBlock = parseCaseBlock();
+ return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc);
+ }
+ function parseThrowStatement() {
+ // ThrowStatement[Yield] :
+ // throw [no LineTerminator here]Expression[In, ?Yield];
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(109 /* ThrowKeyword */);
+ // 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.
+ // Instead, we create a "missing" identifier, but don't report an error. The actual error
+ // will be reported in the grammar walker.
+ var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
+ if (expression === undefined) {
+ identifierCount++;
+ expression = finishNode(factory.createIdentifier(""), getNodePos());
+ }
+ if (!tryParseSemicolon()) {
+ parseErrorForMissingSemicolonAfter(expression);
+ }
+ return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc);
+ }
+ // TODO: Review for error recovery
+ function parseTryStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(111 /* TryKeyword */);
+ var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
+ var catchClause = token() === 83 /* 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.
+ var finallyBlock;
+ if (!catchClause || token() === 96 /* FinallyKeyword */) {
+ parseExpected(96 /* FinallyKeyword */);
+ finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
+ }
+ return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc);
+ }
+ function parseCatchClause() {
+ var pos = getNodePos();
+ parseExpected(83 /* CatchKeyword */);
+ var variableDeclaration;
+ if (parseOptional(20 /* OpenParenToken */)) {
+ variableDeclaration = parseVariableDeclaration();
+ parseExpected(21 /* CloseParenToken */);
+ }
+ else {
+ // Keep shape of node to avoid degrading performance.
+ variableDeclaration = undefined;
+ }
+ var block = parseBlock(/*ignoreMissingOpenBrace*/ false);
+ return finishNode(factory.createCatchClause(variableDeclaration, block), pos);
+ }
+ function parseDebuggerStatement() {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ parseExpected(87 /* DebuggerKeyword */);
+ parseSemicolon();
+ return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc);
+ }
+ function parseExpressionOrLabeledStatement() {
+ // 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 pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var node;
+ var hasParen = token() === 20 /* OpenParenToken */;
+ var expression = allowInAnd(parseExpression);
+ if (ts.isIdentifier(expression) && parseOptional(58 /* ColonToken */)) {
+ node = factory.createLabeledStatement(expression, parseStatement());
+ }
+ else {
+ if (!tryParseSemicolon()) {
+ parseErrorForMissingSemicolonAfter(expression);
+ }
+ node = factory.createExpressionStatement(expression);
+ if (hasParen) {
+ // do not parse the same jsdoc twice
+ hasJSDoc = false;
+ }
+ }
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function nextTokenIsIdentifierOrKeywordOnSameLine() {
+ nextToken();
+ return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
+ }
+ function nextTokenIsClassKeywordOnSameLine() {
+ nextToken();
+ return token() === 84 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
+ }
+ function nextTokenIsFunctionKeywordOnSameLine() {
+ nextToken();
+ return token() === 98 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
+ }
+ function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
+ nextToken();
+ return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
+ }
+ function isDeclaration() {
+ while (true) {
+ switch (token()) {
+ case 113 /* VarKeyword */:
+ case 119 /* LetKeyword */:
+ case 85 /* ConstKeyword */:
+ case 98 /* FunctionKeyword */:
+ case 84 /* ClassKeyword */:
+ case 92 /* EnumKeyword */:
+ return true;
+ // '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 118 /* InterfaceKeyword */:
+ case 151 /* TypeKeyword */:
+ return nextTokenIsIdentifierOnSameLine();
+ case 141 /* ModuleKeyword */:
+ case 142 /* NamespaceKeyword */:
+ return nextTokenIsIdentifierOrStringLiteralOnSameLine();
+ case 126 /* AbstractKeyword */:
+ case 131 /* AsyncKeyword */:
+ case 135 /* DeclareKeyword */:
+ case 121 /* PrivateKeyword */:
+ case 122 /* ProtectedKeyword */:
+ case 123 /* PublicKeyword */:
+ case 144 /* ReadonlyKeyword */:
+ nextToken();
+ // ASI takes effect for this modifier.
+ if (scanner.hasPrecedingLineBreak()) {
+ return false;
+ }
+ continue;
+ case 156 /* GlobalKeyword */:
+ nextToken();
+ return token() === 18 /* OpenBraceToken */ || token() === 79 /* Identifier */ || token() === 93 /* ExportKeyword */;
+ case 100 /* ImportKeyword */:
+ nextToken();
+ return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
+ token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
+ case 93 /* ExportKeyword */:
+ var currentToken_1 = nextToken();
+ if (currentToken_1 === 151 /* TypeKeyword */) {
+ currentToken_1 = lookAhead(nextToken);
+ }
+ if (currentToken_1 === 63 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
+ currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 88 /* DefaultKeyword */ ||
+ currentToken_1 === 127 /* AsKeyword */) {
+ return true;
+ }
+ continue;
+ case 124 /* StaticKeyword */:
+ nextToken();
+ continue;
+ default:
+ return false;
+ }
+ }
+ }
+ function isStartOfDeclaration() {
+ return lookAhead(isDeclaration);
+ }
+ function isStartOfStatement() {
+ switch (token()) {
+ case 59 /* AtToken */:
+ case 26 /* SemicolonToken */:
+ case 18 /* OpenBraceToken */:
+ case 113 /* VarKeyword */:
+ case 119 /* LetKeyword */:
+ case 98 /* FunctionKeyword */:
+ case 84 /* ClassKeyword */:
+ case 92 /* EnumKeyword */:
+ case 99 /* IfKeyword */:
+ case 90 /* DoKeyword */:
+ case 115 /* WhileKeyword */:
+ case 97 /* ForKeyword */:
+ case 86 /* ContinueKeyword */:
+ case 81 /* BreakKeyword */:
+ case 105 /* ReturnKeyword */:
+ case 116 /* WithKeyword */:
+ case 107 /* SwitchKeyword */:
+ case 109 /* ThrowKeyword */:
+ case 111 /* TryKeyword */:
+ case 87 /* 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.
+ // falls through
+ case 83 /* CatchKeyword */:
+ case 96 /* FinallyKeyword */:
+ return true;
+ case 100 /* ImportKeyword */:
+ return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
+ case 85 /* ConstKeyword */:
+ case 93 /* ExportKeyword */:
+ return isStartOfDeclaration();
+ case 131 /* AsyncKeyword */:
+ case 135 /* DeclareKeyword */:
+ case 118 /* InterfaceKeyword */:
+ case 141 /* ModuleKeyword */:
+ case 142 /* NamespaceKeyword */:
+ case 151 /* TypeKeyword */:
+ case 156 /* GlobalKeyword */:
+ // When these don't start a declaration, they're an identifier in an expression statement
+ return true;
+ case 123 /* PublicKeyword */:
+ case 121 /* PrivateKeyword */:
+ case 122 /* ProtectedKeyword */:
+ case 124 /* StaticKeyword */:
+ case 144 /* 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();
+ }
+ }
+ function nextTokenIsBindingIdentifierOrStartOfDestructuring() {
+ nextToken();
+ return isBindingIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
+ }
+ function isLetDeclaration() {
+ // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
+ // or [.
+ return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring);
+ }
+ function parseStatement() {
+ switch (token()) {
+ case 26 /* SemicolonToken */:
+ return parseEmptyStatement();
+ case 18 /* OpenBraceToken */:
+ return parseBlock(/*ignoreMissingOpenBrace*/ false);
+ case 113 /* VarKeyword */:
+ return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
+ case 119 /* LetKeyword */:
+ if (isLetDeclaration()) {
+ return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
+ }
+ break;
+ case 98 /* FunctionKeyword */:
+ return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
+ case 84 /* ClassKeyword */:
+ return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
+ case 99 /* IfKeyword */:
+ return parseIfStatement();
+ case 90 /* DoKeyword */:
+ return parseDoStatement();
+ case 115 /* WhileKeyword */:
+ return parseWhileStatement();
+ case 97 /* ForKeyword */:
+ return parseForOrForInOrForOfStatement();
+ case 86 /* ContinueKeyword */:
+ return parseBreakOrContinueStatement(244 /* ContinueStatement */);
+ case 81 /* BreakKeyword */:
+ return parseBreakOrContinueStatement(245 /* BreakStatement */);
+ case 105 /* ReturnKeyword */:
+ return parseReturnStatement();
+ case 116 /* WithKeyword */:
+ return parseWithStatement();
+ case 107 /* SwitchKeyword */:
+ return parseSwitchStatement();
+ case 109 /* ThrowKeyword */:
+ return parseThrowStatement();
+ case 111 /* TryKeyword */:
+ // Include 'catch' and 'finally' for error recovery.
+ // falls through
+ case 83 /* CatchKeyword */:
+ case 96 /* FinallyKeyword */:
+ return parseTryStatement();
+ case 87 /* DebuggerKeyword */:
+ return parseDebuggerStatement();
+ case 59 /* AtToken */:
+ return parseDeclaration();
+ case 131 /* AsyncKeyword */:
+ case 118 /* InterfaceKeyword */:
+ case 151 /* TypeKeyword */:
+ case 141 /* ModuleKeyword */:
+ case 142 /* NamespaceKeyword */:
+ case 135 /* DeclareKeyword */:
+ case 85 /* ConstKeyword */:
+ case 92 /* EnumKeyword */:
+ case 93 /* ExportKeyword */:
+ case 100 /* ImportKeyword */:
+ case 121 /* PrivateKeyword */:
+ case 122 /* ProtectedKeyword */:
+ case 123 /* PublicKeyword */:
+ case 126 /* AbstractKeyword */:
+ case 124 /* StaticKeyword */:
+ case 144 /* ReadonlyKeyword */:
+ case 156 /* GlobalKeyword */:
+ if (isStartOfDeclaration()) {
+ return parseDeclaration();
+ }
+ break;
+ }
+ return parseExpressionOrLabeledStatement();
+ }
+ function isDeclareModifier(modifier) {
+ return modifier.kind === 135 /* DeclareKeyword */;
+ }
+ function parseDeclaration() {
+ // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
+ // if we can't reuse the declaration, so that we don't do this work twice?
+ //
+ // `parseListElement` attempted to get the reused node at this position,
+ // but the ambient context flag was not yet set, so the node appeared
+ // not reusable in that context.
+ var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier);
+ if (isAmbient) {
+ var node = tryReuseAmbientDeclaration();
+ if (node) {
+ return node;
+ }
+ }
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var decorators = parseDecorators();
+ var modifiers = parseModifiers();
+ if (isAmbient) {
+ for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
+ var m = _a[_i];
+ m.flags |= 8388608 /* Ambient */;
+ }
+ return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); });
+ }
+ else {
+ return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers);
+ }
+ }
+ function tryReuseAmbientDeclaration() {
+ return doInsideOfContext(8388608 /* Ambient */, function () {
+ var node = currentNode(parsingContext);
+ if (node) {
+ return consumeNode(node);
+ }
+ });
+ }
+ function parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers) {
+ switch (token()) {
+ case 113 /* VarKeyword */:
+ case 119 /* LetKeyword */:
+ case 85 /* ConstKeyword */:
+ return parseVariableStatement(pos, hasJSDoc, decorators, modifiers);
+ case 98 /* FunctionKeyword */:
+ return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 84 /* ClassKeyword */:
+ return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 118 /* InterfaceKeyword */:
+ return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 151 /* TypeKeyword */:
+ return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 92 /* EnumKeyword */:
+ return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 156 /* GlobalKeyword */:
+ case 141 /* ModuleKeyword */:
+ case 142 /* NamespaceKeyword */:
+ return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 100 /* ImportKeyword */:
+ return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers);
+ case 93 /* ExportKeyword */:
+ nextToken();
+ switch (token()) {
+ case 88 /* DefaultKeyword */:
+ case 63 /* EqualsToken */:
+ return parseExportAssignment(pos, hasJSDoc, decorators, modifiers);
+ case 127 /* AsKeyword */:
+ return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers);
+ default:
+ return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers);
+ }
+ default:
+ if (decorators || modifiers) {
+ // 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(275 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
+ ts.setTextRangePos(missing, pos);
+ missing.decorators = decorators;
+ missing.modifiers = modifiers;
+ return missing;
+ }
+ return undefined; // TODO: GH#18217
+ }
+ }
+ function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
+ nextToken();
+ return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
+ }
+ function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
+ if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
+ parseSemicolon();
+ return;
+ }
+ return parseFunctionBlock(flags, diagnosticMessage);
+ }
+ // DECLARATIONS
+ function parseArrayBindingElement() {
+ var pos = getNodePos();
+ if (token() === 27 /* CommaToken */) {
+ return finishNode(factory.createOmittedExpression(), pos);
+ }
+ var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
+ var name = parseIdentifierOrPattern();
+ var initializer = parseInitializer();
+ return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos);
+ }
+ function parseObjectBindingElement() {
+ var pos = getNodePos();
+ var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
+ var tokenIsIdentifier = isBindingIdentifier();
+ var propertyName = parsePropertyName();
+ var name;
+ if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
+ name = propertyName;
+ propertyName = undefined;
+ }
+ else {
+ parseExpected(58 /* ColonToken */);
+ name = parseIdentifierOrPattern();
+ }
+ var initializer = parseInitializer();
+ return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
+ }
+ function parseObjectBindingPattern() {
+ var pos = getNodePos();
+ parseExpected(18 /* OpenBraceToken */);
+ var elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
+ parseExpected(19 /* CloseBraceToken */);
+ return finishNode(factory.createObjectBindingPattern(elements), pos);
+ }
+ function parseArrayBindingPattern() {
+ var pos = getNodePos();
+ parseExpected(22 /* OpenBracketToken */);
+ var elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
+ parseExpected(23 /* CloseBracketToken */);
+ return finishNode(factory.createArrayBindingPattern(elements), pos);
+ }
+ function isBindingIdentifierOrPrivateIdentifierOrPattern() {
+ return token() === 18 /* OpenBraceToken */
+ || token() === 22 /* OpenBracketToken */
+ || token() === 80 /* PrivateIdentifier */
+ || isBindingIdentifier();
+ }
+ function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
+ if (token() === 22 /* OpenBracketToken */) {
+ return parseArrayBindingPattern();
+ }
+ if (token() === 18 /* OpenBraceToken */) {
+ return parseObjectBindingPattern();
+ }
+ return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
+ }
+ function parseVariableDeclarationAllowExclamation() {
+ return parseVariableDeclaration(/*allowExclamation*/ true);
+ }
+ function parseVariableDeclaration(allowExclamation) {
+ var pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
+ var exclamationToken;
+ if (allowExclamation && name.kind === 79 /* Identifier */ &&
+ token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
+ exclamationToken = parseTokenNode();
+ }
+ var type = parseTypeAnnotation();
+ var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
+ var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseVariableDeclarationList(inForStatementInitializer) {
+ var pos = getNodePos();
+ var flags = 0;
+ switch (token()) {
+ case 113 /* VarKeyword */:
+ break;
+ case 119 /* LetKeyword */:
+ flags |= 1 /* Let */;
+ break;
+ case 85 /* ConstKeyword */:
+ flags |= 2 /* Const */;
+ break;
+ default:
+ ts.Debug.fail();
+ }
+ nextToken();
+ // 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.
+ var declarations;
+ if (token() === 159 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
+ declarations = createMissingList();
+ }
+ else {
+ var savedDisallowIn = inDisallowInContext();
+ setDisallowInContext(inForStatementInitializer);
+ declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
+ setDisallowInContext(savedDisallowIn);
+ }
+ return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
+ }
+ function canFollowContextualOfKeyword() {
+ return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
+ }
+ function parseVariableStatement(pos, hasJSDoc, decorators, modifiers) {
+ var declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
+ parseSemicolon();
+ var node = factory.createVariableStatement(modifiers, declarationList);
+ // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker.
+ node.decorators = decorators;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ var savedAwaitContext = inAwaitContext();
+ var modifierFlags = ts.modifiersToFlags(modifiers);
+ parseExpected(98 /* FunctionKeyword */);
+ var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
+ // We don't parse the name here in await context, instead we will report a grammar error in the checker.
+ var name = modifierFlags & 512 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
+ var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
+ var isAsync = modifierFlags & 256 /* Async */ ? 2 /* Await */ : 0 /* None */;
+ var typeParameters = parseTypeParameters();
+ if (modifierFlags & 1 /* Export */)
+ setAwaitContext(/*value*/ true);
+ var parameters = parseParameters(isGenerator | isAsync);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
+ setAwaitContext(savedAwaitContext);
+ var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseConstructorName() {
+ if (token() === 134 /* ConstructorKeyword */) {
+ return parseExpected(134 /* ConstructorKeyword */);
+ }
+ if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
+ return tryParse(function () {
+ var literalNode = parseLiteralNode();
+ return literalNode.text === "constructor" ? literalNode : undefined;
+ });
+ }
+ }
+ function tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ return tryParse(function () {
+ if (parseConstructorName()) {
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(0 /* None */);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ var body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
+ var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body);
+ // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker.
+ node.typeParameters = typeParameters;
+ node.type = type;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ });
+ }
+ function parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
+ var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
+ var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(isGenerator | isAsync);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
+ var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body);
+ // An exclamation token on a method is invalid syntax and will be handled by the grammar checker
+ node.exclamationToken = exclamationToken;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken) {
+ var exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */) : undefined;
+ var type = parseTypeAnnotation();
+ var initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
+ parseSemicolonAfterPropertyName(name, type, initializer);
+ var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
+ var name = parsePropertyName();
+ // Note: this is not legal as per the grammar. But we allow it in the parser and
+ // report an error in the grammar checker.
+ var questionToken = parseOptionalToken(57 /* QuestionToken */);
+ if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
+ return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, ts.Diagnostics.or_expected);
+ }
+ return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
+ }
+ function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) {
+ var name = parsePropertyName();
+ var typeParameters = parseTypeParameters();
+ var parameters = parseParameters(0 /* None */);
+ var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
+ var body = parseFunctionBlockOrSemicolon(0 /* None */);
+ var node = kind === 171 /* GetAccessor */
+ ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body)
+ : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body);
+ // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
+ node.typeParameters = typeParameters;
+ if (type && node.kind === 172 /* SetAccessor */)
+ node.type = type;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function isClassMemberStart() {
+ var idToken;
+ if (token() === 59 /* 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() === 41 /* 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();
+ }
+ // Index signatures and computed properties are class members; we can parse.
+ if (token() === 22 /* OpenBracketToken */) {
+ return true;
+ }
+ // If we were able to get any potential identifier...
+ if (idToken !== undefined) {
+ // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
+ if (!ts.isKeyword(idToken) || idToken === 148 /* SetKeyword */ || idToken === 136 /* 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 20 /* OpenParenToken */: // Method declaration
+ case 29 /* LessThanToken */: // Generic Method declaration
+ case 53 /* ExclamationToken */: // Non-null assertion on property name
+ case 58 /* ColonToken */: // Type Annotation for declaration
+ case 63 /* EqualsToken */: // Initializer for declaration
+ case 57 /* 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();
+ }
+ }
+ return false;
}
- ]);
- /* @internal */
- ts.typeAcquisitionDeclarations = [
- {
- /* @deprecated typingOptions.enableAutoDiscovery
- * Use typeAcquisition.enable instead.
- */
- name: "enableAutoDiscovery",
- type: "boolean",
- },
- {
- name: "enable",
- type: "boolean",
- },
- {
- name: "include",
- type: "list",
- element: {
- name: "include",
- type: "string"
+ function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ parseExpectedToken(124 /* StaticKeyword */);
+ var body = parseClassStaticBlockBody();
+ return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc);
+ }
+ function parseClassStaticBlockBody() {
+ var savedYieldContext = inYieldContext();
+ var savedAwaitContext = inAwaitContext();
+ setYieldContext(false);
+ setAwaitContext(true);
+ var body = parseBlock(/*ignoreMissingOpenBrace*/ false);
+ setYieldContext(savedYieldContext);
+ setAwaitContext(savedAwaitContext);
+ return body;
+ }
+ function parseDecoratorExpression() {
+ if (inAwaitContext() && token() === 132 /* AwaitKeyword */) {
+ // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails
+ // This simply parses the missing identifier and moves on.
+ var pos = getNodePos();
+ var awaitExpression = parseIdentifier(ts.Diagnostics.Expression_expected);
+ nextToken();
+ var memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true);
+ return parseCallExpressionRest(pos, memberExpression);
}
- },
- {
- name: "exclude",
- type: "list",
- element: {
- name: "exclude",
- type: "string"
+ return parseLeftHandSideExpressionOrHigher();
+ }
+ function tryParseDecorator() {
+ var pos = getNodePos();
+ if (!parseOptional(59 /* AtToken */)) {
+ return undefined;
}
+ var expression = doInDecoratorContext(parseDecoratorExpression);
+ return finishNode(factory.createDecorator(expression), pos);
}
- ];
- /*@internal*/
- function createOptionNameMap(optionDeclarations) {
- var optionsNameMap = ts.createMap();
- var shortOptionNames = ts.createMap();
- ts.forEach(optionDeclarations, function (option) {
- optionsNameMap.set(option.name.toLowerCase(), option);
- if (option.shortName) {
- shortOptionNames.set(option.shortName, option.name);
+ function parseDecorators() {
+ var pos = getNodePos();
+ var list, decorator;
+ while (decorator = tryParseDecorator()) {
+ list = ts.append(list, decorator);
+ }
+ return list && createNodeArray(list, pos);
+ }
+ function tryParseModifier(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) {
+ var pos = getNodePos();
+ var kind = token();
+ if (token() === 85 /* 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)) {
+ return undefined;
+ }
+ }
+ else if (stopOnStartOfClassStaticBlock && token() === 124 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) {
+ return undefined;
+ }
+ else if (hasSeenStaticModifier && token() === 124 /* StaticKeyword */) {
+ return undefined;
+ }
+ else {
+ if (!parseAnyContextualModifier()) {
+ return undefined;
+ }
+ }
+ return finishNode(factory.createToken(kind), pos);
+ }
+ /*
+ * 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, stopOnStartOfClassStaticBlock) {
+ var pos = getNodePos();
+ var list, modifier, hasSeenStatic = false;
+ while (modifier = tryParseModifier(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock, hasSeenStatic)) {
+ if (modifier.kind === 124 /* StaticKeyword */)
+ hasSeenStatic = true;
+ list = ts.append(list, modifier);
+ }
+ return list && createNodeArray(list, pos);
+ }
+ function parseModifiersForArrowFunction() {
+ var modifiers;
+ if (token() === 131 /* AsyncKeyword */) {
+ var pos = getNodePos();
+ nextToken();
+ var modifier = finishNode(factory.createToken(131 /* AsyncKeyword */), pos);
+ modifiers = createNodeArray([modifier], pos);
+ }
+ return modifiers;
+ }
+ function parseClassElement() {
+ var pos = getNodePos();
+ if (token() === 26 /* SemicolonToken */) {
+ nextToken();
+ return finishNode(factory.createSemicolonClassElement(), pos);
+ }
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var decorators = parseDecorators();
+ var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true, /*stopOnStartOfClassStaticBlock*/ true);
+ if (token() === 124 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) {
+ return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers);
+ }
+ if (parseContextualModifier(136 /* GetKeyword */)) {
+ return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 171 /* GetAccessor */);
+ }
+ if (parseContextualModifier(148 /* SetKeyword */)) {
+ return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SetAccessor */);
+ }
+ if (token() === 134 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
+ var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers);
+ if (constructorDeclaration) {
+ return constructorDeclaration;
+ }
+ }
+ if (isIndexSignature()) {
+ return parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers);
+ }
+ // 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() === 10 /* StringLiteral */ ||
+ token() === 8 /* NumericLiteral */ ||
+ token() === 41 /* AsteriskToken */ ||
+ token() === 22 /* OpenBracketToken */) {
+ var isAmbient = ts.some(modifiers, isDeclareModifier);
+ if (isAmbient) {
+ for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
+ var m = _a[_i];
+ m.flags |= 8388608 /* Ambient */;
+ }
+ return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); });
+ }
+ else {
+ return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers);
+ }
+ }
+ if (decorators || modifiers) {
+ // treat this as a property declaration with a missing name.
+ var name = createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
+ return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, /*questionToken*/ undefined);
+ }
+ // '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(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 225 /* ClassExpression */);
+ }
+ function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 256 /* ClassDeclaration */);
+ }
+ function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) {
+ var savedAwaitContext = inAwaitContext();
+ parseExpected(84 /* ClassKeyword */);
+ // We don't parse the name here in await context, instead we will report a grammar error in the checker.
+ var name = parseNameOfClassDeclarationOrExpression();
+ var typeParameters = parseTypeParameters();
+ if (ts.some(modifiers, ts.isExportModifier))
+ setAwaitContext(/*value*/ true);
+ var heritageClauses = parseHeritageClauses();
+ var members;
+ if (parseExpected(18 /* OpenBraceToken */)) {
+ // ClassTail[Yield,Await] : (Modified) See 14.5
+ // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
+ members = parseClassMembers();
+ parseExpected(19 /* CloseBraceToken */);
+ }
+ else {
+ members = createMissingList();
+ }
+ setAwaitContext(savedAwaitContext);
+ var node = kind === 256 /* ClassDeclaration */
+ ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members)
+ : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ 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 isBindingIdentifier() && !isImplementsClause()
+ ? createIdentifier(isBindingIdentifier())
+ : undefined;
+ }
+ function isImplementsClause() {
+ return token() === 117 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
+ }
+ function parseHeritageClauses() {
+ // ClassTail[Yield,Await] : (Modified) See 14.5
+ // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
+ if (isHeritageClause()) {
+ return parseList(22 /* HeritageClauses */, parseHeritageClause);
+ }
+ return undefined;
+ }
+ function parseHeritageClause() {
+ var pos = getNodePos();
+ var tok = token();
+ ts.Debug.assert(tok === 94 /* ExtendsKeyword */ || tok === 117 /* ImplementsKeyword */); // isListElement() should ensure this.
+ nextToken();
+ var types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
+ return finishNode(factory.createHeritageClause(tok, types), pos);
+ }
+ function parseExpressionWithTypeArguments() {
+ var pos = getNodePos();
+ var expression = parseLeftHandSideExpressionOrHigher();
+ var typeArguments = tryParseTypeArguments();
+ return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
+ }
+ function tryParseTypeArguments() {
+ return token() === 29 /* LessThanToken */ ?
+ parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
+ }
+ function isHeritageClause() {
+ return token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */;
+ }
+ function parseClassMembers() {
+ return parseList(5 /* ClassMembers */, parseClassElement);
+ }
+ function parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ parseExpected(118 /* InterfaceKeyword */);
+ var name = parseIdentifier();
+ var typeParameters = parseTypeParameters();
+ var heritageClauses = parseHeritageClauses();
+ var members = parseObjectTypeMembers();
+ var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ parseExpected(151 /* TypeKeyword */);
+ var name = parseIdentifier();
+ var typeParameters = parseTypeParameters();
+ parseExpected(63 /* EqualsToken */);
+ var type = token() === 138 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType();
+ parseSemicolon();
+ var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ // 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 pos = getNodePos();
+ var hasJSDoc = hasPrecedingJSDocComment();
+ var name = parsePropertyName();
+ var initializer = allowInAnd(parseInitializer);
+ return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc);
+ }
+ function parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ parseExpected(92 /* EnumKeyword */);
+ var name = parseIdentifier();
+ var members;
+ if (parseExpected(18 /* OpenBraceToken */)) {
+ members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
+ parseExpected(19 /* CloseBraceToken */);
+ }
+ else {
+ members = createMissingList();
+ }
+ var node = factory.createEnumDeclaration(decorators, modifiers, name, members);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseModuleBlock() {
+ var pos = getNodePos();
+ var statements;
+ if (parseExpected(18 /* OpenBraceToken */)) {
+ statements = parseList(1 /* BlockStatements */, parseStatement);
+ parseExpected(19 /* CloseBraceToken */);
+ }
+ else {
+ statements = createMissingList();
+ }
+ return finishNode(factory.createModuleBlock(statements), pos);
+ }
+ function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags) {
+ // 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 */;
+ var name = parseIdentifier();
+ var body = parseOptional(24 /* DotToken */)
+ ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag)
+ : parseModuleBlock();
+ var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ var flags = 0;
+ var name;
+ if (token() === 156 /* GlobalKeyword */) {
+ // parse 'global' as name of global scope augmentation
+ name = parseIdentifier();
+ flags |= 1024 /* GlobalAugmentation */;
+ }
+ else {
+ name = parseLiteralNode();
+ name.text = internIdentifier(name.text);
+ }
+ var body;
+ if (token() === 18 /* OpenBraceToken */) {
+ body = parseModuleBlock();
+ }
+ else {
+ parseSemicolon();
+ }
+ var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ var flags = 0;
+ if (token() === 156 /* GlobalKeyword */) {
+ // global augmentation
+ return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
+ }
+ else if (parseOptional(142 /* NamespaceKeyword */)) {
+ flags |= 16 /* Namespace */;
+ }
+ else {
+ parseExpected(141 /* ModuleKeyword */);
+ if (token() === 10 /* StringLiteral */) {
+ return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
+ }
+ }
+ return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags);
+ }
+ function isExternalModuleReference() {
+ return token() === 145 /* RequireKeyword */ &&
+ lookAhead(nextTokenIsOpenParen);
+ }
+ function nextTokenIsOpenParen() {
+ return nextToken() === 20 /* OpenParenToken */;
+ }
+ function nextTokenIsOpenBrace() {
+ return nextToken() === 18 /* OpenBraceToken */;
+ }
+ function nextTokenIsSlash() {
+ return nextToken() === 43 /* SlashToken */;
+ }
+ function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ parseExpected(127 /* AsKeyword */);
+ parseExpected(142 /* NamespaceKeyword */);
+ var name = parseIdentifier();
+ parseSemicolon();
+ var node = factory.createNamespaceExportDeclaration(name);
+ // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker
+ node.decorators = decorators;
+ node.modifiers = modifiers;
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ parseExpected(100 /* ImportKeyword */);
+ var afterImportPos = scanner.getStartPos();
+ // We don't parse the identifier here in await context, instead we will report a grammar error in the checker.
+ var identifier;
+ if (isIdentifier()) {
+ identifier = parseIdentifier();
+ }
+ var isTypeOnly = false;
+ if (token() !== 155 /* FromKeyword */ &&
+ (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
+ (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
+ isTypeOnly = true;
+ identifier = isIdentifier() ? parseIdentifier() : undefined;
+ }
+ if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
+ return parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly);
+ }
+ // ImportDeclaration:
+ // import ImportClause from ModuleSpecifier ;
+ // import ModuleSpecifier;
+ var importClause;
+ if (identifier || // import id
+ token() === 41 /* AsteriskToken */ || // import *
+ token() === 18 /* OpenBraceToken */ // import {
+ ) {
+ importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
+ parseExpected(155 /* FromKeyword */);
+ }
+ var moduleSpecifier = parseModuleSpecifier();
+ var assertClause;
+ if (token() === 129 /* AssertKeyword */ && !scanner.hasPrecedingLineBreak()) {
+ assertClause = parseAssertClause();
+ }
+ parseSemicolon();
+ var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseAssertEntry() {
+ var pos = getNodePos();
+ var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* StringLiteral */);
+ parseExpected(58 /* ColonToken */);
+ var value = parseLiteralLikeNode(10 /* StringLiteral */);
+ return finishNode(factory.createAssertEntry(name, value), pos);
+ }
+ function parseAssertClause() {
+ var pos = getNodePos();
+ parseExpected(129 /* AssertKeyword */);
+ var openBracePosition = scanner.getTokenPos();
+ if (parseExpected(18 /* OpenBraceToken */)) {
+ var multiLine = scanner.hasPrecedingLineBreak();
+ var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true);
+ if (!parseExpected(19 /* CloseBraceToken */)) {
+ var lastError = ts.lastOrUndefined(parseDiagnostics);
+ if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
+ ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
+ }
+ }
+ return finishNode(factory.createAssertClause(elements, multiLine), pos);
+ }
+ else {
+ var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false);
+ return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos);
+ }
+ }
+ function tokenAfterImportDefinitelyProducesImportDeclaration() {
+ return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
+ }
+ function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
+ // In `import id ___`, the current token decides whether to produce
+ // an ImportDeclaration or ImportEqualsDeclaration.
+ return token() === 27 /* CommaToken */ || token() === 155 /* FromKeyword */;
+ }
+ function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) {
+ parseExpected(63 /* EqualsToken */);
+ var moduleReference = parseModuleReference();
+ parseSemicolon();
+ var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference);
+ var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
+ return finished;
+ }
+ function parseImportClause(identifier, pos, isTypeOnly) {
+ // ImportClause:
+ // ImportedDefaultBinding
+ // NameSpaceImport
+ // NamedImports
+ // ImportedDefaultBinding, NameSpaceImport
+ // ImportedDefaultBinding, NamedImports
+ // If there was no default import or if there is comma token after default import
+ // parse namespace or named imports
+ var namedBindings;
+ if (!identifier ||
+ parseOptional(27 /* CommaToken */)) {
+ namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(268 /* NamedImports */);
+ }
+ return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos);
+ }
+ function parseModuleReference() {
+ return isExternalModuleReference()
+ ? parseExternalModuleReference()
+ : parseEntityName(/*allowReservedWords*/ false);
+ }
+ function parseExternalModuleReference() {
+ var pos = getNodePos();
+ parseExpected(145 /* RequireKeyword */);
+ parseExpected(20 /* OpenParenToken */);
+ var expression = parseModuleSpecifier();
+ parseExpected(21 /* CloseParenToken */);
+ return finishNode(factory.createExternalModuleReference(expression), pos);
+ }
+ function parseModuleSpecifier() {
+ if (token() === 10 /* 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() {
+ // NameSpaceImport:
+ // * as ImportedBinding
+ var pos = getNodePos();
+ parseExpected(41 /* AsteriskToken */);
+ parseExpected(127 /* AsKeyword */);
+ var name = parseIdentifier();
+ return finishNode(factory.createNamespaceImport(name), pos);
+ }
+ function parseNamedImportsOrExports(kind) {
+ var pos = getNodePos();
+ // NamedImports:
+ // { }
+ // { ImportsList }
+ // { ImportsList, }
+ // ImportsList:
+ // ImportSpecifier
+ // ImportsList, ImportSpecifier
+ var node = kind === 268 /* NamedImports */
+ ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */))
+ : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */));
+ return finishNode(node, pos);
+ }
+ function parseExportSpecifier() {
+ return parseImportOrExportSpecifier(274 /* ExportSpecifier */);
+ }
+ function parseImportSpecifier() {
+ return parseImportOrExportSpecifier(269 /* ImportSpecifier */);
+ }
+ function parseImportOrExportSpecifier(kind) {
+ var pos = getNodePos();
+ // 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 isTypeOnly = false;
+ var propertyName;
+ var canParseAsKeyword = true;
+ var name = parseIdentifierName();
+ if (name.escapedText === "type") {
+ // If the first token of an import specifier is 'type', there are a lot of possibilities,
+ // especially if we see 'as' afterwards:
+ //
+ // import { type } from "mod"; - isTypeOnly: false, name: type
+ // import { type as } from "mod"; - isTypeOnly: true, name: as
+ // import { type as as } from "mod"; - isTypeOnly: false, name: as, propertyName: type
+ // import { type as as as } from "mod"; - isTypeOnly: true, name: as, propertyName: as
+ if (token() === 127 /* AsKeyword */) {
+ // { type as ...? }
+ var firstAs = parseIdentifierName();
+ if (token() === 127 /* AsKeyword */) {
+ // { type as as ...? }
+ var secondAs = parseIdentifierName();
+ if (ts.tokenIsIdentifierOrKeyword(token())) {
+ // { type as as something }
+ isTypeOnly = true;
+ propertyName = firstAs;
+ name = parseNameWithKeywordCheck();
+ canParseAsKeyword = false;
+ }
+ else {
+ // { type as as }
+ propertyName = name;
+ name = secondAs;
+ canParseAsKeyword = false;
+ }
+ }
+ else if (ts.tokenIsIdentifierOrKeyword(token())) {
+ // { type as something }
+ propertyName = name;
+ canParseAsKeyword = false;
+ name = parseNameWithKeywordCheck();
+ }
+ else {
+ // { type as }
+ isTypeOnly = true;
+ name = firstAs;
+ }
+ }
+ else if (ts.tokenIsIdentifierOrKeyword(token())) {
+ // { type something ...? }
+ isTypeOnly = true;
+ name = parseNameWithKeywordCheck();
+ }
+ }
+ if (canParseAsKeyword && token() === 127 /* AsKeyword */) {
+ propertyName = name;
+ parseExpected(127 /* AsKeyword */);
+ name = parseNameWithKeywordCheck();
+ }
+ if (kind === 269 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
+ parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
+ }
+ var node = kind === 269 /* ImportSpecifier */
+ ? factory.createImportSpecifier(isTypeOnly, propertyName, name)
+ : factory.createExportSpecifier(isTypeOnly, propertyName, name);
+ return finishNode(node, pos);
+ function parseNameWithKeywordCheck() {
+ checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
+ checkIdentifierStart = scanner.getTokenPos();
+ checkIdentifierEnd = scanner.getTextPos();
+ return parseIdentifierName();
+ }
+ }
+ function parseNamespaceExport(pos) {
+ return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos);
+ }
+ function parseExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
+ var savedAwaitContext = inAwaitContext();
+ setAwaitContext(/*value*/ true);
+ var exportClause;
+ var moduleSpecifier;
+ var assertClause;
+ var isTypeOnly = parseOptional(151 /* TypeKeyword */);
+ var namespaceExportPos = getNodePos();
+ if (parseOptional(41 /* AsteriskToken */)) {
+ if (parseOptional(127 /* AsKeyword */)) {
+ exportClause = parseNamespaceExport(namespaceExportPos);
+ }
+ parseExpected(155 /* FromKeyword */);
+ moduleSpecifier = parseModuleSpecifier();
+ }
+ else {
+ exportClause = parseNamedImportsOrExports(272 /* 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() === 155 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
+ parseExpected(155 /* FromKeyword */);
+ moduleSpecifier = parseModuleSpecifier();
+ }
+ }
+ if (moduleSpecifier && token() === 129 /* AssertKeyword */ && !scanner.hasPrecedingLineBreak()) {
+ assertClause = parseAssertClause();
+ }
+ parseSemicolon();
+ setAwaitContext(savedAwaitContext);
+ var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) {
+ var savedAwaitContext = inAwaitContext();
+ setAwaitContext(/*value*/ true);
+ var isExportEquals;
+ if (parseOptional(63 /* EqualsToken */)) {
+ isExportEquals = true;
+ }
+ else {
+ parseExpected(88 /* DefaultKeyword */);
+ }
+ var expression = parseAssignmentExpressionOrHigher();
+ parseSemicolon();
+ setAwaitContext(savedAwaitContext);
+ var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression);
+ return withJSDoc(finishNode(node, pos), hasJSDoc);
+ }
+ 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 hasModifierOfKind(node, 93 /* ExportKeyword */)
+ || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
+ || ts.isImportDeclaration(node)
+ || ts.isExportAssignment(node)
+ || ts.isExportDeclaration(node) ? node : undefined;
+ }
+ function getImportMetaIfNecessary(sourceFile) {
+ return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
+ walkTreeForExternalModuleIndicators(sourceFile) :
+ undefined;
+ }
+ function walkTreeForExternalModuleIndicators(node) {
+ return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
+ }
+ /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
+ function hasModifierOfKind(node, kind) {
+ return ts.some(node.modifiers, function (m) { return m.kind === kind; });
+ }
+ function isImportMeta(node) {
+ return ts.isMetaProperty(node) && node.keywordToken === 100 /* ImportKeyword */ && node.name.escapedText === "meta";
+ }
+ var ParsingContext;
+ (function (ParsingContext) {
+ ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
+ ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
+ ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
+ ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
+ ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
+ ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
+ ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
+ ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
+ ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
+ ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
+ ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
+ ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
+ ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
+ ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
+ ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
+ ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
+ ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
+ ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
+ ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
+ ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
+ ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
+ ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
+ ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
+ ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
+ ParsingContext[ParsingContext["AssertEntries"] = 24] = "AssertEntries";
+ ParsingContext[ParsingContext["Count"] = 25] = "Count"; // Number of parsing contexts
+ })(ParsingContext || (ParsingContext = {}));
+ var Tristate;
+ (function (Tristate) {
+ Tristate[Tristate["False"] = 0] = "False";
+ Tristate[Tristate["True"] = 1] = "True";
+ Tristate[Tristate["Unknown"] = 2] = "Unknown";
+ })(Tristate || (Tristate = {}));
+ var JSDocParser;
+ (function (JSDocParser) {
+ function parseJSDocTypeExpressionForTests(content, start, length) {
+ initializeState("file.js", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ scanner.setText(content, start, length);
+ currentToken = scanner.scan();
+ var jsDocTypeExpression = parseJSDocTypeExpression();
+ var sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false, [], factory.createToken(1 /* EndOfFileToken */), 0 /* None */);
+ var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
+ if (jsDocDiagnostics) {
+ sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
+ }
+ clearState();
+ return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
+ }
+ JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
+ // Parses out a JSDoc type expression.
+ function parseJSDocTypeExpression(mayOmitBraces) {
+ var pos = getNodePos();
+ var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
+ var type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
+ if (!mayOmitBraces || hasBrace) {
+ parseExpectedJSDoc(19 /* CloseBraceToken */);
+ }
+ var result = factory.createJSDocTypeExpression(type);
+ fixupParentReferences(result);
+ return finishNode(result, pos);
+ }
+ JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
+ function parseJSDocNameReference() {
+ var pos = getNodePos();
+ var hasBrace = parseOptional(18 /* OpenBraceToken */);
+ var p2 = getNodePos();
+ var entityName = parseEntityName(/* allowReservedWords*/ false);
+ while (token() === 80 /* PrivateIdentifier */) {
+ reScanHashToken(); // rescan #id as # id
+ nextTokenJSDoc(); // then skip the #
+ entityName = finishNode(factory.createJSDocMemberName(entityName, parseIdentifier()), p2);
+ }
+ if (hasBrace) {
+ parseExpectedJSDoc(19 /* CloseBraceToken */);
+ }
+ var result = factory.createJSDocNameReference(entityName);
+ fixupParentReferences(result);
+ return finishNode(result, pos);
+ }
+ JSDocParser.parseJSDocNameReference = parseJSDocNameReference;
+ function parseIsolatedJSDocComment(content, start, length) {
+ initializeState("", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
+ var sourceFile = { languageVariant: 0 /* Standard */, text: content };
+ var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
+ clearState();
+ return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
+ }
+ JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
+ function parseJSDocComment(parent, start, length) {
+ var saveToken = currentToken;
+ var saveParseDiagnosticsLength = parseDiagnostics.length;
+ var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
+ var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
+ ts.setParent(comment, parent);
+ if (contextFlags & 131072 /* JavaScriptFile */) {
+ if (!jsDocDiagnostics) {
+ jsDocDiagnostics = [];
+ }
+ jsDocDiagnostics.push.apply(jsDocDiagnostics, parseDiagnostics);
+ }
+ currentToken = saveToken;
+ parseDiagnostics.length = saveParseDiagnosticsLength;
+ parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
+ return comment;
}
- });
- return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
- }
- ts.createOptionNameMap = createOptionNameMap;
- var optionsNameMapCache;
- /* @internal */
- function getOptionsNameMap() {
- return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
- }
- ts.getOptionsNameMap = getOptionsNameMap;
- /* @internal */
- ts.defaultInitCompilerOptions = {
- module: ts.ModuleKind.CommonJS,
- target: 1 /* ES5 */,
- strict: true,
- esModuleInterop: true,
- forceConsistentCasingInFileNames: true,
- skipLibCheck: true
- };
- /* @internal */
- function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
- // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
- if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
- return {
- enable: typeAcquisition.enableAutoDiscovery,
- include: typeAcquisition.include || [],
- exclude: typeAcquisition.exclude || []
- };
- }
- return typeAcquisition;
- }
- ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
- /* @internal */
- function createCompilerDiagnosticForInvalidCustomType(opt) {
- return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
- }
- ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
- function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
- 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);
- if (ts.startsWith(value, "-")) {
- return undefined;
- }
- if (value === "") {
- return [];
- }
- var values = value.split(",");
- switch (opt.element.type) {
- case "number":
- return ts.map(values, parseInt);
- case "string":
- return ts.map(values, function (v) { return v || ""; });
- default:
- return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
- }
- }
- ts.parseListTypeOption = parseListTypeOption;
- function getOptionName(option) {
- return option.name;
- }
- function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
- var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
- return possibleOption ?
- createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
- createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
- }
- /*@internal*/
- function parseCommandLineWorker(diagnostics, commandLine, readFile) {
- var options = {};
- var watchOptions;
- var fileNames = [];
- var errors = [];
- parseStrings(commandLine);
- return {
- options: options,
- watchOptions: watchOptions,
- fileNames: fileNames,
- errors: errors
- };
- function parseStrings(args) {
- var i = 0;
- while (i < args.length) {
- var s = args[i];
- i++;
- if (s.charCodeAt(0) === 64 /* at */) {
- parseResponseFile(s.slice(1));
+ JSDocParser.parseJSDocComment = parseJSDocComment;
+ var JSDocState;
+ (function (JSDocState) {
+ JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
+ JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
+ JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
+ JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
+ })(JSDocState || (JSDocState = {}));
+ var PropertyLikeParse;
+ (function (PropertyLikeParse) {
+ PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
+ PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
+ PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
+ })(PropertyLikeParse || (PropertyLikeParse = {}));
+ function parseJSDocCommentWorker(start, length) {
+ if (start === void 0) { start = 0; }
+ var content = sourceText;
+ var end = length === undefined ? content.length : start + length;
+ length = end - start;
+ ts.Debug.assert(start >= 0);
+ ts.Debug.assert(start <= end);
+ ts.Debug.assert(end <= content.length);
+ // Check for /** (JSDoc opening part)
+ if (!isJSDocLikeText(content, start)) {
+ return undefined;
}
- else if (s.charCodeAt(0) === 45 /* minus */) {
- var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
- var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
- if (opt) {
- i = parseOptionValue(args, i, diagnostics, opt, options, errors);
+ var tags;
+ var tagsPos;
+ var tagsEnd;
+ var linkEnd;
+ var commentsPos;
+ var comments = [];
+ var parts = [];
+ // + 3 for leading /**, - 5 in total for /** */
+ return scanner.scanRange(start + 3, length - 5, function () {
+ // 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 '/** '
+ // + 1 because the last index of \n is always one index before the first character in the line and coincidentally, if there is no \n before start, it is -1, which is also one index before the first character
+ var indent = start - (content.lastIndexOf("\n", start) + 1) + 4;
+ function pushComment(text) {
+ if (!margin) {
+ margin = indent;
+ }
+ comments.push(text);
+ indent += text.length;
+ }
+ nextTokenJSDoc();
+ while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
+ ;
+ if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
+ state = 0 /* BeginningOfLine */;
+ indent = 0;
+ }
+ loop: while (true) {
+ switch (token()) {
+ case 59 /* AtToken */:
+ if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
+ removeTrailingWhitespace(comments);
+ if (!commentsPos)
+ commentsPos = getNodePos();
+ addTag(parseTag(indent));
+ // 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;
+ }
+ else {
+ pushComment(scanner.getTokenText());
+ }
+ break;
+ case 4 /* NewLineTrivia */:
+ comments.push(scanner.getTokenText());
+ state = 0 /* BeginningOfLine */;
+ indent = 0;
+ break;
+ case 41 /* AsteriskToken */:
+ var asterisk = scanner.getTokenText();
+ 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 {
+ // Ignore the first asterisk on a line
+ state = 1 /* SawAsterisk */;
+ indent += asterisk.length;
+ }
+ break;
+ 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 /* SavingComments */) {
+ comments.push(whitespace);
+ }
+ else if (margin !== undefined && indent + whitespace.length > margin) {
+ comments.push(whitespace.slice(margin - indent));
+ }
+ indent += whitespace.length;
+ break;
+ case 1 /* EndOfFileToken */:
+ break loop;
+ case 18 /* OpenBraceToken */:
+ state = 2 /* SavingComments */;
+ var commentEnd = scanner.getStartPos();
+ var linkStart = scanner.getTextPos() - 1;
+ var link = parseJSDocLink(linkStart);
+ if (link) {
+ if (!linkEnd) {
+ removeLeadingNewlines(comments);
+ }
+ parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd));
+ parts.push(link);
+ comments = [];
+ linkEnd = scanner.getTextPos();
+ break;
+ }
+ // fallthrough if it's not a {@link sequence
+ default:
+ // 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.
+ state = 2 /* SavingComments */;
+ pushComment(scanner.getTokenText());
+ break;
+ }
+ nextTokenJSDoc();
+ }
+ removeTrailingWhitespace(comments);
+ if (parts.length && comments.length) {
+ parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos));
+ }
+ if (parts.length && tags)
+ ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set");
+ var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
+ return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end);
+ });
+ function removeLeadingNewlines(comments) {
+ while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
+ comments.shift();
+ }
+ }
+ function removeTrailingWhitespace(comments) {
+ while (comments.length && comments[comments.length - 1].trim() === "") {
+ comments.pop();
+ }
+ }
+ function isNextNonwhitespaceTokenEndOfFile() {
+ // We must use infinite lookahead, as there could be any number of newlines :(
+ while (true) {
+ nextTokenJSDoc();
+ if (token() === 1 /* EndOfFileToken */) {
+ return true;
+ }
+ if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
+ return false;
+ }
+ }
+ }
+ function skipWhitespace() {
+ if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
+ if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
+ 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 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
+ nextTokenJSDoc();
+ }
+ }
+ function skipWhitespaceOrAsterisk() {
+ if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
+ if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
+ return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
+ }
+ }
+ var precedingLineBreak = scanner.hasPrecedingLineBreak();
+ var seenLineBreak = false;
+ var indentText = "";
+ while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
+ indentText += scanner.getTokenText();
+ if (token() === 4 /* NewLineTrivia */) {
+ precedingLineBreak = true;
+ seenLineBreak = true;
+ indentText = "";
+ }
+ else if (token() === 41 /* AsteriskToken */) {
+ precedingLineBreak = false;
+ }
+ nextTokenJSDoc();
+ }
+ return seenLineBreak ? indentText : "";
+ }
+ function parseTag(margin) {
+ ts.Debug.assert(token() === 59 /* AtToken */);
+ var start = scanner.getTokenPos();
+ nextTokenJSDoc();
+ var tagName = parseJSDocIdentifierName(/*message*/ undefined);
+ var indentText = skipWhitespaceOrAsterisk();
+ var tag;
+ switch (tagName.escapedText) {
+ case "author":
+ tag = parseAuthorTag(start, tagName, margin, indentText);
+ break;
+ case "implements":
+ tag = parseImplementsTag(start, tagName, margin, indentText);
+ break;
+ case "augments":
+ case "extends":
+ tag = parseAugmentsTag(start, tagName, margin, indentText);
+ break;
+ case "class":
+ case "constructor":
+ tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText);
+ break;
+ case "public":
+ tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText);
+ break;
+ case "private":
+ tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText);
+ break;
+ case "protected":
+ tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText);
+ break;
+ case "readonly":
+ tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText);
+ break;
+ case "override":
+ tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText);
+ break;
+ case "deprecated":
+ hasDeprecatedTag = true;
+ tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText);
+ break;
+ case "this":
+ tag = parseThisTag(start, tagName, margin, indentText);
+ break;
+ case "enum":
+ tag = parseEnumTag(start, tagName, margin, indentText);
+ break;
+ case "arg":
+ case "argument":
+ case "param":
+ return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
+ case "return":
+ case "returns":
+ tag = parseReturnTag(start, tagName, margin, indentText);
+ break;
+ case "template":
+ tag = parseTemplateTag(start, tagName, margin, indentText);
+ break;
+ case "type":
+ tag = parseTypeTag(start, tagName, margin, indentText);
+ break;
+ case "typedef":
+ tag = parseTypedefTag(start, tagName, margin, indentText);
+ break;
+ case "callback":
+ tag = parseCallbackTag(start, tagName, margin, indentText);
+ break;
+ case "see":
+ tag = parseSeeTag(start, tagName, margin, indentText);
+ break;
+ default:
+ tag = parseUnknownTag(start, tagName, margin, indentText);
+ break;
+ }
+ return tag;
+ }
+ function parseTrailingTagComments(pos, end, margin, indentText) {
+ // some tags, like typedef and callback, have already parsed their comments earlier
+ if (!indentText) {
+ margin += end - pos;
+ }
+ return parseTagComments(margin, indentText.slice(margin));
+ }
+ function parseTagComments(indent, initialMargin) {
+ var commentsPos = getNodePos();
+ var comments = [];
+ var parts = [];
+ var linkEnd;
+ var state = 0 /* BeginningOfLine */;
+ var previousWhitespace = true;
+ var margin;
+ function pushComment(text) {
+ if (!margin) {
+ margin = indent;
+ }
+ comments.push(text);
+ indent += text.length;
+ }
+ if (initialMargin !== undefined) {
+ // jump straight to saving comments if there is some initial indentation
+ if (initialMargin !== "") {
+ pushComment(initialMargin);
+ }
+ state = 1 /* SawAsterisk */;
+ }
+ var tok = token();
+ loop: while (true) {
+ switch (tok) {
+ case 4 /* NewLineTrivia */:
+ state = 0 /* BeginningOfLine */;
+ // don't use pushComment here because we want to keep the margin unchanged
+ comments.push(scanner.getTokenText());
+ indent = 0;
+ break;
+ case 59 /* AtToken */:
+ if (state === 3 /* SavingBackticks */
+ || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) {
+ // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace
+ comments.push(scanner.getTokenText());
+ break;
+ }
+ scanner.setTextPos(scanner.getTextPos() - 1);
+ // falls through
+ case 1 /* EndOfFileToken */:
+ // Done
+ break loop;
+ case 5 /* WhitespaceTrivia */:
+ if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
+ 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));
+ }
+ indent += whitespace.length;
+ }
+ break;
+ case 18 /* OpenBraceToken */:
+ state = 2 /* SavingComments */;
+ var commentEnd = scanner.getStartPos();
+ var linkStart = scanner.getTextPos() - 1;
+ var link = parseJSDocLink(linkStart);
+ if (link) {
+ parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd));
+ parts.push(link);
+ comments = [];
+ linkEnd = scanner.getTextPos();
+ }
+ else {
+ pushComment(scanner.getTokenText());
+ }
+ break;
+ case 61 /* BacktickToken */:
+ if (state === 3 /* SavingBackticks */) {
+ state = 2 /* SavingComments */;
+ }
+ else {
+ state = 3 /* SavingBackticks */;
+ }
+ pushComment(scanner.getTokenText());
+ break;
+ case 41 /* 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:
+ if (state !== 3 /* SavingBackticks */) {
+ state = 2 /* SavingComments */; // leading identifiers start recording as well
+ }
+ pushComment(scanner.getTokenText());
+ break;
+ }
+ previousWhitespace = token() === 5 /* WhitespaceTrivia */;
+ tok = nextTokenJSDoc();
+ }
+ removeLeadingNewlines(comments);
+ removeTrailingWhitespace(comments);
+ if (parts.length) {
+ if (comments.length) {
+ parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos));
+ }
+ return createNodeArray(parts, commentsPos, scanner.getTextPos());
+ }
+ else if (comments.length) {
+ return comments.join("");
+ }
+ }
+ function isNextJSDocTokenWhitespace() {
+ var next = nextTokenJSDoc();
+ return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */;
+ }
+ function parseJSDocLink(start) {
+ var linkType = tryParse(parseJSDocLinkPrefix);
+ if (!linkType) {
+ return undefined;
+ }
+ nextTokenJSDoc(); // start at token after link, then skip any whitespace
+ skipWhitespace();
+ // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error
+ var p2 = getNodePos();
+ var name = ts.tokenIsIdentifierOrKeyword(token())
+ ? parseEntityName(/*allowReservedWords*/ true)
+ : undefined;
+ if (name) {
+ while (token() === 80 /* PrivateIdentifier */) {
+ reScanHashToken(); // rescan #id as # id
+ nextTokenJSDoc(); // then skip the #
+ name = finishNode(factory.createJSDocMemberName(name, parseIdentifier()), p2);
+ }
+ }
+ var text = [];
+ while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) {
+ text.push(scanner.getTokenText());
+ nextTokenJSDoc();
+ }
+ var create = linkType === "link" ? factory.createJSDocLink
+ : linkType === "linkcode" ? factory.createJSDocLinkCode
+ : factory.createJSDocLinkPlain;
+ return finishNode(create(name, text.join("")), start, scanner.getTextPos());
+ }
+ function parseJSDocLinkPrefix() {
+ skipWhitespaceOrAsterisk();
+ if (token() === 18 /* OpenBraceToken */
+ && nextTokenJSDoc() === 59 /* AtToken */
+ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc())) {
+ var kind = scanner.getTokenValue();
+ if (kind === "link" || kind === "linkcode" || kind === "linkplain") {
+ return kind;
+ }
+ }
+ }
+ function parseUnknownTag(start, tagName, indent, indentText) {
+ return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
+ }
+ function addTag(tag) {
+ if (!tag) {
+ return;
+ }
+ if (!tags) {
+ tags = [tag];
+ tagsPos = tag.pos;
+ }
+ else {
+ tags.push(tag);
+ }
+ tagsEnd = tag.end;
+ }
+ function tryParseTypeExpression() {
+ skipWhitespaceOrAsterisk();
+ return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
+ }
+ function parseBracketNameInPropertyAndParamTag() {
+ // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
+ var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
+ if (isBracketed) {
+ skipWhitespace();
+ }
+ // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
+ var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
+ var name = parseJSDocEntityName();
+ if (isBackquoted) {
+ parseExpectedTokenJSDoc(61 /* BacktickToken */);
+ }
+ if (isBracketed) {
+ skipWhitespace();
+ // May have an optional default, e.g. '[foo = 42]'
+ if (parseOptionalToken(63 /* EqualsToken */)) {
+ parseExpression();
+ }
+ parseExpected(23 /* CloseBracketToken */);
+ }
+ return { name: name, isBracketed: isBracketed };
+ }
+ function isObjectOrObjectArrayTypeReference(node) {
+ switch (node.kind) {
+ case 147 /* ObjectKeyword */:
+ return true;
+ case 182 /* ArrayType */:
+ return isObjectOrObjectArrayTypeReference(node.elementType);
+ default:
+ return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
+ }
+ }
+ function parseParameterOrPropertyTag(start, tagName, target, indent) {
+ var typeExpression = tryParseTypeExpression();
+ var isNameFirst = !typeExpression;
+ skipWhitespaceOrAsterisk();
+ var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
+ var indentText = skipWhitespaceOrAsterisk();
+ if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) {
+ typeExpression = tryParseTypeExpression();
+ }
+ var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText);
+ var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
+ if (nestedTypeLiteral) {
+ typeExpression = nestedTypeLiteral;
+ isNameFirst = true;
+ }
+ var result = target === 1 /* Property */
+ ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment)
+ : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
+ return finishNode(result, start);
+ }
+ function parseNestedTypeLiteral(typeExpression, name, target, indent) {
+ if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
+ var pos = getNodePos();
+ var child = void 0;
+ var children = void 0;
+ while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
+ if (child.kind === 338 /* JSDocParameterTag */ || child.kind === 345 /* JSDocPropertyTag */) {
+ children = ts.append(children, child);
+ }
+ }
+ if (children) {
+ var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 182 /* ArrayType */), pos);
+ return finishNode(factory.createJSDocTypeExpression(literal), pos);
+ }
+ }
+ }
+ function parseReturnTag(start, tagName, indent, indentText) {
+ if (ts.some(tags, ts.isJSDocReturnTag)) {
+ parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
+ }
+ var typeExpression = tryParseTypeExpression();
+ return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
+ }
+ function parseTypeTag(start, tagName, indent, indentText) {
+ if (ts.some(tags, ts.isJSDocTypeTag)) {
+ parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- else {
- var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
- if (watchOpt) {
- i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
+ var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
+ var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined;
+ return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start);
+ }
+ function parseSeeTag(start, tagName, indent, indentText) {
+ var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */
+ || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; });
+ var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference();
+ var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined;
+ return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start);
+ }
+ function parseAuthorTag(start, tagName, indent, indentText) {
+ var commentStart = getNodePos();
+ var textOnly = parseAuthorNameAndEmail();
+ var commentEnd = scanner.getStartPos();
+ var comments = parseTrailingTagComments(start, commentEnd, indent, indentText);
+ if (!comments) {
+ commentEnd = scanner.getStartPos();
+ }
+ var allParts = typeof comments !== "string"
+ ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly
+ : textOnly.text + comments;
+ return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start);
+ }
+ function parseAuthorNameAndEmail() {
+ var comments = [];
+ var inEmail = false;
+ var token = scanner.getToken();
+ while (token !== 1 /* EndOfFileToken */ && token !== 4 /* NewLineTrivia */) {
+ if (token === 29 /* LessThanToken */) {
+ inEmail = true;
}
- else {
- errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
+ else if (token === 59 /* AtToken */ && !inEmail) {
+ break;
+ }
+ else if (token === 31 /* GreaterThanToken */ && inEmail) {
+ comments.push(scanner.getTokenText());
+ scanner.setTextPos(scanner.getTokenPos() + 1);
+ break;
}
+ comments.push(scanner.getTokenText());
+ token = nextTokenJSDoc();
}
+ return factory.createJSDocText(comments.join(""));
}
- else {
- fileNames.push(s);
+ function parseImplementsTag(start, tagName, margin, indentText) {
+ var className = parseExpressionWithTypeArgumentsForAugments();
+ return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
}
- }
- }
- function parseResponseFile(fileName) {
- var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
- if (!ts.isString(text)) {
- errors.push(text);
- return;
- }
- var args = [];
- var pos = 0;
- while (true) {
- while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
- pos++;
- if (pos >= text.length)
- break;
- var start = pos;
- if (text.charCodeAt(start) === 34 /* doubleQuote */) {
- pos++;
- while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
- pos++;
- if (pos < text.length) {
- args.push(text.substring(start + 1, pos));
- pos++;
+ function parseAugmentsTag(start, tagName, margin, indentText) {
+ var className = parseExpressionWithTypeArgumentsForAugments();
+ return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
+ }
+ function parseExpressionWithTypeArgumentsForAugments() {
+ var usedBrace = parseOptional(18 /* OpenBraceToken */);
+ var pos = getNodePos();
+ var expression = parsePropertyAccessEntityNameExpression();
+ var typeArguments = tryParseTypeArguments();
+ var node = factory.createExpressionWithTypeArguments(expression, typeArguments);
+ var res = finishNode(node, pos);
+ if (usedBrace) {
+ parseExpected(19 /* CloseBraceToken */);
}
- else {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
+ return res;
+ }
+ function parsePropertyAccessEntityNameExpression() {
+ var pos = getNodePos();
+ var node = parseJSDocIdentifierName();
+ while (parseOptional(24 /* DotToken */)) {
+ var name = parseJSDocIdentifierName();
+ node = finishNode(factory.createPropertyAccessExpression(node, name), pos);
}
+ return node;
}
- else {
- while (text.charCodeAt(pos) > 32 /* space */)
- pos++;
- args.push(text.substring(start, pos));
+ function parseSimpleTag(start, createTag, tagName, margin, indentText) {
+ return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
}
- }
- parseStrings(args);
- }
- }
- ts.parseCommandLineWorker = parseCommandLineWorker;
- function parseOptionValue(args, i, diagnostics, opt, options, errors) {
- if (opt.isTSConfigOnly) {
- var optValue = args[i];
- if (optValue === "null") {
- options[opt.name] = undefined;
- i++;
- }
- else if (opt.type === "boolean") {
- if (optValue === "false") {
- options[opt.name] = false;
- i++;
+ function parseThisTag(start, tagName, margin, indentText) {
+ var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
+ skipWhitespace();
+ return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
}
- else {
- if (optValue === "true")
- i++;
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
+ function parseEnumTag(start, tagName, margin, indentText) {
+ var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
+ skipWhitespace();
+ return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
}
- }
- else {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
- if (optValue && !ts.startsWith(optValue, "-"))
- i++;
- }
- }
- 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(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
- }
- if (args[i] !== "null") {
- switch (opt.type) {
- case "number":
- options[opt.name] = parseInt(args[i]);
- 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++;
+ function parseTypedefTag(start, tagName, indent, indentText) {
+ var _a;
+ var typeExpression = tryParseTypeExpression();
+ skipWhitespaceOrAsterisk();
+ var fullName = parseJSDocTypeNameWithNamespace();
+ skipWhitespace();
+ var comment = parseTagComments(indent);
+ var end;
+ if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
+ var child = void 0;
+ var childTypeTag = void 0;
+ var jsDocPropertyTags = void 0;
+ var hasChildren = false;
+ while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
+ hasChildren = true;
+ if (child.kind === 341 /* JSDocTypeTag */) {
+ if (childTypeTag) {
+ parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
+ var lastError = ts.lastOrUndefined(parseDiagnostics);
+ if (lastError) {
+ ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, 0, 0, ts.Diagnostics.The_tag_was_first_specified_here));
+ }
+ break;
+ }
+ else {
+ childTypeTag = child;
+ }
+ }
+ else {
+ jsDocPropertyTags = ts.append(jsDocPropertyTags, child);
+ }
}
- break;
- case "string":
- options[opt.name] = args[i] || "";
- i++;
- break;
- case "list":
- var result = parseListTypeOption(opt, args[i], errors);
- options[opt.name] = result || [];
- if (result) {
- i++;
+ if (hasChildren) {
+ var isArrayType = typeExpression && typeExpression.type.kind === 182 /* ArrayType */;
+ var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
+ typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
+ childTypeTag.typeExpression :
+ finishNode(jsdocTypeLiteral, start);
+ end = typeExpression.end;
}
- 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++;
- break;
+ }
+ // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
+ end = end || comment !== undefined ?
+ getNodePos() :
+ ((_a = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _a !== void 0 ? _a : tagName).end;
+ if (!comment) {
+ comment = parseTrailingTagComments(start, end, indent, indentText);
+ }
+ var typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
+ return finishNode(typedefTag, start, end);
}
- }
- else {
- options[opt.name] = undefined;
- i++;
- }
- }
- return i;
- }
- /*@internal*/
- ts.compilerOptionsDidYouMeanDiagnostics = {
- getOptionsNameMap: getOptionsNameMap,
- optionDeclarations: ts.optionDeclarations,
- unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
- unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
- optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
- };
- function parseCommandLine(commandLine, readFile) {
- return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
- }
- ts.parseCommandLine = parseCommandLine;
- /** @internal */
- function getOptionFromName(optionName, allowShort) {
- return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
- }
- ts.getOptionFromName = getOptionFromName;
- function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
- if (allowShort === void 0) { allowShort = false; }
- optionName = optionName.toLowerCase();
- var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
- // Try to translate short option names to their full equivalents.
- if (allowShort) {
- var short = shortOptionNames.get(optionName);
- if (short !== undefined) {
- optionName = short;
- }
- }
- return optionsNameMap.get(optionName);
- }
- var buildOptionsNameMapCache;
- function getBuildOptionsNameMap() {
- return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
- }
- var buildOptionsDidYouMeanDiagnostics = {
- getOptionsNameMap: getBuildOptionsNameMap,
- optionDeclarations: ts.buildOpts,
- unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
- unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
- optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
- };
- /*@internal*/
- function parseBuildCommand(args) {
- var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
- var buildOptions = options;
- if (projects.length === 0) {
- // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
- projects.push(".");
- }
- // Nonsensical combinations
- if (buildOptions.clean && buildOptions.force) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
- }
- if (buildOptions.clean && buildOptions.verbose) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
- }
- if (buildOptions.clean && buildOptions.watch) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
- }
- if (buildOptions.watch && buildOptions.dry) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
- }
- return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
- }
- ts.parseBuildCommand = parseBuildCommand;
- /* @internal */
- function getDiagnosticText(_message) {
- var _args = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- _args[_i - 1] = arguments[_i];
- }
- var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
- return diagnostic.messageText;
- }
- ts.getDiagnosticText = getDiagnosticText;
- /**
- * Reads the config file, reports errors if any and exits if the config file cannot be found
- */
- function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
- var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
- if (!ts.isString(configFileText)) {
- host.onUnRecoverableConfigFileDiagnostic(configFileText);
- return undefined;
- }
- var result = ts.parseJsonText(configFileName, configFileText);
- var cwd = host.getCurrentDirectory();
- result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
- result.resolvedPath = result.path;
- result.originalFileName = result.fileName;
- return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd),
- /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
- }
- 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 {
- config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
- error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
- };
- }
- 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] };
- }
- ts.readJsonConfigFile = readJsonConfigFile;
- /*@internal*/
- function tryReadFile(fileName, readFile) {
- var text;
- try {
- text = readFile(fileName);
- }
- catch (e) {
- return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
- }
- return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
- }
- ts.tryReadFile = tryReadFile;
- function commandLineOptionsToMap(options) {
- return ts.arrayToMap(options, getOptionName);
- }
- var typeAcquisitionDidYouMeanDiagnostics = {
- optionDeclarations: ts.typeAcquisitionDeclarations,
- unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
- unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
- };
- var watchOptionsNameMapCache;
- function getWatchOptionsNameMap() {
- return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
- }
- var watchOptionsDidYouMeanDiagnostics = {
- getOptionsNameMap: getWatchOptionsNameMap,
- optionDeclarations: ts.optionsForWatch,
- unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
- unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
- optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
- };
- var commandLineCompilerOptionsMapCache;
- function getCommandLineCompilerOptionsMap() {
- return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
- }
- var commandLineWatchOptionsMapCache;
- function getCommandLineWatchOptionsMap() {
- return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
- }
- var commandLineTypeAcquisitionMapCache;
- function getCommandLineTypeAcquisitionMap() {
- return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
- }
- var _tsconfigRootOptions;
- function getTsconfigRootOptionsMap() {
- if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = {
- name: undefined,
- type: "object",
- elementOptions: commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: getCommandLineCompilerOptionsMap(),
- extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
- },
- {
- name: "watchOptions",
- type: "object",
- elementOptions: getCommandLineWatchOptionsMap(),
- extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: getCommandLineTypeAcquisitionMap(),
- extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: getCommandLineTypeAcquisitionMap(),
- extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "references",
- type: "list",
- element: {
- name: "references",
- type: "object"
+ function parseJSDocTypeNameWithNamespace(nested) {
+ var pos = scanner.getTokenPos();
+ if (!ts.tokenIsIdentifierOrKeyword(token())) {
+ return undefined;
+ }
+ var typeNameOrNamespaceName = parseJSDocIdentifierName();
+ if (parseOptional(24 /* DotToken */)) {
+ var body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
+ var jsDocNamespaceNode = factory.createModuleDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : undefined);
+ return finishNode(jsDocNamespaceNode, pos);
+ }
+ if (nested) {
+ typeNameOrNamespaceName.isInJSDocNamespace = true;
+ }
+ return typeNameOrNamespaceName;
+ }
+ function parseCallbackTagParameters(indent) {
+ var pos = getNodePos();
+ var child;
+ var parameters;
+ while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
+ parameters = ts.append(parameters, child);
+ }
+ return createNodeArray(parameters || [], pos);
+ }
+ function parseCallbackTag(start, tagName, indent, indentText) {
+ var fullName = parseJSDocTypeNameWithNamespace();
+ skipWhitespace();
+ var comment = parseTagComments(indent);
+ var parameters = parseCallbackTagParameters(indent);
+ var returnTag = tryParse(function () {
+ if (parseOptionalJsdoc(59 /* AtToken */)) {
+ var tag = parseTag(indent);
+ if (tag && tag.kind === 339 /* JSDocReturnTag */) {
+ return tag;
+ }
}
- },
- {
- name: "files",
- type: "list",
- element: {
- name: "files",
- type: "string"
+ });
+ var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start);
+ if (!comment) {
+ comment = parseTrailingTagComments(start, getNodePos(), indent, indentText);
+ }
+ return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start);
+ }
+ function escapedTextsEqual(a, b) {
+ while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
+ if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
+ a = a.left;
+ b = b.left;
}
- },
- {
- name: "include",
- type: "list",
- element: {
- name: "include",
- type: "string"
+ else {
+ return false;
}
- },
- {
- name: "exclude",
- type: "list",
- element: {
- name: "exclude",
- type: "string"
+ }
+ return a.escapedText === b.escapedText;
+ }
+ function parseChildPropertyTag(indent) {
+ return parseChildParameterOrPropertyTag(1 /* Property */, indent);
+ }
+ function parseChildParameterOrPropertyTag(target, indent, name) {
+ var canParseTag = true;
+ var seenAsterisk = false;
+ while (true) {
+ switch (nextTokenJSDoc()) {
+ case 59 /* AtToken */:
+ if (canParseTag) {
+ var child = tryParseChildTag(target, indent);
+ if (child && (child.kind === 338 /* JSDocParameterTag */ || child.kind === 345 /* JSDocPropertyTag */) &&
+ target !== 4 /* CallbackParameter */ &&
+ name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
+ return false;
+ }
+ return child;
+ }
+ seenAsterisk = false;
+ break;
+ case 4 /* NewLineTrivia */:
+ canParseTag = true;
+ seenAsterisk = false;
+ break;
+ case 41 /* AsteriskToken */:
+ if (seenAsterisk) {
+ canParseTag = false;
+ }
+ seenAsterisk = true;
+ break;
+ case 79 /* Identifier */:
+ canParseTag = false;
+ break;
+ case 1 /* EndOfFileToken */:
+ return false;
}
- },
- ts.compileOnSaveCommandLineOption
- ])
- };
- }
- return _tsconfigRootOptions;
- }
- /**
- * Convert the json syntax tree into the json value
- */
- function convertToObject(sourceFile, errors) {
- 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;
- }
- return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
- function isRootOptionMap(knownOptions) {
- return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
- }
- function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
- var result = returnValue ? {} : undefined;
- var _loop_3 = function (element) {
- if (element.kind !== 281 /* PropertyAssignment */) {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
- return "continue";
+ }
}
- if (element.questionToken) {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
+ function tryParseChildTag(target, indent) {
+ ts.Debug.assert(token() === 59 /* AtToken */);
+ var start = scanner.getStartPos();
+ nextTokenJSDoc();
+ var tagName = parseJSDocIdentifierName();
+ skipWhitespace();
+ var t;
+ switch (tagName.escapedText) {
+ case "type":
+ return target === 1 /* Property */ && parseTypeTag(start, tagName);
+ case "prop":
+ case "property":
+ t = 1 /* Property */;
+ break;
+ case "arg":
+ case "argument":
+ case "param":
+ t = 2 /* Parameter */ | 4 /* CallbackParameter */;
+ break;
+ default:
+ return false;
+ }
+ if (!(target & t)) {
+ return false;
+ }
+ return parseParameterOrPropertyTag(start, tagName, target, indent);
+ }
+ function parseTemplateTagTypeParameter() {
+ var typeParameterPos = getNodePos();
+ var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
+ if (isBracketed) {
+ skipWhitespace();
+ }
+ var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
+ var defaultType;
+ if (isBracketed) {
+ skipWhitespace();
+ parseExpected(63 /* EqualsToken */);
+ defaultType = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
+ parseExpected(23 /* CloseBracketToken */);
+ }
+ if (ts.nodeIsMissing(name)) {
+ return undefined;
+ }
+ return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, defaultType), typeParameterPos);
+ }
+ function parseTemplateTagTypeParameters() {
+ var pos = getNodePos();
+ var typeParameters = [];
+ do {
+ skipWhitespace();
+ var node = parseTemplateTagTypeParameter();
+ if (node !== undefined) {
+ typeParameters.push(node);
+ }
+ skipWhitespaceOrAsterisk();
+ } while (parseOptionalJsdoc(27 /* CommaToken */));
+ return createNodeArray(typeParameters, pos);
}
- if (!isDoubleQuotedString(element.name)) {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
+ function parseTemplateTag(start, tagName, indent, indentText) {
+ // The template tag looks like one of the following:
+ // @template T,U,V
+ // @template {Constraint} T
+ //
+ // According to the [closure docs](https://github.com/google/closure-compiler/wiki/Generic-Types#multiple-bounded-template-types):
+ // > Multiple bounded generics cannot be declared on the same line. For the sake of clarity, if multiple templates share the same
+ // > type bound they must be declared on separate lines.
+ //
+ // TODO: Determine whether we should enforce this in the checker.
+ // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`.
+ // TODO: Consider only parsing a single type parameter if there is a constraint.
+ var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
+ var typeParameters = parseTemplateTagTypeParameters();
+ return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
}
- var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
- var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
- var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
- if (keyText && extraKeyDiagnostics && !option) {
- if (knownOptions) {
- errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
- }
- else {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
+ function parseOptionalJsdoc(t) {
+ if (token() === t) {
+ nextTokenJSDoc();
+ return true;
}
+ return false;
}
- var value = convertPropertyValueToJson(element.initializer, option);
- if (typeof keyText !== "undefined") {
- if (returnValue) {
- result[keyText] = value;
+ function parseJSDocEntityName() {
+ var entity = parseJSDocIdentifierName();
+ if (parseOptional(22 /* OpenBracketToken */)) {
+ parseExpected(23 /* 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.
}
- // 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);
- }
+ while (parseOptional(24 /* DotToken */)) {
+ var name = parseJSDocIdentifierName();
+ if (parseOptional(22 /* OpenBracketToken */)) {
+ parseExpected(23 /* CloseBracketToken */);
}
+ entity = createQualifiedName(entity, name);
}
+ return entity;
+ }
+ function parseJSDocIdentifierName(message) {
+ if (!ts.tokenIsIdentifierOrKeyword(token())) {
+ return createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
+ }
+ identifierCount++;
+ var pos = scanner.getTokenPos();
+ var end = scanner.getTextPos();
+ var originalKeywordKind = token();
+ var text = internIdentifier(scanner.getTokenValue());
+ var result = finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos, end);
+ nextTokenJSDoc();
+ return result;
}
- };
- for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
- var element = _a[_i];
- _loop_3(element);
}
- return result;
- }
- function convertArrayLiteralExpressionToJson(elements, elementOption) {
- if (!returnValue) {
- return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
+ })(Parser || (Parser = {}));
+ var IncrementalParser;
+ (function (IncrementalParser) {
+ function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
+ 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;
}
- // Filter out invalid values
- return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
+ if (sourceFile.statements.length === 0) {
+ // If we don't have any statements in the current source file, then there's no real
+ // way to incrementally parse. So just do a full parse instead.
+ return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*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;
+ Parser.fixupParentReferences(incrementalSourceFile);
+ 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);
+ // 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);
+ result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
+ result.impliedNodeFormat = sourceFile.impliedNodeFormat;
+ return result;
}
- function convertPropertyValueToJson(valueExpression, option) {
- switch (valueExpression.kind) {
- case 106 /* TrueKeyword */:
- reportInvalidOptionValue(option && option.type !== "boolean");
- return true;
- case 91 /* FalseKeyword */:
- reportInvalidOptionValue(option && option.type !== "boolean");
- return false;
- case 100 /* NullKeyword */:
- reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
- return null; // eslint-disable-line no-null/no-null
- case 10 /* StringLiteral */:
- if (!isDoubleQuotedString(valueExpression)) {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
- }
- reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
- 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 /* NumericLiteral */:
- reportInvalidOptionValue(option && option.type !== "number");
- return Number(valueExpression.text);
- case 207 /* PrefixUnaryExpression */:
- if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
- break; // not valid JSON syntax
- }
- reportInvalidOptionValue(option && option.type !== "number");
- return -Number(valueExpression.operand.text);
- case 193 /* 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, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
- return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
- }
- else {
- return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
- /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
+ IncrementalParser.updateSourceFile = updateSourceFile;
+ function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
+ if (!oldDirectives)
+ return newDirectives;
+ var commentDirectives;
+ var addedNewlyScannedDirectives = false;
+ for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
+ var directive = oldDirectives_1[_i];
+ var range = directive.range, type = directive.type;
+ // Range before the change
+ if (range.end < changeStart) {
+ commentDirectives = ts.append(commentDirectives, directive);
+ }
+ else if (range.pos > changeRangeOldEnd) {
+ addNewlyScannedDirectives();
+ // Node is entirely past the change range. We need to move both its pos and
+ // end, forward or backward appropriately.
+ var updatedDirective = {
+ range: { pos: range.pos + delta, end: range.end + delta },
+ type: type
+ };
+ commentDirectives = ts.append(commentDirectives, updatedDirective);
+ if (aggressiveChecks) {
+ ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
}
- case 192 /* ArrayLiteralExpression */:
- reportInvalidOptionValue(option && option.type !== "list");
- return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
+ }
+ // Ignore ranges that fall in change range
}
- // Not in expected format
- if (option) {
- reportInvalidOptionValue(/*isError*/ true);
+ addNewlyScannedDirectives();
+ return commentDirectives;
+ function addNewlyScannedDirectives() {
+ if (addedNewlyScannedDirectives)
+ return;
+ addedNewlyScannedDirectives = true;
+ if (!commentDirectives) {
+ commentDirectives = newDirectives;
+ }
+ else if (newDirectives) {
+ commentDirectives.push.apply(commentDirectives, newDirectives);
+ }
+ }
+ }
+ function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
+ if (isArray) {
+ visitArray(element);
}
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));
+ visitNode(element);
}
- return undefined;
- function reportInvalidOptionValue(isError) {
- if (isError) {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
+ return;
+ function visitNode(node) {
+ var text = "";
+ 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;
+ }
+ ts.setTextRangePosEnd(node, node.pos + delta, node.end + delta);
+ if (aggressiveChecks && shouldCheckNode(node)) {
+ ts.Debug.assert(text === newText.substring(node.pos, node.end));
+ }
+ forEachChild(node, visitNode, visitArray);
+ if (ts.hasJSDocNodes(node)) {
+ for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
+ var jsDocComment = _a[_i];
+ visitNode(jsDocComment);
+ }
}
+ checkNodePositions(node, aggressiveChecks);
}
- }
- function isDoubleQuotedString(node) {
- return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
- }
- }
- ts.convertToObjectWorker = convertToObjectWorker;
- function getCompilerOptionValueTypeString(option) {
- return option.type === "list" ?
- "Array" :
- ts.isString(option.type) ? option.type : "string";
- }
- function isCompilerOptionsValue(option, value) {
- if (option) {
- if (isNullOrUndefined(value))
- return true; // All options are undefinable/nullable
- if (option.type === "list") {
- return ts.isArray(value);
+ function visitArray(array) {
+ array._children = undefined;
+ ts.setTextRangePosEnd(array, array.pos + delta, array.end + delta);
+ for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
+ var node = array_9[_i];
+ visitNode(node);
+ }
}
- var expectedType = ts.isString(option.type) ? option.type : "string";
- return typeof value === expectedType;
}
- return false;
- }
- /**
- * Generate an uncommented, complete tsconfig for use with "--showConfig"
- * @param configParseResult options to be generated into tsconfig.json
- * @param configFileName name of the parsed config file - output paths will be generated relative to this
- * @param host provides current directory and case sensitivity services
- */
- /** @internal */
- function convertToTSConfig(configParseResult, configFileName, host) {
- var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
- var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
- var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
- var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
- var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? {
- include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
- exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
- } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
- return config;
- }
- ts.convertToTSConfig = convertToTSConfig;
- function optionMapToObject(optionMap) {
- return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
- var _a;
- return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
- }, {}));
- }
- function filterSameAsDefaultInclude(specs) {
- if (!ts.length(specs))
- return undefined;
- if (ts.length(specs) !== 1)
- return specs;
- if (specs[0] === "**/*")
- return undefined;
- return specs;
- }
- function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
- if (!includeSpecs)
- return function (_) { return true; };
- var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
- var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
- var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
- if (includeRe) {
- if (excludeRe) {
- return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
+ function shouldCheckNode(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ case 79 /* Identifier */:
+ return true;
}
- return function (path) { return !includeRe.test(path); };
- }
- if (excludeRe) {
- return function (path) { return excludeRe.test(path); };
- }
- return function (_) { return true; };
- }
- function getCustomTypeMapOfCommandLineOption(optionDefinition) {
- if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
- // this is of a type CommandLineOptionOfPrimitiveType
- return undefined;
- }
- else if (optionDefinition.type === "list") {
- return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
+ return false;
}
- else {
- return optionDefinition.type;
+ function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
+ 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.
+ var 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.
+ var end = element.end >= changeRangeOldEnd ?
+ // Element ends after the change range. Always adjust the end pos.
+ element.end + delta :
+ // 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.
+ Math.min(element.end, changeRangeNewEnd);
+ ts.Debug.assert(pos <= end);
+ if (element.parent) {
+ ts.Debug.assertGreaterThanOrEqual(pos, element.parent.pos);
+ ts.Debug.assertLessThanOrEqual(end, element.parent.end);
+ }
+ ts.setTextRangePosEnd(element, pos, end);
}
- }
- 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;
+ function checkNodePositions(node, aggressiveChecks) {
+ if (aggressiveChecks) {
+ var pos_2 = node.pos;
+ var visitNode_1 = function (child) {
+ ts.Debug.assert(child.pos >= pos_2);
+ pos_2 = child.end;
+ };
+ if (ts.hasJSDocNodes(node)) {
+ for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
+ var jsDocComment = _a[_i];
+ visitNode_1(jsDocComment);
+ }
+ }
+ forEachChild(node, visitNode_1);
+ ts.Debug.assert(pos_2 <= node.end);
}
- });
- }
- function serializeCompilerOptions(options, pathOptions) {
- return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
- }
- function serializeWatchOptions(options) {
- return serializeOptionBaseObject(options, getWatchOptionsNameMap());
- }
- function serializeOptionBaseObject(options, _a, pathOptions) {
- var optionsNameMap = _a.optionsNameMap;
- var result = ts.createMap();
- var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
- var _loop_4 = 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";
+ }
+ function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
+ visitNode(sourceFile);
+ return;
+ function visitNode(child) {
+ ts.Debug.assert(child.pos <= child.end);
+ if (child.pos > changeRangeOldEnd) {
+ // 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;
}
- var value = options[name];
- var optionDefinition = optionsNameMap.get(name.toLowerCase());
- 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
- if (pathOptions && optionDefinition.isFilePath) {
- result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
- }
- else {
- result.set(name, value);
+ // 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)) {
+ for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
+ var jsDocComment = _a[_i];
+ visitNode(jsDocComment);
}
}
- else {
- if (optionDefinition.type === "list") {
- 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));
- }
+ 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) {
+ // 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_10 = array; _i < array_10.length; _i++) {
+ var node = array_10[_i];
+ visitNode(node);
}
+ return;
}
+ // Otherwise, the array is entirely before the change range. No need to do anything with it.
+ ts.Debug.assert(fullEnd < changeStart);
}
- };
- for (var name in options) {
- _loop_4(name);
}
- return result;
- }
- /**
- * 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 getDefaultValueForOption(option) {
- switch (option.type) {
- case "number":
- return 1;
- case "boolean":
- return true;
- case "string":
- return option.isFilePath ? "./" : "";
- case "list":
- return [];
- case "object":
- return {};
- default:
- var iterResult = option.type.keys().next();
- if (!iterResult.done)
- return iterResult.value;
- return ts.Debug.fail("Expected 'option.type' to have entries.");
+ 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);
+ var position = nearestNode.pos;
+ start = Math.max(0, position - 1);
}
+ var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
+ var finalLength = changeRange.newLength + (changeRange.span.start - start);
+ return ts.createTextChangeRange(finalSpan, finalLength);
}
- function makePadding(paddingLength) {
- return Array(paddingLength + 1).join(" ");
- }
- 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];
- var category = option.category;
- if (isAllowedOption(option)) {
- categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
+ function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
+ var bestResult = sourceFile;
+ var lastNodeEntirelyBeforePosition;
+ forEachChild(sourceFile, visit);
+ if (lastNodeEntirelyBeforePosition) {
+ var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
+ if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
+ bestResult = lastChildOfLastEntireNodeBeforePosition;
}
}
- // Serialize all options and their descriptions
- var marginLength = 0;
- var seenKnownKeys = 0;
- var entries = [];
- categorizedOptions.forEach(function (options, category) {
- if (entries.length !== 0) {
- entries.push({ value: "" });
- }
- entries.push({ value: "/* " + category + " */" });
- for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
- var option = options_1[_i];
- var optionName = void 0;
- if (compilerOptionsMap.has(option.name)) {
- optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
+ return bestResult;
+ function getLastDescendant(node) {
+ while (true) {
+ var lastChild = ts.getLastChild(node);
+ if (lastChild) {
+ node = lastChild;
}
else {
- optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
+ return node;
}
- entries.push({
- value: optionName,
- description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
- });
- marginLength = Math.max(optionName.length, marginLength);
}
- });
- // Write the output
- var tab = makePadding(2);
- var result = [];
- result.push("{");
- result.push(tab + "\"compilerOptions\": {");
- result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
- result.push("");
- // Print out each row, aligning all the descriptions on the same column.
- for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
- var entry = entries_3[_a];
- var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
- result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
}
- if (fileNames.length) {
- result.push(tab + "},");
- result.push(tab + "\"files\": [");
- for (var i = 0; i < fileNames.length; i++) {
- result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
+ 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;
}
- result.push(tab + "]");
- }
- else {
- result.push(tab + "}");
- }
- result.push("}");
- return result.join(newLine) + newLine;
- }
- }
- ts.generateTSConfig = generateTSConfig;
- /* @internal */
- function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
- var result = {};
- var optionsNameMap = getOptionsNameMap().optionsNameMap;
- for (var name in options) {
- if (ts.hasProperty(options, name)) {
- result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
}
}
- if (result.configFilePath) {
- result.configFilePath = toAbsolutePath(result.configFilePath);
- }
- return result;
- }
- ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
- function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
- if (option && !isNullOrUndefined(value)) {
- if (option.type === "list") {
- var values = value;
- if (option.element.isFilePath && values.length) {
- return values.map(toAbsolutePath);
+ function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
+ var oldText = sourceFile.text;
+ if (textChangeRange) {
+ ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
+ 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);
+ var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
+ var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
+ ts.Debug.assert(oldTextSuffix === newTextSuffix);
}
}
- else if (option.isFilePath) {
- return toAbsolutePath(value);
- }
- }
- return value;
- }
- /**
- * 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, extendedConfigCache, existingWatchOptions) {
- return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
- }
- 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, extendedConfigCache, existingWatchOptions) {
- return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
- }
- ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
- /*@internal*/
- function setConfigFileInOptions(options, configFile) {
- if (configFile) {
- Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
}
- }
- ts.setConfigFileInOptions = setConfigFileInOptions;
- function isNullOrUndefined(x) {
- return x === undefined || x === null; // eslint-disable-line no-null/no-null
- }
- function directoryOfCombinedPath(fileName, basePath) {
- // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistent 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, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
- if (existingOptions === void 0) { existingOptions = {}; }
- if (resolutionStack === void 0) { resolutionStack = []; }
- if (extraFileExtensions === void 0) { extraFileExtensions = []; }
- ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
- var errors = [];
- var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
- var raw = parsedConfig.raw;
- var options = ts.extend(existingOptions, parsedConfig.options || {});
- var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
- ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
- parsedConfig.watchOptions || existingWatchOptions;
- options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
- setConfigFileInOptions(options, sourceFile);
- var projectReferences;
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
- return {
- options: options,
- watchOptions: watchOptions,
- fileNames: fileNames,
- projectReferences: projectReferences,
- typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
- raw: raw,
- errors: errors,
- wildcardDirectories: wildcardDirectories,
- compileOnSave: !!raw.compileOnSave,
- configFileSpecs: spec
- };
- function getFileNames() {
- var filesSpecs;
- if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
- if (ts.isArray(raw.files)) {
- filesSpecs = raw.files;
- var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
- var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
- var hasExtends = ts.hasProperty(raw, "extends");
- if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
- if (sourceFile) {
- var fileName = configFileName || "tsconfig.json";
- var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
- var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
- var error = nodeValue
- ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
- : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
- errors.push(error);
+ function createSyntaxCursor(sourceFile) {
+ var currentArray = sourceFile.statements;
+ var currentArrayIndex = 0;
+ ts.Debug.assert(currentArrayIndex < currentArray.length);
+ var current = currentArray[currentArrayIndex];
+ 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];
}
- else {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
+ // 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;
}
- else {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
- }
- }
- var includeSpecs;
- if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
- if (ts.isArray(raw.include)) {
- includeSpecs = raw.include;
+ };
+ // 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 /* 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;
}
- else {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
+ 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;
+ return true;
+ }
+ 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;
+ }
+ }
+ }
+ }
+ }
+ // position wasn't in this array, have to keep searching.
+ return false;
}
}
- var excludeSpecs;
- if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
- if (ts.isArray(raw.exclude)) {
- excludeSpecs = raw.exclude;
+ }
+ IncrementalParser.createSyntaxCursor = createSyntaxCursor;
+ var InvalidPosition;
+ (function (InvalidPosition) {
+ InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
+ })(InvalidPosition || (InvalidPosition = {}));
+ })(IncrementalParser || (IncrementalParser = {}));
+ /** @internal */
+ function isDeclarationFileName(fileName) {
+ return ts.fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */]);
+ }
+ ts.isDeclarationFileName = isDeclarationFileName;
+ /*@internal*/
+ function processCommentPragmas(context, sourceText) {
+ var pragmas = [];
+ for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
+ var range = _a[_i];
+ var comment = sourceText.substring(range.pos, range.end);
+ extractPragmas(pragmas, range, comment);
+ }
+ context.pragmas = new ts.Map();
+ for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
+ var pragma = pragmas_1[_b];
+ if (context.pragmas.has(pragma.name)) {
+ var currentValue = context.pragmas.get(pragma.name);
+ if (currentValue instanceof Array) {
+ currentValue.push(pragma.args);
}
else {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
- }
- }
- else if (raw.compilerOptions) {
- var outDir = raw.compilerOptions.outDir;
- var declarationDir = raw.compilerOptions.declarationDir;
- if (outDir || declarationDir) {
- excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
+ context.pragmas.set(pragma.name, [currentValue, pragma.args]);
}
+ continue;
}
- if (filesSpecs === undefined && includeSpecs === undefined) {
- includeSpecs = ["**/*"];
- }
- var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
- errors.push(getErrorForNoInputFiles(result.spec, configFileName));
- }
- if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
- if (ts.isArray(raw.references)) {
- for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
- var ref = _a[_i];
- if (typeof ref.path !== "string") {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ context.pragmas.set(pragma.name, pragma.args);
+ }
+ }
+ ts.processCommentPragmas = processCommentPragmas;
+ /*@internal*/
+ function processPragmasIntoFields(context, reportDiagnostic) {
+ context.checkJsDirective = undefined;
+ context.referencedFiles = [];
+ context.typeReferenceDirectives = [];
+ context.libReferenceDirectives = [];
+ 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) {
+ var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
+ if (arg.arguments["no-default-lib"]) {
+ context.hasNoDefaultLib = true;
+ }
+ else if (types) {
+ typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
+ }
+ else if (lib) {
+ libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
+ }
+ else if (path) {
+ referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
}
else {
- (projectReferences || (projectReferences = [])).push({
- path: ts.getNormalizedAbsolutePath(ref.path, basePath),
- originalPath: ref.path,
- prepend: ref.prepend,
- circular: ref.circular
- });
+ reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
}
+ });
+ break;
+ }
+ case "amd-dependency": {
+ context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
+ break;
+ }
+ case "amd-module": {
+ if (entryOrList instanceof Array) {
+ 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;
+ }
+ }
+ else {
+ context.moduleName = entryOrList.arguments.name;
}
+ break;
}
- else {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ 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) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
}
+ case "jsx":
+ case "jsxfrag":
+ case "jsximportsource":
+ case "jsxruntime":
+ return; // Accessed directly
+ default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
}
- return result;
- }
- function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
- if (!sourceFile) {
- errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
- }
- }
- }
- 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;
- }
- 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 || []));
- }
- function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
- return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
- }
- /*@internal*/
- function canJsonReportNoInutFiles(raw) {
- return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
+ });
}
- ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
- /*@internal*/
- function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
- var existingErrors = configParseDiagnostics.length;
- if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
- configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
- }
- else {
- ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = new ts.Map();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
}
- return existingErrors !== configParseDiagnostics.length;
- }
- ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
- function isSuccessfulParsedTsconfig(value) {
- return !!value.options;
+ var result = new RegExp("(\\s".concat(name, "\\s*=\\s*)(?:(?:'([^']*)')|(?:\"([^\"]*)\"))"), "im");
+ namedArgRegExCache.set(name, result);
+ return result;
}
- /**
- * 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, extendedConfigCache) {
- basePath = ts.normalizeSlashes(basePath);
- var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
- if (resolutionStack.indexOf(resolvedPath) >= 0) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
- return { raw: json || convertToObject(sourceFile, errors) };
- }
- var ownConfig = json ?
- 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, extendedConfigCache);
- if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
- var baseRaw_1 = extendedConfig.raw;
- var raw_1 = ownConfig.raw;
- var setPropertyInRawIfNotUndefined = function (propertyName) {
- var value = raw_1[propertyName] || baseRaw_1[propertyName];
- if (value) {
- raw_1[propertyName] = value;
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ 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 /* TripleSlashXML */)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return; // Missing required argument, don't parse
+ }
+ else if (matchResult) {
+ var value = matchResult[2] || matchResult[3];
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + 1;
+ argument[arg.name] = {
+ value: value,
+ pos: startPos,
+ end: startPos + value.length
+ };
+ }
+ else {
+ argument[arg.name] = value;
+ }
}
- };
- setPropertyInRawIfNotUndefined("include");
- setPropertyInRawIfNotUndefined("exclude");
- setPropertyInRawIfNotUndefined("files");
- if (raw_1.compileOnSave === undefined) {
- raw_1.compileOnSave = baseRaw_1.compileOnSave;
}
- ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
- ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
- ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
- ownConfig.watchOptions || extendedConfig.watchOptions;
- // TODO extend type typeAcquisition
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
+ }
+ if (range.kind === 3 /* MultiLineCommentTrivia */) {
+ var multiLinePragmaRegEx = /@(\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 /* MultiLine */, multiLineMatch);
}
}
- return ownConfig;
}
- function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
- if (ts.hasProperty(json, "excludes")) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ 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 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);
- var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
- json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
- var extendedConfigPath;
- if (json.extends) {
- if (!ts.isString(json.extends)) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
+ var args = match[2]; // Split on spaces and match up positionally with definition
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return; // Missing required argument, fail to parse it
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = ts.trimString(text).split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
}
- else {
- var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
- extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
}
+ argMap[argument.name] = args[i];
}
- return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
+ return argMap;
}
- function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
- var options = getDefaultCompilerOptions(configFileName);
- var typeAcquisition, typingOptionstypeAcquisition;
- var watchOptions;
- var extendedConfigPath;
- var optionsIterator = {
- onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
- var currentOption;
- switch (parentOption) {
- case "compilerOptions":
- currentOption = options;
- break;
- case "watchOptions":
- currentOption = (watchOptions || (watchOptions = {}));
- break;
- case "typeAcquisition":
- currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
- break;
- case "typingOptions":
- currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
- break;
- default:
- ts.Debug.fail("Unknown option");
- }
- currentOption[option.name] = normalizeOptionValue(option, basePath, value);
+ /** @internal */
+ function tagNamesAreEquivalent(lhs, rhs) {
+ if (lhs.kind !== rhs.kind) {
+ return false;
+ }
+ if (lhs.kind === 79 /* Identifier */) {
+ return lhs.escapedText === rhs.escapedText;
+ }
+ if (lhs.kind === 108 /* 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);
+ }
+ ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ /* @internal */
+ ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" };
+ var jsxOptionMap = new ts.Map(ts.getEntries({
+ "preserve": 1 /* Preserve */,
+ "react-native": 3 /* ReactNative */,
+ "react": 2 /* React */,
+ "react-jsx": 4 /* ReactJSX */,
+ "react-jsxdev": 5 /* ReactJSXDev */,
+ }));
+ /* @internal */
+ ts.inverseJsxOptionMap = new ts.Map(ts.arrayFrom(ts.mapIterator(jsxOptionMap.entries(), function (_a) {
+ var key = _a[0], value = _a[1];
+ return ["" + value, key];
+ })));
+ // 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"],
+ ["es7", "lib.es2016.d.ts"],
+ ["es2016", "lib.es2016.d.ts"],
+ ["es2017", "lib.es2017.d.ts"],
+ ["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
+ ["es2020", "lib.es2020.d.ts"],
+ ["es2021", "lib.es2021.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"],
+ ["webworker.iterable", "lib.webworker.iterable.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"],
+ ["es2015.iterable", "lib.es2015.iterable.d.ts"],
+ ["es2015.promise", "lib.es2015.promise.d.ts"],
+ ["es2015.proxy", "lib.es2015.proxy.d.ts"],
+ ["es2015.reflect", "lib.es2015.reflect.d.ts"],
+ ["es2015.symbol", "lib.es2015.symbol.d.ts"],
+ ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
+ ["es2016.array.include", "lib.es2016.array.include.d.ts"],
+ ["es2017.object", "lib.es2017.object.d.ts"],
+ ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
+ ["es2017.string", "lib.es2017.string.d.ts"],
+ ["es2017.intl", "lib.es2017.intl.d.ts"],
+ ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
+ ["es2018.intl", "lib.es2018.intl.d.ts"],
+ ["es2018.promise", "lib.es2018.promise.d.ts"],
+ ["es2018.regexp", "lib.es2018.regexp.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.object", "lib.es2019.object.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["es2020.bigint", "lib.es2020.bigint.d.ts"],
+ ["es2020.promise", "lib.es2020.promise.d.ts"],
+ ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"],
+ ["es2020.string", "lib.es2020.string.d.ts"],
+ ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
+ ["es2020.intl", "lib.es2020.intl.d.ts"],
+ ["es2021.promise", "lib.es2021.promise.d.ts"],
+ ["es2021.string", "lib.es2021.string.d.ts"],
+ ["es2021.weakref", "lib.es2021.weakref.d.ts"],
+ ["es2021.intl", "lib.es2021.intl.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
+ ["esnext.intl", "lib.esnext.intl.d.ts"],
+ ["esnext.bigint", "lib.es2020.bigint.d.ts"],
+ ["esnext.string", "lib.es2021.string.d.ts"],
+ ["esnext.promise", "lib.es2021.promise.d.ts"],
+ ["esnext.weakref", "lib.es2021.weakref.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 = new ts.Map(libEntries);
+ // Watch related options
+ /* @internal */
+ ts.optionsForWatch = [
+ {
+ name: "watchFile",
+ type: new ts.Map(ts.getEntries({
+ fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
+ prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
+ dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
+ fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling,
+ usefsevents: ts.WatchFileKind.UseFsEvents,
+ usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
+ })),
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Specify_how_the_TypeScript_watch_mode_works,
+ },
+ {
+ name: "watchDirectory",
+ type: new ts.Map(ts.getEntries({
+ usefsevents: ts.WatchDirectoryKind.UseFsEvents,
+ fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
+ dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
+ fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling,
+ })),
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality,
+ },
+ {
+ name: "fallbackPolling",
+ type: new ts.Map(ts.getEntries({
+ fixedinterval: ts.PollingWatchKind.FixedInterval,
+ priorityinterval: ts.PollingWatchKind.PriorityInterval,
+ dynamicpriority: ts.PollingWatchKind.DynamicPriority,
+ fixedchunksize: ts.PollingWatchKind.FixedChunkSize,
+ })),
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers,
+ },
+ {
+ name: "synchronousWatchDirectory",
+ type: "boolean",
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "excludeDirectories",
+ type: "list",
+ element: {
+ name: "excludeDirectory",
+ type: "string",
+ isFilePath: true,
+ extraValidation: specToDiagnostic
+ },
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Remove_a_list_of_directories_from_the_watch_process,
+ },
+ {
+ name: "excludeFiles",
+ type: "list",
+ element: {
+ name: "excludeFile",
+ type: "string",
+ isFilePath: true,
+ extraValidation: specToDiagnostic
+ },
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing,
+ },
+ ];
+ /* @internal */
+ ts.commonOptionsWithBuild = [
+ {
+ name: "help",
+ shortName: "h",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Print_this_message,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "help",
+ shortName: "?",
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ {
+ name: "watch",
+ shortName: "w",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ isCommandLineOnly: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Watch_input_files,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Output_Formatting,
+ description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "listFiles",
+ type: "boolean",
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Print_all_of_the_files_read_during_the_compilation,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "explainFiles",
+ type: "boolean",
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "listEmittedFiles",
+ type: "boolean",
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Print_the_names_of_emitted_files_after_a_compilation,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "pretty",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Output_Formatting,
+ description: ts.Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read,
+ defaultValueDescription: "true"
+ },
+ {
+ name: "traceResolution",
+ type: "boolean",
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Log_paths_used_during_the_moduleResolution_process,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Output_compiler_performance_information_after_building,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Output_more_detailed_compiler_performance_information_after_building,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "generateCpuProfile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging,
+ defaultValueDescription: "profile.cpuprofile"
+ },
+ {
+ name: "generateTrace",
+ type: "string",
+ isFilePath: true,
+ isCommandLineOnly: true,
+ paramType: ts.Diagnostics.DIRECTORY,
+ category: ts.Diagnostics.Compiler_Diagnostics,
+ description: ts.Diagnostics.Generates_an_event_trace_and_a_list_of_types
+ },
+ {
+ name: "incremental",
+ shortName: "i",
+ type: "boolean",
+ category: ts.Diagnostics.Projects,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ transpileOptionValue: undefined,
+ defaultValueDescription: ts.Diagnostics.false_unless_composite_is_set
+ },
+ {
+ name: "assumeChangesOnlyAffectDirectDependencies",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ affectsEmit: true,
+ category: ts.Diagnostics.Watch_and_Build_Modes,
+ description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "locale",
+ type: "string",
+ category: ts.Diagnostics.Command_line_Options,
+ isCommandLineOnly: true,
+ description: ts.Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit,
+ defaultValueDescription: ts.Diagnostics.Platform_specific
+ },
+ ];
+ /* @internal */
+ ts.targetOptionDeclaration = {
+ name: "target",
+ shortName: "t",
+ type: new ts.Map(ts.getEntries({
+ es3: 0 /* ES3 */,
+ es5: 1 /* ES5 */,
+ es6: 2 /* ES2015 */,
+ es2015: 2 /* ES2015 */,
+ es2016: 3 /* ES2016 */,
+ es2017: 4 /* ES2017 */,
+ es2018: 5 /* ES2018 */,
+ es2019: 6 /* ES2019 */,
+ es2020: 7 /* ES2020 */,
+ es2021: 8 /* ES2021 */,
+ esnext: 99 /* ESNext */,
+ })),
+ affectsSourceFile: true,
+ affectsModuleResolution: true,
+ affectsEmit: true,
+ paramType: ts.Diagnostics.VERSION,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations,
+ defaultValueDescription: "ES3"
+ };
+ var commandOptionsWithoutBuild = [
+ // CommandLine only options
+ {
+ name: "all",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Show_all_compiler_options,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "version",
+ shortName: "v",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Print_the_compiler_s_version,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "init",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "project",
+ shortName: "p",
+ type: "string",
+ isFilePath: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
+ description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
+ },
+ {
+ name: "build",
+ type: "boolean",
+ shortName: "b",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "showConfig",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ isCommandLineOnly: true,
+ description: ts.Diagnostics.Print_the_final_configuration_instead_of_building,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "listFilesOnly",
+ type: "boolean",
+ category: ts.Diagnostics.Command_line_Options,
+ affectsSemanticDiagnostics: true,
+ affectsEmit: true,
+ isCommandLineOnly: true,
+ description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing,
+ defaultValueDescription: "false",
+ },
+ // Basic
+ ts.targetOptionDeclaration,
+ {
+ name: "module",
+ shortName: "m",
+ type: new ts.Map(ts.getEntries({
+ none: ts.ModuleKind.None,
+ commonjs: ts.ModuleKind.CommonJS,
+ amd: ts.ModuleKind.AMD,
+ system: ts.ModuleKind.System,
+ umd: ts.ModuleKind.UMD,
+ es6: ts.ModuleKind.ES2015,
+ es2015: ts.ModuleKind.ES2015,
+ es2020: ts.ModuleKind.ES2020,
+ es2022: ts.ModuleKind.ES2022,
+ esnext: ts.ModuleKind.ESNext,
+ node12: ts.ModuleKind.Node12,
+ nodenext: ts.ModuleKind.NodeNext,
+ })),
+ affectsModuleResolution: true,
+ affectsEmit: true,
+ paramType: ts.Diagnostics.KIND,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_what_module_code_is_generated,
+ },
+ {
+ name: "lib",
+ type: "list",
+ element: {
+ name: "lib",
+ type: ts.libMap
+ },
+ affectsProgramStructure: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment,
+ transpileOptionValue: undefined
+ },
+ {
+ name: "allowJs",
+ type: "boolean",
+ affectsModuleResolution: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.JavaScript_Support,
+ description: ts.Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "checkJs",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.JavaScript_Support,
+ description: ts.Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "jsx",
+ type: jsxOptionMap,
+ affectsSourceFile: true,
+ affectsEmit: true,
+ affectsModuleResolution: true,
+ paramType: ts.Diagnostics.KIND,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Specify_what_JSX_code_is_generated,
+ defaultValueDescription: "undefined"
+ },
+ {
+ name: "declaration",
+ shortName: "d",
+ type: "boolean",
+ affectsEmit: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ transpileOptionValue: undefined,
+ description: ts.Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project,
+ defaultValueDescription: ts.Diagnostics.false_unless_composite_is_set,
+ },
+ {
+ name: "declarationMap",
+ type: "boolean",
+ affectsEmit: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ transpileOptionValue: undefined,
+ defaultValueDescription: "false",
+ description: ts.Diagnostics.Create_sourcemaps_for_d_ts_files
+ },
+ {
+ name: "emitDeclarationOnly",
+ type: "boolean",
+ affectsEmit: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files,
+ transpileOptionValue: undefined,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "sourceMap",
+ type: "boolean",
+ affectsEmit: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ defaultValueDescription: "false",
+ description: ts.Diagnostics.Create_source_map_files_for_emitted_JavaScript_files,
+ },
+ {
+ name: "outFile",
+ type: "string",
+ affectsEmit: true,
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output,
+ transpileOptionValue: undefined,
+ },
+ {
+ name: "outDir",
+ type: "string",
+ affectsEmit: true,
+ isFilePath: true,
+ paramType: ts.Diagnostics.DIRECTORY,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files,
+ },
+ {
+ name: "rootDir",
+ type: "string",
+ affectsEmit: true,
+ isFilePath: true,
+ paramType: ts.Diagnostics.LOCATION,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_the_root_folder_within_your_source_files,
+ defaultValueDescription: ts.Diagnostics.Computed_from_the_list_of_input_files
+ },
+ {
+ name: "composite",
+ type: "boolean",
+ affectsEmit: true,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Projects,
+ transpileOptionValue: undefined,
+ defaultValueDescription: "false",
+ description: ts.Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ affectsEmit: true,
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ category: ts.Diagnostics.Projects,
+ transpileOptionValue: undefined,
+ defaultValueDescription: ".tsbuildinfo",
+ description: ts.Diagnostics.Specify_the_folder_for_tsbuildinfo_incremental_compilation_files,
+ },
+ {
+ name: "removeComments",
+ type: "boolean",
+ affectsEmit: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ defaultValueDescription: "false",
+ description: ts.Diagnostics.Disable_emitting_comments,
+ },
+ {
+ name: "noEmit",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Disable_emitting_files_from_a_compilation,
+ transpileOptionValue: undefined,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "importHelpers",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "importsNotUsedAsValues",
+ type: new ts.Map(ts.getEntries({
+ remove: 0 /* Remove */,
+ preserve: 1 /* Preserve */,
+ error: 2 /* Error */,
+ })),
+ affectsEmit: true,
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
+ },
+ {
+ name: "downlevelIteration",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "isolatedModules",
+ type: "boolean",
+ category: ts.Diagnostics.Interop_Constraints,
+ description: ts.Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports,
+ transpileOptionValue: true,
+ defaultValueDescription: "false"
+ },
+ // Strict Type Checks
+ {
+ name: "strict",
+ type: "boolean",
+ // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here
+ // The value of each strictFlag depends on own strictFlag value or this and never accessed directly.
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enable_all_strict_type_checking_options,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noImplicitAny",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ {
+ name: "strictNullChecks",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ {
+ name: "strictFunctionTypes",
+ type: "boolean",
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ {
+ name: "strictBindCallApply",
+ type: "boolean",
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ {
+ name: "strictPropertyInitialization",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ {
+ name: "noImplicitThis",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ {
+ name: "useUnknownInCatchVariables",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "alwaysStrict",
+ type: "boolean",
+ affectsSourceFile: true,
+ strictFlag: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Ensure_use_strict_is_always_emitted,
+ defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
+ },
+ // Additional Checks
+ {
+ name: "noUnusedLocals",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enable_error_reporting_when_a_local_variables_aren_t_read,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noUnusedParameters",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "exactOptionalPropertyTypes",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "noImplicitReturns",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noFallthroughCasesInSwitch",
+ type: "boolean",
+ affectsBindDiagnostics: true,
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "noUncheckedIndexedAccess",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Include_undefined_in_index_signature_results,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "noImplicitOverride",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "noPropertyAccessFromIndexSignature",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type,
+ defaultValueDescription: "false"
+ },
+ // Module Resolution
+ {
+ name: "moduleResolution",
+ type: new ts.Map(ts.getEntries({
+ node: ts.ModuleResolutionKind.NodeJs,
+ classic: ts.ModuleResolutionKind.Classic,
+ node12: ts.ModuleResolutionKind.Node12,
+ nodenext: ts.ModuleResolutionKind.NodeNext,
+ })),
+ affectsModuleResolution: true,
+ paramType: ts.Diagnostics.STRATEGY,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier,
+ defaultValueDescription: ts.Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node
+ },
+ {
+ name: "baseUrl",
+ type: "string",
+ affectsModuleResolution: true,
+ isFilePath: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names
+ },
+ {
+ // this option can only be specified in tsconfig.json
+ // use type = object to copy the value as-is
+ name: "paths",
+ type: "object",
+ affectsModuleResolution: true,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations,
+ transpileOptionValue: undefined
+ },
+ {
+ // this option can only be specified in tsconfig.json
+ // use type = object to copy the value as-is
+ name: "rootDirs",
+ type: "list",
+ isTSConfigOnly: true,
+ element: {
+ name: "rootDirs",
+ type: "string",
+ isFilePath: true
},
- onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
- switch (key) {
- case "extends":
- var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
- extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
- return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
- });
- return;
- }
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules,
+ transpileOptionValue: undefined,
+ defaultValueDescription: ts.Diagnostics.Computed_from_the_list_of_input_files
+ },
+ {
+ name: "typeRoots",
+ type: "list",
+ element: {
+ name: "typeRoots",
+ type: "string",
+ isFilePath: true
},
- onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
- if (key === "excludes") {
- errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
- }
- }
- };
- var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
- if (!typeAcquisition) {
- if (typingOptionstypeAcquisition) {
- typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
- {
- enable: typingOptionstypeAcquisition.enableAutoDiscovery,
- include: typingOptionstypeAcquisition.include,
- exclude: typingOptionstypeAcquisition.exclude
- } :
- typingOptionstypeAcquisition;
- }
- else {
- typeAcquisition = getDefaultTypeAcquisition(configFileName);
- }
- }
- return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
- }
- function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
- extendedConfig = ts.normalizeSlashes(extendedConfig);
- if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
- var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
- if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
- extendedConfigPath = extendedConfigPath + ".json";
- if (!host.fileExists(extendedConfigPath)) {
- errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
- return undefined;
- }
- }
- return extendedConfigPath;
- }
- // If the path isn't a rooted or relative path, resolve like a module
- var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
- if (resolved.resolvedModule) {
- return resolved.resolvedModule.resolvedFileName;
- }
- errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
- return undefined;
- }
- function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
- var _a;
- var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
- var value;
- var extendedResult;
- var extendedConfig;
- if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
- (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
- }
- else {
- extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
- if (!extendedResult.parseDiagnostics.length) {
- var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
- extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
- 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) {
- if (raw_2[propertyName]) {
- raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
- }
- };
- var raw_2 = extendedConfig.raw;
- mapPropertiesInRawIfNotUndefined("include");
- mapPropertiesInRawIfNotUndefined("exclude");
- mapPropertiesInRawIfNotUndefined("files");
- }
- }
- if (extendedConfigCache) {
- extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
- }
- }
- if (sourceFile) {
- sourceFile.extendedSourceFiles = [extendedResult.fileName];
- if (extendedResult.extendedSourceFiles) {
- (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
- }
- }
- if (extendedResult.parseDiagnostics.length) {
- errors.push.apply(errors, extendedResult.parseDiagnostics);
- return undefined;
- }
- return extendedConfig;
- }
- function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
- if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
- return false;
- }
- var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
- return typeof result === "boolean" && result;
- }
- function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
- var errors = [];
- var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
- return { options: options, errors: errors };
- }
- ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
- function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
- var errors = [];
- var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
- return { options: options, errors: errors };
- }
- ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
- function getDefaultCompilerOptions(configFileName) {
- var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
- ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
- : {};
- return options;
- }
- function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = getDefaultCompilerOptions(configFileName);
- convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
- if (configFileName) {
- options.configFilePath = ts.normalizeSlashes(configFileName);
- }
- return options;
- }
- function getDefaultTypeAcquisition(configFileName) {
- return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
- }
- function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
- var options = getDefaultTypeAcquisition(configFileName);
- var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
- convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
- return options;
- }
- function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
- return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
- }
- function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
- if (!jsonOptions) {
- return;
- }
- for (var id in jsonOptions) {
- var opt = optionsNameMap.get(id);
- if (opt) {
- (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
- }
- else {
- errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
- }
- }
- return defaultOptions;
- }
- function convertJsonOption(opt, value, basePath, errors) {
- if (isCompilerOptionsValue(opt, value)) {
- var optType = opt.type;
- if (optType === "list" && ts.isArray(value)) {
- return convertJsonOptionOfListType(opt, value, basePath, errors);
- }
- else if (!ts.isString(optType)) {
- return convertJsonOptionOfCustomType(opt, value, errors);
- }
- return normalizeNonListOptionValue(opt, basePath, value);
- }
- else {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
- }
- }
- function normalizeOptionValue(option, basePath, value) {
- if (isNullOrUndefined(value))
- return undefined;
- if (option.type === "list") {
- var listOption_1 = option;
- if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
- return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
- }
- return value;
- }
- else if (!ts.isString(option.type)) {
- return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
- }
- return normalizeNonListOptionValue(option, basePath, value);
- }
- function normalizeNonListOptionValue(option, basePath, value) {
- if (option.isFilePath) {
- value = ts.getNormalizedAbsolutePath(value, basePath);
- if (value === "") {
- value = ".";
- }
- }
- return value;
- }
- function convertJsonOptionOfCustomType(opt, value, errors) {
- if (isNullOrUndefined(value))
- return undefined;
- var key = value.toLowerCase();
- var val = opt.type.get(key);
- if (val !== undefined) {
- return val;
- }
- else {
- errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types
+ },
+ {
+ name: "types",
+ type: "list",
+ element: {
+ name: "types",
+ type: "string"
+ },
+ affectsProgramStructure: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file,
+ transpileOptionValue: undefined
+ },
+ {
+ name: "allowSyntheticDefaultImports",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Interop_Constraints,
+ description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export,
+ defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop
+ },
+ {
+ name: "esModuleInterop",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ affectsEmit: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Interop_Constraints,
+ description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "preserveSymlinks",
+ type: "boolean",
+ category: ts.Diagnostics.Interop_Constraints,
+ description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "allowUmdGlobalAccess",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
+ defaultValueDescription: "false"
+ },
+ // Source Maps
+ {
+ name: "sourceRoot",
+ type: "string",
+ affectsEmit: true,
+ paramType: ts.Diagnostics.LOCATION,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code,
+ },
+ {
+ name: "mapRoot",
+ type: "string",
+ affectsEmit: true,
+ paramType: ts.Diagnostics.LOCATION,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
+ },
+ {
+ name: "inlineSourceMap",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "inlineSources",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript,
+ defaultValueDescription: "false"
+ },
+ // Experimental
+ {
+ name: "experimentalDecorators",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "emitDecoratorMetadata",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ affectsEmit: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files,
+ defaultValueDescription: "false",
+ },
+ // Advanced
+ {
+ name: "jsxFactory",
+ type: "string",
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h,
+ defaultValueDescription: "`React.createElement`"
+ },
+ {
+ name: "jsxFragmentFactory",
+ type: "string",
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment
+ },
+ {
+ name: "jsxImportSource",
+ type: "string",
+ affectsSemanticDiagnostics: true,
+ affectsEmit: true,
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk,
+ defaultValueDescription: "react"
+ },
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Enable_importing_json_files,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "out",
+ type: "string",
+ affectsEmit: true,
+ isFilePath: false,
+ // for correct behaviour, please use outFile
+ category: ts.Diagnostics.Backwards_Compatibility,
+ paramType: ts.Diagnostics.FILE,
+ transpileOptionValue: undefined,
+ description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead,
+ },
+ {
+ name: "reactNamespace",
+ type: "string",
+ affectsEmit: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit,
+ defaultValueDescription: "`React`",
+ },
+ {
+ name: "skipDefaultLibCheck",
+ type: "boolean",
+ category: ts.Diagnostics.Completeness,
+ description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "charset",
+ type: "string",
+ category: ts.Diagnostics.Backwards_Compatibility,
+ description: ts.Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files,
+ defaultValueDescription: "utf8"
+ },
+ {
+ name: "emitBOM",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "newLine",
+ type: new ts.Map(ts.getEntries({
+ crlf: 0 /* CarriageReturnLineFeed */,
+ lf: 1 /* LineFeed */
+ })),
+ affectsEmit: true,
+ paramType: ts.Diagnostics.NEWLINE,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Set_the_newline_character_for_emitting_files,
+ defaultValueDescription: ts.Diagnostics.Platform_specific
+ },
+ {
+ name: "noErrorTruncation",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Output_Formatting,
+ description: ts.Diagnostics.Disable_truncating_types_in_error_messages,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noLib",
+ type: "boolean",
+ category: ts.Diagnostics.Language_and_Environment,
+ affectsProgramStructure: true,
+ description: ts.Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts,
+ // We are not returning a sourceFile for lib file when asked by the program,
+ // so pass --noLib to avoid reporting a file not found error.
+ transpileOptionValue: true,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noResolve",
+ type: "boolean",
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.Modules,
+ description: ts.Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project,
+ // We are not doing a full typecheck, we are not resolving the whole context,
+ // so pass --noResolve to avoid reporting missing file errors.
+ transpileOptionValue: true,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "stripInternal",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "disableSizeLimit",
+ type: "boolean",
+ affectsProgramStructure: true,
+ category: ts.Diagnostics.Editor_Support,
+ description: ts.Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "disableSourceOfProjectReferenceRedirect",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Projects,
+ description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "disableSolutionSearching",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Projects,
+ description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "disableReferencedProjectLoad",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Projects,
+ description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "noImplicitUseStrict",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Backwards_Compatibility,
+ description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noEmitHelpers",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "noEmitOnError",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ transpileOptionValue: undefined,
+ description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "preserveConstEnums",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "declarationDir",
+ type: "string",
+ affectsEmit: true,
+ isFilePath: true,
+ paramType: ts.Diagnostics.DIRECTORY,
+ category: ts.Diagnostics.Emit,
+ transpileOptionValue: undefined,
+ description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files,
+ },
+ {
+ name: "skipLibCheck",
+ type: "boolean",
+ category: ts.Diagnostics.Completeness,
+ description: ts.Diagnostics.Skip_type_checking_all_d_ts_files,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "allowUnusedLabels",
+ type: "boolean",
+ affectsBindDiagnostics: true,
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Disable_error_reporting_for_unused_labels,
+ defaultValueDescription: "undefined"
+ },
+ {
+ name: "allowUnreachableCode",
+ type: "boolean",
+ affectsBindDiagnostics: true,
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Type_Checking,
+ description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code,
+ defaultValueDescription: "undefined"
+ },
+ {
+ name: "suppressExcessPropertyErrors",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Backwards_Compatibility,
+ description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "suppressImplicitAnyIndexErrors",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Backwards_Compatibility,
+ description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "forceConsistentCasingInFileNames",
+ type: "boolean",
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.Interop_Constraints,
+ description: ts.Diagnostics.Ensure_that_casing_is_correct_in_imports,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "maxNodeModuleJsDepth",
+ type: "number",
+ affectsModuleResolution: true,
+ category: ts.Diagnostics.JavaScript_Support,
+ description: ts.Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs,
+ defaultValueDescription: "0"
+ },
+ {
+ name: "noStrictGenericChecks",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ category: ts.Diagnostics.Backwards_Compatibility,
+ description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
+ defaultValueDescription: "false"
+ },
+ {
+ name: "useDefineForClassFields",
+ type: "boolean",
+ affectsSemanticDiagnostics: true,
+ affectsEmit: true,
+ category: ts.Diagnostics.Language_and_Environment,
+ description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields,
+ defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext
+ },
+ {
+ name: "preserveValueImports",
+ type: "boolean",
+ affectsEmit: true,
+ category: ts.Diagnostics.Emit,
+ description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed,
+ defaultValueDescription: "false",
+ },
+ {
+ name: "keyofStringsOnly",
+ type: "boolean",
+ category: ts.Diagnostics.Backwards_Compatibility,
+ description: ts.Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option,
+ defaultValueDescription: "false"
+ },
+ {
+ // A list of plugins to load in the language service
+ name: "plugins",
+ type: "list",
+ isTSConfigOnly: true,
+ element: {
+ name: "plugin",
+ type: "object"
+ },
+ description: ts.Diagnostics.List_of_language_service_plugins,
+ category: ts.Diagnostics.Editor_Support,
+ },
+ ];
+ /* @internal */
+ ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild, true), commandOptionsWithoutBuild, true);
+ /* @internal */
+ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
+ /* @internal */
+ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
+ /* @internal */
+ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
+ /* @internal */
+ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
+ return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
+ });
+ /* @internal */
+ ts.optionsAffectingProgramStructure = ts.optionDeclarations.filter(function (option) { return !!option.affectsProgramStructure; });
+ /* @internal */
+ ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
+ return ts.hasProperty(option, "transpileOptionValue");
+ });
+ // Build related options
+ /* @internal */
+ ts.optionsForBuild = [
+ {
+ name: "verbose",
+ shortName: "v",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Enable_verbose_logging,
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ {
+ name: "dry",
+ shortName: "d",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ {
+ name: "force",
+ shortName: "f",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ {
+ name: "clean",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
+ type: "boolean",
+ defaultValueDescription: "false",
}
- }
- function convertJsonOptionOfListType(option, values, basePath, errors) {
- return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
- }
- 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, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
- }
- if (excludeSpecs) {
- 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, 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 = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
- // 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();
- // Wildcard paths of json files (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 of *.json kind
- var wildCardJsonFileMap = 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);
- var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
- // 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];
- var file = ts.getNormalizedAbsolutePath(fileName, basePath);
- literalFileMap.set(keyMapper(file), file);
+ ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild, true), ts.optionsForBuild, true);
+ /* @internal */
+ ts.typeAcquisitionDeclarations = [
+ {
+ /* @deprecated typingOptions.enableAutoDiscovery
+ * Use typeAcquisition.enable instead.
+ */
+ name: "enableAutoDiscovery",
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ {
+ name: "enable",
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ {
+ name: "include",
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
}
- }
- var jsonOnlyIncludeRegexes;
- if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
- var _loop_5 = function (file) {
- if (ts.fileExtensionIs(file, ".json" /* Json */)) {
- // Valid only if *.json specified
- if (!jsonOnlyIncludeRegexes) {
- var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
- var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
- jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
- }
- var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
- if (includeIndex !== -1) {
- var key_1 = keyMapper(file);
- if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
- wildCardJsonFileMap.set(key_1, file);
- }
- }
- return "continue";
- }
- // 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)) {
- return "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)) {
- wildcardFileMap.set(key, file);
- }
- };
- for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
- var file = _b[_a];
- _loop_5(file);
+ },
+ {
+ name: "exclude",
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
}
- }
- var literalFiles = ts.arrayFrom(literalFileMap.values());
- var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
- return {
- fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
- wildcardDirectories: wildcardDirectories,
- spec: spec
- };
- }
- ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
- function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
- return specs.filter(function (spec) {
- var diag = specToDiagnostic(spec, allowTrailingRecursion);
- if (diag !== undefined) {
- errors.push(createDiagnostic(diag, spec));
+ },
+ {
+ name: "disableFilenameBasedTypeAcquisition",
+ type: "boolean",
+ defaultValueDescription: "false",
+ },
+ ];
+ /*@internal*/
+ function createOptionNameMap(optionDeclarations) {
+ var optionsNameMap = new ts.Map();
+ var shortOptionNames = new ts.Map();
+ ts.forEach(optionDeclarations, function (option) {
+ optionsNameMap.set(option.name.toLowerCase(), option);
+ if (option.shortName) {
+ shortOptionNames.set(option.shortName, option.name);
}
- return diag === undefined;
});
- function createDiagnostic(message, spec) {
- var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
- return element ?
- ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
- ts.createCompilerDiagnostic(message, spec);
- }
- }
- function specToDiagnostic(spec, allowTrailingRecursion) {
- if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
- return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
- }
- else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
- return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
- }
+ return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
}
- /**
- * 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 = {};
- if (include !== undefined) {
- var recursiveKeys = [];
- for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
- var file = include_1[_i];
- var spec = ts.normalizePath(ts.combinePaths(path, file));
- if (excludeRegex && excludeRegex.test(spec)) {
- continue;
- }
- var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
- if (match) {
- var key = match.key, flags = match.flags;
- var existingFlags = wildcardDirectories[key];
- if (existingFlags === undefined || existingFlags < flags) {
- wildcardDirectories[key] = flags;
- 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++) {
- var recursiveKey = recursiveKeys_1[_a];
- if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
- delete wildcardDirectories[key];
- }
- }
- }
- }
- }
- return wildcardDirectories;
+ ts.createOptionNameMap = createOptionNameMap;
+ var optionsNameMapCache;
+ /* @internal */
+ function getOptionsNameMap() {
+ return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
}
- function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
- var match = wildcardDirectoryPattern.exec(spec);
- if (match) {
+ ts.getOptionsNameMap = getOptionsNameMap;
+ var compilerOptionsAlternateMode = {
+ diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build,
+ getOptionsNameMap: getBuildOptionsNameMap
+ };
+ /* @internal */
+ ts.defaultInitCompilerOptions = {
+ module: ts.ModuleKind.CommonJS,
+ target: 3 /* ES2016 */,
+ strict: true,
+ esModuleInterop: true,
+ forceConsistentCasingInFileNames: true,
+ skipLibCheck: true
+ };
+ /* @internal */
+ function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
+ // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
+ if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
return {
- key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
- flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
+ enable: typeAcquisition.enableAutoDiscovery,
+ include: typeAcquisition.include || [],
+ exclude: typeAcquisition.exclude || []
};
}
- if (ts.isImplicitGlob(spec)) {
- 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 /* Highest */; i < adjustedExtensionPriority; i++) {
- var higherPriorityExtension = extensions[i];
- var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
- if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
- return true;
- }
- }
- 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);
- for (var i = nextExtensionPriority; i < extensions.length; i++) {
- var lowerPriorityExtension = extensions[i];
- var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
- wildcardFiles.delete(lowerPriorityPath);
- }
+ return typeAcquisition;
}
- /**
- * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
- * Also converts enum values back to strings.
- */
+ ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
/* @internal */
- function convertCompilerOptionsForTelemetry(opts) {
- var out = {};
- for (var key in opts) {
- if (opts.hasOwnProperty(key)) {
- var type = getOptionFromName(key);
- if (type !== undefined) { // Ignore unknown options
- out[key] = getOptionValueWithEmptyStrings(opts[key], type);
- }
- }
- }
- return out;
- }
- ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
- function getOptionValueWithEmptyStrings(value, option) {
- switch (option.type) {
- case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
- return "";
- case "string": // Could be any arbitrary string -- use empty string instead.
- return "";
- 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 : "";
- case "list":
- var elementType_1 = option.element;
- return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
- default:
- return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
- if (optionEnumValue === value) {
- return optionStringValue;
- }
- }); // TODO: GH#18217
- }
+ function createCompilerDiagnosticForInvalidCustomType(opt) {
+ return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
}
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- function trace(host) {
- host.trace(ts.formatMessage.apply(undefined, arguments));
+ ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
+ function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
+ var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'".concat(key, "'"); }).join(", ");
+ return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--".concat(opt.name), namesOfType);
}
- ts.trace = trace;
/* @internal */
- function isTraceEnabled(compilerOptions, host) {
- return !!compilerOptions.traceResolution && host.trace !== undefined;
- }
- ts.isTraceEnabled = isTraceEnabled;
- function withPackageId(packageInfo, r) {
- var packageId;
- if (r && packageInfo) {
- var packageJsonContent = packageInfo.packageJsonContent;
- if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
- packageId = {
- name: packageJsonContent.name,
- subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
- version: packageJsonContent.version
- };
- }
- }
- return r && { path: r.path, extension: r.ext, packageId: packageId };
- }
- function noPackageId(r) {
- return withPackageId(/*packageInfo*/ undefined, r);
- }
- function removeIgnoredPackageId(r) {
- if (r) {
- ts.Debug.assert(r.packageId === undefined);
- return { path: r.path, ext: r.extension };
- }
+ function parseCustomTypeOption(opt, value, errors) {
+ return convertJsonOptionOfCustomType(opt, ts.trimString(value || ""), errors);
}
- /**
- * 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["TSConfig"] = 3] = "TSConfig";
- Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
- })(Extensions || (Extensions = {}));
- /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
- function resolvedTypeScriptOnly(resolved) {
- if (!resolved) {
+ ts.parseCustomTypeOption = parseCustomTypeOption;
+ /* @internal */
+ function parseListTypeOption(opt, value, errors) {
+ if (value === void 0) { value = ""; }
+ value = ts.trimString(value);
+ if (ts.startsWith(value, "-")) {
return undefined;
}
- ts.Debug.assert(ts.extensionIsTS(resolved.extension));
- return { fileName: resolved.path, packageId: resolved.packageId };
+ if (value === "") {
+ return [];
+ }
+ var values = value.split(",");
+ switch (opt.element.type) {
+ case "number":
+ return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, parseInt(v), errors); });
+ case "string":
+ return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, v || "", errors); });
+ default:
+ return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
+ }
}
- function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
+ ts.parseListTypeOption = parseListTypeOption;
+ function getOptionName(option) {
+ return option.name;
+ }
+ function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
var _a;
- if (resultFromCache) {
- (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
- return resultFromCache;
+ if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) {
+ return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption);
}
+ var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
+ return possibleOption ?
+ createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
+ createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
+ }
+ /*@internal*/
+ function parseCommandLineWorker(diagnostics, commandLine, readFile) {
+ var options = {};
+ var watchOptions;
+ var fileNames = [];
+ var errors = [];
+ parseStrings(commandLine);
return {
- resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
- failedLookupLocations: failedLookupLocations
+ options: options,
+ watchOptions: watchOptions,
+ fileNames: fileNames,
+ errors: errors
};
- }
- function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
- if (!ts.hasProperty(jsonContent, fieldName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
+ function parseStrings(args) {
+ var i = 0;
+ while (i < args.length) {
+ var s = args[i];
+ i++;
+ if (s.charCodeAt(0) === 64 /* at */) {
+ parseResponseFile(s.slice(1));
+ }
+ else if (s.charCodeAt(0) === 45 /* minus */) {
+ var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
+ var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
+ if (opt) {
+ i = parseOptionValue(args, i, diagnostics, opt, options, errors);
+ }
+ else {
+ var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
+ if (watchOpt) {
+ i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
+ }
+ else {
+ errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
+ }
+ }
+ }
+ else {
+ fileNames.push(s);
+ }
}
- return;
}
- var value = jsonContent[fieldName];
- if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
- if (state.traceEnabled) {
- // eslint-disable-next-line no-null/no-null
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
+ function parseResponseFile(fileName) {
+ var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
+ if (!ts.isString(text)) {
+ errors.push(text);
+ return;
}
- return;
- }
- return value;
- }
- function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
- var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
- if (fileName === undefined) {
- return;
- }
- if (!fileName) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
+ var args = [];
+ var pos = 0;
+ while (true) {
+ while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
+ pos++;
+ if (pos >= text.length)
+ break;
+ var start = pos;
+ if (text.charCodeAt(start) === 34 /* doubleQuote */) {
+ pos++;
+ while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
+ pos++;
+ if (pos < text.length) {
+ args.push(text.substring(start + 1, pos));
+ pos++;
+ }
+ else {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
+ }
+ }
+ else {
+ while (text.charCodeAt(pos) > 32 /* space */)
+ pos++;
+ args.push(text.substring(start, pos));
+ }
}
- return;
- }
- var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
- }
- return path;
- }
- function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
- return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
- || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
- }
- function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
- return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
- }
- function readPackageJsonMainField(jsonContent, baseDirectory, state) {
- return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
- }
- function readPackageJsonTypesVersionsField(jsonContent, state) {
- var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
- if (typesVersions === undefined)
- return;
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
+ parseStrings(args);
}
- return typesVersions;
}
- function readPackageJsonTypesVersionPaths(jsonContent, state) {
- var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
- if (typesVersions === undefined)
- return;
- if (state.traceEnabled) {
- for (var key in typesVersions) {
- if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
- trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
+ ts.parseCommandLineWorker = parseCommandLineWorker;
+ function parseOptionValue(args, i, diagnostics, opt, options, errors) {
+ if (opt.isTSConfigOnly) {
+ var optValue = args[i];
+ if (optValue === "null") {
+ options[opt.name] = undefined;
+ i++;
+ }
+ else if (opt.type === "boolean") {
+ if (optValue === "false") {
+ options[opt.name] = validateJsonOptionValue(opt, /*value*/ false, errors);
+ i++;
+ }
+ else {
+ if (optValue === "true")
+ i++;
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
}
}
- }
- var result = getPackageJsonTypesVersionsPaths(typesVersions);
- if (!result) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
+ else {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
+ if (optValue && !ts.startsWith(optValue, "-"))
+ i++;
}
- return;
}
- var bestVersionKey = result.version, bestVersionPaths = result.paths;
- if (typeof bestVersionPaths !== "object") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
+ 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(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
+ }
+ if (args[i] !== "null") {
+ switch (opt.type) {
+ case "number":
+ options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors);
+ i++;
+ break;
+ case "boolean":
+ // boolean flag has optional value true, false, others
+ var optValue = args[i];
+ options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors);
+ // consume next argument as boolean flag value
+ if (optValue === "false" || optValue === "true") {
+ i++;
+ }
+ break;
+ case "string":
+ options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors);
+ i++;
+ break;
+ case "list":
+ var result = parseListTypeOption(opt, args[i], errors);
+ options[opt.name] = result || [];
+ if (result) {
+ 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++;
+ break;
+ }
+ }
+ else {
+ options[opt.name] = undefined;
+ i++;
}
- return;
}
- return result;
+ return i;
}
- var typeScriptVersion;
- /* @internal */
- function getPackageJsonTypesVersionsPaths(typesVersions) {
- if (!typeScriptVersion)
- typeScriptVersion = new ts.Version(ts.version);
- for (var key in typesVersions) {
- if (!ts.hasProperty(typesVersions, key))
- continue;
- var keyRange = ts.VersionRange.tryParse(key);
- if (keyRange === undefined) {
- continue;
- }
- // return the first entry whose range matches the current compiler version.
- if (keyRange.test(typeScriptVersion)) {
- return { version: key, paths: typesVersions[key] };
+ /*@internal*/
+ ts.compilerOptionsDidYouMeanDiagnostics = {
+ alternateMode: compilerOptionsAlternateMode,
+ getOptionsNameMap: getOptionsNameMap,
+ optionDeclarations: ts.optionDeclarations,
+ unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
+ unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
+ optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
+ };
+ function parseCommandLine(commandLine, readFile) {
+ return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
+ }
+ ts.parseCommandLine = parseCommandLine;
+ /** @internal */
+ function getOptionFromName(optionName, allowShort) {
+ return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
+ }
+ ts.getOptionFromName = getOptionFromName;
+ function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
+ if (allowShort === void 0) { allowShort = false; }
+ optionName = optionName.toLowerCase();
+ var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
+ // Try to translate short option names to their full equivalents.
+ if (allowShort) {
+ var short = shortOptionNames.get(optionName);
+ if (short !== undefined) {
+ optionName = short;
}
}
+ return optionsNameMap.get(optionName);
}
- ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
- function getEffectiveTypeRoots(options, host) {
- if (options.typeRoots) {
- return options.typeRoots;
+ var buildOptionsNameMapCache;
+ function getBuildOptionsNameMap() {
+ return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
+ }
+ var buildOptionsAlternateMode = {
+ diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build,
+ getOptionsNameMap: getOptionsNameMap
+ };
+ var buildOptionsDidYouMeanDiagnostics = {
+ alternateMode: buildOptionsAlternateMode,
+ getOptionsNameMap: getBuildOptionsNameMap,
+ optionDeclarations: ts.buildOpts,
+ unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
+ unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
+ optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
+ };
+ /*@internal*/
+ function parseBuildCommand(args) {
+ var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
+ var buildOptions = options;
+ if (projects.length === 0) {
+ // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
+ projects.push(".");
}
- var currentDirectory;
- if (options.configFilePath) {
- currentDirectory = ts.getDirectoryPath(options.configFilePath);
+ // Nonsensical combinations
+ if (buildOptions.clean && buildOptions.force) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
}
- else if (host.getCurrentDirectory) {
- currentDirectory = host.getCurrentDirectory();
+ if (buildOptions.clean && buildOptions.verbose) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
}
- if (currentDirectory !== undefined) {
- return getDefaultTypeRoots(currentDirectory, host);
+ if (buildOptions.clean && buildOptions.watch) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
+ }
+ if (buildOptions.watch && buildOptions.dry) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
}
+ return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
}
- ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
+ ts.parseBuildCommand = parseBuildCommand;
+ /* @internal */
+ function getDiagnosticText(_message) {
+ var _args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ _args[_i - 1] = arguments[_i];
+ }
+ var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
+ return diagnostic.messageText;
+ }
+ ts.getDiagnosticText = getDiagnosticText;
/**
- * Returns the path to every node_modules/@types directory from some ancestor directory.
- * Returns undefined if there are none.
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
*/
- 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) {
- var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
- if (host.directoryExists(atTypes)) {
- (typeRoots || (typeRoots = [])).push(atTypes);
- }
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
+ var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
+ if (!ts.isString(configFileText)) {
+ host.onUnRecoverableConfigFileDiagnostic(configFileText);
return undefined;
- });
- return typeRoots;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
+ result.resolvedPath = result.path;
+ result.originalFileName = result.fileName;
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd),
+ /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
}
- var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
- * @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.
+ * Read tsconfig.json file
+ * @param fileName The path to the config file
*/
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
- var traceEnabled = isTraceEnabled(options, host);
- if (redirectedReference) {
- options = redirectedReference.commandLine.options;
- }
- var failedLookupLocations = [];
- var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
- var typeRoots = getEffectiveTypeRoots(options, host);
- if (traceEnabled) {
- if (containingFile === undefined) {
- if (typeRoots === undefined) {
- trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
- }
- else {
- trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
- }
- }
- else {
- if (typeRoots === undefined) {
- trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
- }
- else {
- trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
- }
- }
- if (redirectedReference) {
- trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
- }
- }
- var resolved = primaryLookup();
- var primary = true;
- if (!resolved) {
- resolved = secondaryLookup();
- primary = false;
+ 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 {
+ config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined),
+ error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
+ };
+ }
+ 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) : { fileName: fileName, parseDiagnostics: [textOrDiagnostic] };
+ }
+ ts.readJsonConfigFile = readJsonConfigFile;
+ /*@internal*/
+ function tryReadFile(fileName, readFile) {
+ var text;
+ try {
+ text = readFile(fileName);
}
- var resolvedTypeReferenceDirective;
- if (resolved) {
- var fileName = resolved.fileName, packageId = resolved.packageId;
- var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
- if (traceEnabled) {
- if (packageId) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary);
- }
- else {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
- }
- }
- resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
+ catch (e) {
+ return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
}
- 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(", "));
- }
- return ts.firstDefined(typeRoots, function (typeRoot) {
- var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
- var candidateDirectory = ts.getDirectoryPath(candidate);
- var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
- if (!directoryExists && traceEnabled) {
- trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
- }
- return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
- });
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
- }
- }
+ return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
+ }
+ ts.tryReadFile = tryReadFile;
+ function commandLineOptionsToMap(options) {
+ return ts.arrayToMap(options, getOptionName);
+ }
+ var typeAcquisitionDidYouMeanDiagnostics = {
+ optionDeclarations: ts.typeAcquisitionDeclarations,
+ unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
+ unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
+ };
+ var watchOptionsNameMapCache;
+ function getWatchOptionsNameMap() {
+ return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
+ }
+ var watchOptionsDidYouMeanDiagnostics = {
+ getOptionsNameMap: getWatchOptionsNameMap,
+ optionDeclarations: ts.optionsForWatch,
+ unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
+ unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
+ optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
+ };
+ var commandLineCompilerOptionsMapCache;
+ function getCommandLineCompilerOptionsMap() {
+ return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
+ }
+ var commandLineWatchOptionsMapCache;
+ function getCommandLineWatchOptionsMap() {
+ return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
+ }
+ var commandLineTypeAcquisitionMapCache;
+ function getCommandLineTypeAcquisitionMap() {
+ return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
+ }
+ var _tsconfigRootOptions;
+ function getTsconfigRootOptionsMap() {
+ if (_tsconfigRootOptions === undefined) {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: getCommandLineCompilerOptionsMap(),
+ extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
+ },
+ {
+ name: "watchOptions",
+ type: "object",
+ elementOptions: getCommandLineWatchOptionsMap(),
+ extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: getCommandLineTypeAcquisitionMap(),
+ extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: getCommandLineTypeAcquisitionMap(),
+ extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
+ },
+ {
+ name: "extends",
+ type: "string",
+ category: ts.Diagnostics.File_Management,
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ },
+ category: ts.Diagnostics.Projects,
+ },
+ {
+ name: "files",
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ },
+ category: ts.Diagnostics.File_Management,
+ },
+ {
+ name: "include",
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ },
+ category: ts.Diagnostics.File_Management,
+ defaultValueDescription: ts.Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk
+ },
+ {
+ name: "exclude",
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ },
+ category: ts.Diagnostics.File_Management,
+ defaultValueDescription: ts.Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
- 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 = void 0;
- if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
- var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
- result = searchResult && searchResult.value;
- }
- else {
- var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
- result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
- }
- var resolvedFile = resolvedTypeScriptOnly(result);
- if (!resolvedFile && traceEnabled) {
- trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
- }
- return resolvedFile;
- }
- else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ return _tsconfigRootOptions;
+ }
+ function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) {
+ var _a;
+ var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression;
+ var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined;
+ if (rootExpression && rootExpression.kind !== 204 /* ObjectLiteralExpression */) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json"));
+ // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by
+ // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that
+ // array is a well-formed configuration object, made into an array element by stray characters.
+ if (ts.isArrayLiteralExpression(rootExpression)) {
+ var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression);
+ if (firstObject) {
+ return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator);
}
}
+ return {};
}
+ return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator);
}
- 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.
+ * Convert the json syntax tree into the json value
*/
- 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);
- if (typeRoots) {
- for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
- var root = typeRoots_1[_i];
- if (host.directoryExists(root)) {
- for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
- var typeDirectivePath = _b[_a];
- var normalized = ts.normalizePath(typeDirectivePath);
- var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
- // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
- // See `createNotNeededPackageJSON` in the types-publisher` repo.
- // eslint-disable-next-line no-null/no-null
- var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
- if (!isNotNeededPackage) {
- var baseFileName = ts.getBaseFileName(normalized);
- // At this stage, skip results with leading dot.
- if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
- // Return just the type directive names
- result.push(baseFileName);
- }
- }
- }
- }
- }
- }
- }
- return result;
- }
- ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
- return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
- }
- ts.createModuleResolutionCache = createModuleResolutionCache;
- /*@internal*/
- function createCacheWithRedirects(options) {
- var ownMap = ts.createMap();
- var redirectsMap = ts.createMap();
- return {
- ownMap: ownMap,
- redirectsMap: redirectsMap,
- getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
- clear: clear,
- setOwnOptions: setOwnOptions,
- setOwnMap: setOwnMap
- };
- function setOwnOptions(newOptions) {
- options = newOptions;
- }
- function setOwnMap(newOwnMap) {
- ownMap = newOwnMap;
- }
- function getOrCreateMapOfCacheRedirects(redirectedReference) {
- if (!redirectedReference) {
- return ownMap;
- }
- var path = redirectedReference.sourceFile.path;
- var redirects = redirectsMap.get(path);
- if (!redirects) {
- // Reuse map if redirected reference map uses same resolution
- redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
- redirectsMap.set(path, redirects);
- }
- return redirects;
- }
- function clear() {
- ownMap.clear();
- redirectsMap.clear();
- }
+ function convertToObject(sourceFile, errors) {
+ var _a;
+ return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
}
- ts.createCacheWithRedirects = createCacheWithRedirects;
+ 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 createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
- return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
- function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
- var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
- return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
- }
- function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
- ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
- return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
+ function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!rootExpression) {
+ return returnValue ? {} : undefined;
}
- function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
- var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
- var result = cache.get(key);
- if (!result) {
- result = create();
- cache.set(key, result);
- }
- return result;
+ return convertPropertyValueToJson(rootExpression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- function createPerModuleNameCache() {
- var directoryPathMap = ts.createMap();
- return { get: get, set: set };
- 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.originalPath || result.resolvedModule.resolvedFileName);
- // find common prefix between directory and resolved file name
- // this common prefix should be the shortest path that has the same resolution
- // directory: /a/b/c/d/e
- // resolvedFileName: /a/b/foo.d.ts
- // commonPrefix: /a/b
- // for failed lookups cache the result for every directory up to root
- var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
- var current = path;
- while (current !== commonPrefix) {
- var parent = ts.getDirectoryPath(current);
- if (parent === current || directoryPathMap.has(parent)) {
- break;
- }
- directoryPathMap.set(parent, result);
- current = parent;
+ function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
+ var result = returnValue ? {} : undefined;
+ var _loop_4 = function (element) {
+ if (element.kind !== 294 /* PropertyAssignment */) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
+ return "continue";
}
- }
- function getCommonPrefix(directory, resolution) {
- var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
- // find first position where directory and resolution differs
- var i = 0;
- var limit = Math.min(directory.length, resolutionDirectory.length);
- while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
- i++;
+ if (element.questionToken) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
}
- if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
- return directory;
+ if (!isDoubleQuotedString(element.name)) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
}
- var rootLength = ts.getRootLength(directory);
- if (i < rootLength) {
- return undefined;
+ var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
+ var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
+ var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
+ if (keyText && extraKeyDiagnostics && !option) {
+ if (knownOptions) {
+ errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
+ }
+ else {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
+ }
}
- var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
- if (sep === -1) {
- return undefined;
+ var value = convertPropertyValueToJson(element.initializer, option);
+ if (typeof keyText !== "undefined") {
+ 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);
+ }
+ }
+ }
}
- return directory.substr(0, Math.max(sep, rootLength));
+ };
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var element = _a[_i];
+ _loop_4(element);
}
+ return result;
}
- }
- ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
- function resolveModuleNameFromCache(moduleName, containingFile, cache) {
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
- return perFolderCache && perFolderCache.get(moduleName);
- }
- ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (redirectedReference) {
- compilerOptions = redirectedReference.commandLine.options;
- }
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
- if (redirectedReference) {
- trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
+ function convertArrayLiteralExpressionToJson(elements, elementOption) {
+ if (!returnValue) {
+ elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return undefined;
}
+ // Filter out invalid values
+ return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
}
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
- var result = perFolderCache && perFolderCache.get(moduleName);
- if (result) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
+ function convertPropertyValueToJson(valueExpression, option) {
+ var invalidReported;
+ switch (valueExpression.kind) {
+ case 110 /* TrueKeyword */:
+ reportInvalidOptionValue(option && option.type !== "boolean");
+ return validateValue(/*value*/ true);
+ case 95 /* FalseKeyword */:
+ reportInvalidOptionValue(option && option.type !== "boolean");
+ return validateValue(/*value*/ false);
+ case 104 /* NullKeyword */:
+ reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
+ return validateValue(/*value*/ null); // eslint-disable-line no-null/no-null
+ case 10 /* StringLiteral */:
+ if (!isDoubleQuotedString(valueExpression)) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
+ }
+ reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
+ 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); }));
+ invalidReported = true;
+ }
+ }
+ return validateValue(text);
+ case 8 /* NumericLiteral */:
+ reportInvalidOptionValue(option && option.type !== "number");
+ return validateValue(Number(valueExpression.text));
+ case 218 /* PrefixUnaryExpression */:
+ if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
+ break; // not valid JSON syntax
+ }
+ reportInvalidOptionValue(option && option.type !== "number");
+ return validateValue(-Number(valueExpression.operand.text));
+ case 204 /* 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, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
+ return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName));
+ }
+ else {
+ return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
+ /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined));
+ }
+ case 203 /* ArrayLiteralExpression */:
+ reportInvalidOptionValue(option && option.type !== "list");
+ return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element));
}
- }
- else {
- var moduleResolution = compilerOptions.moduleResolution;
- if (moduleResolution === undefined) {
- moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
- }
+ // Not in expected format
+ if (option) {
+ reportInvalidOptionValue(/*isError*/ true);
}
else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
- }
- }
- ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
- break;
- default:
- return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
+ 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));
}
- if (result && result.resolvedModule)
- ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
- ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
- if (perFolderCache) {
- perFolderCache.set(moduleName, result);
- if (!ts.isExternalModuleNameRelative(moduleName)) {
- // put result in per-module name cache
- cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
+ return undefined;
+ function validateValue(value) {
+ var _a;
+ if (!invalidReported) {
+ var diagnostic = (_a = option === null || option === void 0 ? void 0 : option.extraValidation) === null || _a === void 0 ? void 0 : _a.call(option, value);
+ if (diagnostic) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile.apply(void 0, __spreadArray([sourceFile, valueExpression], diagnostic, false)));
+ return undefined;
+ }
}
+ return value;
}
- }
- if (traceEnabled) {
- if (result.resolvedModule) {
- if (result.resolvedModule.packageId) {
- trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, ts.packageIdToString(result.resolvedModule.packageId));
- }
- else {
- trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
+ function reportInvalidOptionValue(isError) {
+ if (isError) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
+ invalidReported = true;
}
}
- else {
- trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
+ }
+ function isDoubleQuotedString(node) {
+ return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
+ }
+ }
+ ts.convertToObjectWorker = convertToObjectWorker;
+ function getCompilerOptionValueTypeString(option) {
+ return option.type === "list" ?
+ "Array" :
+ ts.isString(option.type) ? option.type : "string";
+ }
+ function isCompilerOptionsValue(option, value) {
+ if (option) {
+ if (isNullOrUndefined(value))
+ return true; // All options are undefinable/nullable
+ if (option.type === "list") {
+ return ts.isArray(value);
}
+ var expectedType = ts.isString(option.type) ? option.type : "string";
+ return typeof value === expectedType;
}
- return result;
+ return false;
}
- 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/ to '/root/components/folder1/',
- * // it is rooted so it will be final candidate location
- * }
- *
- * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
- * they were in the same location. For example lets say there are two files
- * '/local/src/content/file1.ts'
- * '/shared/components/contracts/src/content/protocols/file2.ts'
- * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
- * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
- * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
- * root dirs were merged together.
- * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
- * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
- * '/local/src/content/protocols/file2' and try to load it - failure.
- * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
- * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
- * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
+ * Generate an uncommented, complete tsconfig for use with "--showConfig"
+ * @param configParseResult options to be generated into tsconfig.json
+ * @param configFileName name of the parsed config file - output paths will be generated relative to this
+ * @param host provides current directory and case sensitivity services
*/
- function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
- var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
- if (resolved)
- return resolved.value;
- if (!ts.isExternalModuleNameRelative(moduleName)) {
- return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
- }
- else {
- return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
- }
+ /** @internal */
+ function convertToTSConfig(configParseResult, configFileName, host) {
+ var _a, _b, _c;
+ var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
+ var files = ts.map(ts.filter(configParseResult.fileNames, !((_b = (_a = configParseResult.options.configFile) === null || _a === void 0 ? void 0 : _a.configFileSpecs) === null || _b === void 0 ? void 0 : _b.validatedIncludeSpecs) ? ts.returnTrue : matchesSpecs(configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
+ var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
+ var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
+ var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (((_c = configParseResult.options.configFile) === null || _c === void 0 ? void 0 : _c.configFileSpecs) ? {
+ include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs),
+ exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs
+ } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
+ return config;
}
- function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
- var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
- if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
- trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
- }
- return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
- }
+ ts.convertToTSConfig = convertToTSConfig;
+ function optionMapToObject(optionMap) {
+ return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
+ var _a;
+ return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
+ }, {}));
}
- function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
- if (!state.compilerOptions.rootDirs) {
+ function filterSameAsDefaultInclude(specs) {
+ if (!ts.length(specs))
return undefined;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var matchedRootDir;
- var matchedNormalizedPrefix;
- for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
- var rootDir = _a[_i];
- // rootDirs are expected to be absolute
- // in case of tsconfig.json this will happen automatically - compiler will expand relative names
- // using location of tsconfig.json as base location
- var normalizedRoot = ts.normalizePath(rootDir);
- if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
- normalizedRoot += ts.directorySeparator;
- }
- var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
- (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
- }
- if (isLongestMatchingPrefix) {
- matchedNormalizedPrefix = normalizedRoot;
- matchedRootDir = rootDir;
+ if (ts.length(specs) !== 1)
+ return specs;
+ if (specs[0] === "**/*")
+ return undefined;
+ return specs;
+ }
+ function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
+ if (!includeSpecs)
+ return ts.returnTrue;
+ var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
+ var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
+ var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
+ if (includeRe) {
+ if (excludeRe) {
+ return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
}
+ return function (path) { return !includeRe.test(path); };
}
- if (matchedNormalizedPrefix) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
- }
- var suffix = candidate.substr(matchedNormalizedPrefix.length);
- // first - try to load from a initial location
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
- }
- var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
- if (resolvedFileName) {
- return resolvedFileName;
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
- }
- // then try to resolve using remaining entries in rootDirs
- for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
- var rootDir = _c[_b];
- if (rootDir === matchedRootDir) {
- // skip the initially matched entry
- continue;
- }
- var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
- }
- var baseDirectory = ts.getDirectoryPath(candidate_1);
- var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
- if (resolvedFileName_1) {
- return resolvedFileName_1;
- }
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
- }
+ if (excludeRe) {
+ return function (path) { return excludeRe.test(path); };
}
- return undefined;
+ return ts.returnTrue;
}
- function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
- var baseUrl = state.compilerOptions.baseUrl;
- if (!baseUrl) {
+ function getCustomTypeMapOfCommandLineOption(optionDefinition) {
+ if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
+ // this is of a type CommandLineOptionOfPrimitiveType
return undefined;
}
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
- }
- var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
+ else if (optionDefinition.type === "list") {
+ return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
}
- return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- }
- /**
- * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
- * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
- * Throws an error if the module can't be resolved.
- */
- /* @internal */
- function resolveJSModule(moduleName, initialDir, host) {
- var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
- if (!resolvedModule) {
- throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
+ else {
+ return optionDefinition.type;
}
- return resolvedModule.resolvedFileName;
}
- ts.resolveJSModule = resolveJSModule;
- /* @internal */
- function tryResolveJSModule(moduleName, initialDir, host) {
- var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
- return resolvedModule && resolvedModule.resolvedFileName;
+ 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;
+ }
+ });
}
- ts.tryResolveJSModule = tryResolveJSModule;
- var jsOnlyExtensions = [Extensions.JavaScript];
- var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
- var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
- var tsconfigExtensions = [Extensions.TSConfig];
- function tryResolveJSModuleWorker(moduleName, initialDir, host) {
- return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
+ function serializeCompilerOptions(options, pathOptions) {
+ return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
}
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
- return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
+ function serializeWatchOptions(options) {
+ return serializeOptionBaseObject(options, getWatchOptionsNameMap());
}
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
- function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
- var _a, _b;
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
- var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
- return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache);
- function tryResolve(extensions) {
- var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
- var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
- if (resolved) {
- return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
- }
- if (!ts.isExternalModuleNameRelative(moduleName)) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
+ function serializeOptionBaseObject(options, _a, pathOptions) {
+ var optionsNameMap = _a.optionsNameMap;
+ var result = new ts.Map();
+ var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
+ var _loop_5 = 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 || optionsNameMap.get(name).category === ts.Diagnostics.Output_Formatting)) {
+ return "continue";
}
- var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
- if (!resolved_1)
- return undefined;
- var resolvedValue = resolved_1.value;
- if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
- var path = realPath(resolvedValue.path, host, traceEnabled);
- var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
- resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
+ var value = options[name];
+ var optionDefinition = optionsNameMap.get(name.toLowerCase());
+ 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
+ if (pathOptions && optionDefinition.isFilePath) {
+ result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
+ }
+ else {
+ result.set(name, value);
+ }
+ }
+ else {
+ if (optionDefinition.type === "list") {
+ 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));
+ }
+ }
}
- // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
- return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
- }
- else {
- var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
- var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
- // Treat explicit "node_modules" import as an external library import.
- return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
}
+ };
+ for (var name in options) {
+ _loop_5(name);
}
+ return result;
}
- function realPath(path, host, traceEnabled) {
- if (!host.realpath) {
- return path;
- }
- var real = ts.normalizePath(host.realpath(path));
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
- }
- ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
- return real;
- }
- function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
+ /**
+ * Generate a list of the compiler options whose value is not the default.
+ * @param options compilerOptions to be evaluated.
+ /** @internal */
+ function getCompilerOptionsDiffValue(options, newLine) {
+ var compilerOptionsMap = getSerializedCompilerOption(options);
+ return getOverwrittenDefaultOptions();
+ function makePadding(paddingLength) {
+ return Array(paddingLength + 1).join(" ");
}
- if (!ts.hasTrailingDirectorySeparator(candidate)) {
- if (!onlyRecordFailures) {
- var parentOfCandidate = ts.getDirectoryPath(candidate);
- if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
- }
- onlyRecordFailures = true;
+ function getOverwrittenDefaultOptions() {
+ var result = [];
+ var tab = makePadding(2);
+ commandOptionsWithoutBuild.forEach(function (cmd) {
+ if (!compilerOptionsMap.has(cmd.name)) {
+ return;
}
- }
- var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
- if (resolvedFromFile) {
- var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
- var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
- return withPackageId(packageInfo, resolvedFromFile);
- }
- }
- if (!onlyRecordFailures) {
- var candidateExists = ts.directoryProbablyExists(candidate, state.host);
- if (!candidateExists) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
+ var newValue = compilerOptionsMap.get(cmd.name);
+ var defaultValue = getDefaultValueForOption(cmd);
+ if (newValue !== defaultValue) {
+ result.push("".concat(tab).concat(cmd.name, ": ").concat(newValue));
}
- onlyRecordFailures = true;
- }
+ else if (ts.hasProperty(ts.defaultInitCompilerOptions, cmd.name)) {
+ result.push("".concat(tab).concat(cmd.name, ": ").concat(defaultValue));
+ }
+ });
+ return result.join(newLine) + newLine;
}
- return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
}
- /*@internal*/
- ts.nodeModulesPathPart = "/node_modules/";
- /*@internal*/
- function pathContainsNodeModules(path) {
- return ts.stringContains(path, ts.nodeModulesPathPart);
- }
- ts.pathContainsNodeModules = pathContainsNodeModules;
+ ts.getCompilerOptionsDiffValue = getCompilerOptionsDiffValue;
/**
- * This will be called on the successfully resolved path from `loadModuleFromFile`.
- * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
- *
- * packageDirectory is the directory of the package itself.
- * For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
- * For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
- * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
- * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
+ * Get the compiler options to be written into the tsconfig.json.
+ * @param options commandlineOptions to be included in the compileOptions.
*/
- function parseNodeModuleFromPath(resolved) {
- var path = ts.normalizePath(resolved.path);
- var idx = path.lastIndexOf(ts.nodeModulesPathPart);
- if (idx === -1) {
- return undefined;
- }
- var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
- var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
- if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
- indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
- }
- return path.slice(0, indexAfterPackageName);
- }
- function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
- var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
- return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
- }
- function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
- return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
+ function getSerializedCompilerOption(options) {
+ var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
+ return serializeCompilerOptions(compilerOptions);
}
/**
- * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
- * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
+ * 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
*/
- function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
- if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
- var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
- return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
+ /* @internal */
+ function generateTSConfig(options, fileNames, newLine) {
+ var compilerOptionsMap = getSerializedCompilerOption(options);
+ return writeConfigurations();
+ function makePadding(paddingLength) {
+ return Array(paddingLength + 1).join(" ");
}
- // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
- var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
- if (resolvedByAddingExtension) {
- return resolvedByAddingExtension;
+ function isAllowedOptionForOutput(_a) {
+ var category = _a.category, name = _a.name, isCommandLineOnly = _a.isCommandLineOnly;
+ // Skip options which do not have a category or have categories which are more niche
+ var categoriesToSkip = [ts.Diagnostics.Command_line_Options, ts.Diagnostics.Editor_Support, ts.Diagnostics.Compiler_Diagnostics, ts.Diagnostics.Backwards_Compatibility, ts.Diagnostics.Watch_and_Build_Modes, ts.Diagnostics.Output_Formatting];
+ return !isCommandLineOnly && category !== undefined && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name));
}
- // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
- // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
- if (ts.hasJSFileExtension(candidate)) {
- var extensionless = ts.removeFileExtension(candidate);
- if (state.traceEnabled) {
- var extension = candidate.substring(extensionless.length);
- trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
+ 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];
+ var category = option.category;
+ if (isAllowedOptionForOutput(option)) {
+ categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
+ }
}
- return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
- }
- }
- /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
- function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
+ // Serialize all options and their descriptions
+ var marginLength = 0;
+ var seenKnownKeys = 0;
+ var entries = [];
+ categorizedOptions.forEach(function (options, category) {
+ if (entries.length !== 0) {
+ entries.push({ value: "" });
+ }
+ entries.push({ value: "/* ".concat(category, " */") });
+ for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
+ var option = options_1[_i];
+ var optionName = void 0;
+ if (compilerOptionsMap.has(option.name)) {
+ optionName = "\"".concat(option.name, "\": ").concat(JSON.stringify(compilerOptionsMap.get(option.name))).concat((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
+ }
+ else {
+ optionName = "// \"".concat(option.name, "\": ").concat(JSON.stringify(getDefaultValueForOption(option)), ",");
+ }
+ entries.push({
+ value: optionName,
+ description: "/* ".concat(option.description && ts.getLocaleSpecificMessage(option.description) || option.name, " */")
+ });
+ marginLength = Math.max(optionName.length, marginLength);
+ }
+ });
+ // Write the output
+ var tab = makePadding(2);
+ var result = [];
+ result.push("{");
+ result.push("".concat(tab, "\"compilerOptions\": {"));
+ result.push("".concat(tab).concat(tab, "/* ").concat(ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file), " */"));
+ result.push("");
+ // Print out each row, aligning all the descriptions on the same column.
+ for (var _a = 0, entries_2 = entries; _a < entries_2.length; _a++) {
+ var entry = entries_2[_a];
+ var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
+ result.push(value && "".concat(tab).concat(tab).concat(value).concat(description && (makePadding(marginLength - value.length + 2) + description)));
}
- }
- switch (extensions) {
- case Extensions.DtsOnly:
- return tryExtension(".d.ts" /* Dts */);
- case Extensions.TypeScript:
- return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
- case Extensions.JavaScript:
- return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
- case Extensions.TSConfig:
- case Extensions.Json:
- return tryExtension(".json" /* Json */);
- }
- function tryExtension(ext) {
- var path = tryFile(candidate + ext, onlyRecordFailures, state);
- return path === undefined ? undefined : { path: path, ext: ext };
- }
- }
- /** Return the file if it exists. */
- function tryFile(fileName, onlyRecordFailures, state) {
- if (!onlyRecordFailures) {
- if (state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ if (fileNames.length) {
+ result.push("".concat(tab, "},"));
+ result.push("".concat(tab, "\"files\": ["));
+ for (var i = 0; i < fileNames.length; i++) {
+ result.push("".concat(tab).concat(tab).concat(JSON.stringify(fileNames[i])).concat(i === fileNames.length - 1 ? "" : ","));
}
- return fileName;
+ result.push("".concat(tab, "]"));
}
else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
- }
+ result.push("".concat(tab, "}"));
}
+ result.push("}");
+ return result.join(newLine) + newLine;
}
- state.failedLookupLocations.push(fileName);
- return undefined;
- }
- function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
- if (considerPackageJson === void 0) { considerPackageJson = true; }
- var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
- var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
- var versionPaths = packageInfo && packageInfo.versionPaths;
- return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
- function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
- var host = state.host, traceEnabled = state.traceEnabled;
- var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
- var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
- if (directoryExists && host.fileExists(packageJsonPath)) {
- var packageJsonContent = ts.readJson(packageJsonPath, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ ts.generateTSConfig = generateTSConfig;
+ /* @internal */
+ function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
+ var result = {};
+ var optionsNameMap = getOptionsNameMap().optionsNameMap;
+ for (var name in options) {
+ if (ts.hasProperty(options, name)) {
+ result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
}
- var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
- return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
}
- else {
- if (directoryExists && traceEnabled) {
- trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
- }
- // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
- state.failedLookupLocations.push(packageJsonPath);
+ if (result.configFilePath) {
+ result.configFilePath = toAbsolutePath(result.configFilePath);
}
+ return result;
}
- function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
- var packageFile;
- if (jsonContent) {
- switch (extensions) {
- case Extensions.JavaScript:
- case Extensions.Json:
- packageFile = readPackageJsonMainField(jsonContent, candidate, state);
- break;
- case Extensions.TypeScript:
- // When resolving typescript modules, try resolving using main field as well
- packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
- break;
- case Extensions.DtsOnly:
- packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
- break;
- case Extensions.TSConfig:
- packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
- break;
- default:
- return ts.Debug.assertNever(extensions);
- }
- }
- var loader = function (extensions, candidate, onlyRecordFailures, state) {
- var fromFile = tryFile(candidate, onlyRecordFailures, state);
- if (fromFile) {
- var resolved = resolvedIfExtensionMatches(extensions, fromFile);
- if (resolved) {
- return noPackageId(resolved);
- }
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
+ ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
+ function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
+ if (option && !isNullOrUndefined(value)) {
+ if (option.type === "list") {
+ var values = value;
+ if (option.element.isFilePath && values.length) {
+ return values.map(toAbsolutePath);
}
}
- // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
- var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
- // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
- return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
- };
- var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
- var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
- var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
- if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
- var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName);
- }
- var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
- if (result) {
- return removeIgnoredPackageId(result.value);
+ else if (option.isFilePath) {
+ return toAbsolutePath(value);
}
}
- // It won't have a `packageId` set, because we disabled `considerPackageJson`.
- var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
- if (packageFileResult)
- return packageFileResult;
- return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
+ return value;
}
- /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
- function resolvedIfExtensionMatches(extensions, path) {
- var ext = ts.tryGetExtensionFromPath(path);
- return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
+ /**
+ * 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, extendedConfigCache, existingWatchOptions) {
+ return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
}
- /** True if `extension` is one of the supported `extensions`. */
- function extensionIsOk(extensions, extension) {
- switch (extensions) {
- case Extensions.JavaScript:
- return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
- case Extensions.TSConfig:
- case Extensions.Json:
- return extension === ".json" /* Json */;
- case Extensions.TypeScript:
- return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
- case Extensions.DtsOnly:
- return extension === ".d.ts" /* Dts */;
- }
+ 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, extendedConfigCache, existingWatchOptions) {
+ return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
}
- /* @internal */
- function parsePackageName(moduleName) {
- var idx = moduleName.indexOf(ts.directorySeparator);
- if (moduleName[0] === "@") {
- idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
+ ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
+ /*@internal*/
+ function setConfigFileInOptions(options, configFile) {
+ if (configFile) {
+ Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
}
- return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
}
- ts.parsePackageName = parsePackageName;
- function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
- return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
+ ts.setConfigFileInOptions = setConfigFileInOptions;
+ function isNullOrUndefined(x) {
+ return x === undefined || x === null; // eslint-disable-line no-null/no-null
}
- function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
- // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
- return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
+ function directoryOfCombinedPath(fileName, basePath) {
+ // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
+ // until consistent casing errors are reported
+ return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
- function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
- var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
- return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
- if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
- var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
- if (resolutionFromCache) {
- return resolutionFromCache;
+ /**
+ * 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, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
+ if (existingOptions === void 0) { existingOptions = {}; }
+ if (resolutionStack === void 0) { resolutionStack = []; }
+ if (extraFileExtensions === void 0) { extraFileExtensions = []; }
+ ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
+ var errors = [];
+ var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
+ var raw = parsedConfig.raw;
+ var options = ts.extend(existingOptions, parsedConfig.options || {});
+ var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
+ ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
+ parsedConfig.watchOptions || existingWatchOptions;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
+ var configFileSpecs = getConfigFileSpecs();
+ if (sourceFile)
+ sourceFile.configFileSpecs = configFileSpecs;
+ setConfigFileInOptions(options, sourceFile);
+ var basePathForFileNames = ts.normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath);
+ return {
+ options: options,
+ watchOptions: watchOptions,
+ fileNames: getFileNames(basePathForFileNames),
+ projectReferences: getProjectReferences(basePathForFileNames),
+ typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
+ raw: raw,
+ errors: errors,
+ // 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.
+ wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames),
+ compileOnSave: !!raw.compileOnSave,
+ };
+ function getConfigFileSpecs() {
+ var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
+ var filesSpecs = toPropValue(getSpecsFromRaw("files"));
+ if (filesSpecs) {
+ var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
+ var hasExtends = ts.hasProperty(raw, "extends");
+ if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
+ if (sourceFile) {
+ var fileName = configFileName || "tsconfig.json";
+ var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
+ var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
+ var error = nodeValue
+ ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
+ : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
+ errors.push(error);
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
+ }
}
- return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
}
- });
- }
- function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
- if (!nodeModulesFolderExists && state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
- }
- var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
- if (packageResult) {
- return packageResult;
- }
- if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
- var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
- var nodeModulesAtTypesExists = nodeModulesFolderExists;
- if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
+ var includeSpecs = toPropValue(getSpecsFromRaw("include"));
+ var excludeOfRaw = getSpecsFromRaw("exclude");
+ var excludeSpecs = toPropValue(excludeOfRaw);
+ if (excludeOfRaw === "no-prop" && raw.compilerOptions) {
+ var outDir = raw.compilerOptions.outDir;
+ var declarationDir = raw.compilerOptions.declarationDir;
+ if (outDir || declarationDir) {
+ excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
}
- nodeModulesAtTypesExists = false;
}
- return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
- }
- }
- function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
- // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
- var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
- if (packageInfo) {
- var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
- if (fromFile) {
- return noPackageId(fromFile);
+ if (filesSpecs === undefined && includeSpecs === undefined) {
+ includeSpecs = ["**/*"];
}
- var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
- return withPackageId(packageInfo, fromDirectory);
- }
- var loader = function (extensions, candidate, onlyRecordFailures, state) {
- var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
- loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
- return withPackageId(packageInfo, pathAndExtension);
- };
- var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
- if (rest !== "") { // If "rest" is empty, we just did this search above.
- var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
- // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
- packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
- if (packageInfo && packageInfo.versionPaths) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
- }
- var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
- var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
- if (fromPaths) {
- return fromPaths.value;
- }
+ 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, /*disallowTrailingRecursion*/ true, sourceFile, "include");
}
- }
- return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
- }
- function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
- var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
- if (matchedPattern) {
- var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
- var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ if (excludeSpecs) {
+ validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*disallowTrailingRecursion*/ false, sourceFile, "exclude");
}
- var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
- var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
- var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
- }
- // A path mapping may have an extension, in contrast to an import, which should omit it.
- var extension = ts.tryGetExtensionFromPath(candidate);
- if (extension !== undefined) {
- var path_1 = tryFile(candidate, onlyRecordFailures, state);
- if (path_1 !== undefined) {
- return noPackageId({ path: path_1, ext: extension });
+ return {
+ filesSpecs: filesSpecs,
+ includeSpecs: includeSpecs,
+ excludeSpecs: excludeSpecs,
+ validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
+ validatedIncludeSpecs: validatedIncludeSpecs,
+ validatedExcludeSpecs: validatedExcludeSpecs,
+ pathPatterns: undefined, // Initialized on first use
+ };
+ }
+ function getFileNames(basePath) {
+ var fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions);
+ if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) {
+ errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
+ }
+ return fileNames;
+ }
+ function getProjectReferences(basePath) {
+ var projectReferences;
+ var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
+ if (ts.isArray(referencesOfRaw)) {
+ for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
+ var ref = referencesOfRaw_1[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ (projectReferences || (projectReferences = [])).push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
}
}
- return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- });
- return { value: resolved };
- }
- }
- /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
- var mangledScopedPackageSeparator = "__";
- /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
- function mangleScopedPackageNameWithTrace(packageName, state) {
- var mangled = mangleScopedPackageName(packageName);
- if (state.traceEnabled && mangled !== packageName) {
- trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
- }
- return mangled;
- }
- /* @internal */
- function getTypesPackageName(packageName) {
- return "@types/" + mangleScopedPackageName(packageName);
- }
- ts.getTypesPackageName = getTypesPackageName;
- /* @internal */
- function mangleScopedPackageName(packageName) {
- if (ts.startsWith(packageName, "@")) {
- var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
- if (replaceSlash !== packageName) {
- return replaceSlash.slice(1); // Take off the "@"
}
+ return projectReferences;
}
- return packageName;
- }
- ts.mangleScopedPackageName = mangleScopedPackageName;
- /* @internal */
- function getPackageNameFromTypesPackageName(mangledName) {
- var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
- if (withoutAtTypePrefix !== mangledName) {
- return unmangleScopedPackageName(withoutAtTypePrefix);
+ function toPropValue(specResult) {
+ return ts.isArray(specResult) ? specResult : undefined;
}
- return mangledName;
- }
- ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
- /* @internal */
- function unmangleScopedPackageName(typesPackageName) {
- return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
- "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
- typesPackageName;
- }
- ts.unmangleScopedPackageName = unmangleScopedPackageName;
- function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
- var result = cache && cache.get(containingDirectory);
- if (result) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
- }
- state.resultFromCache = result;
- return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
+ function getSpecsFromRaw(prop) {
+ return getPropFromRaw(prop, ts.isString, "string");
}
- }
- function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
- var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
- // No originalPath because classic resolution doesn't resolve realPath
- return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
- function tryResolve(extensions) {
- var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
- if (resolvedUsingSettings) {
- return { value: resolvedUsingSettings };
- }
- if (!ts.isExternalModuleNameRelative(moduleName)) {
- var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
- // Climb up parent directories looking for a module.
- var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
- var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
- if (resolutionFromCache) {
- return resolutionFromCache;
+ function getPropFromRaw(prop, validateElement, elementTypeName) {
+ if (ts.hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
+ if (ts.isArray(raw[prop])) {
+ var result = raw[prop];
+ if (!sourceFile && !ts.every(result, validateElement)) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
}
- var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
- return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
- });
- if (resolved_3) {
- return resolved_3;
+ return result;
}
- if (extensions === Extensions.TypeScript) {
- // If we didn't find the file normally, look it up in @types.
- return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
+ return "not-array";
}
}
- else {
- var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
+ return "no-prop";
+ }
+ function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
+ if (!sourceFile) {
+ errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
}
}
}
- ts.classicNameResolver = classicNameResolver;
- /**
- * A host may load a module from a global cache of typings.
- * This is the minumum code needed to expose that functionality; the rest is in the host.
- */
- /* @internal */
- function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
- var traceEnabled = isTraceEnabled(compilerOptions, host);
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
+ 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;
+ }
+ 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 || []));
+ }
+ function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) {
+ return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
+ }
+ /*@internal*/
+ function canJsonReportNoInputFiles(raw) {
+ return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
+ }
+ ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
+ /*@internal*/
+ function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
+ var existingErrors = configParseDiagnostics.length;
+ if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) {
+ configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
}
- var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
- var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
- return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
+ else {
+ ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
+ }
+ return existingErrors !== configParseDiagnostics.length;
+ }
+ ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
+ function isSuccessfulParsedTsconfig(value) {
+ return !!value.options;
}
- ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
/**
- * Wraps value to SearchResult.
- * @returns undefined if value is undefined or { value } otherwise
+ * This *just* extracts options/include/exclude/files out of a config file.
+ * It does *not* resolve the included files.
*/
- function toSearchResult(value) {
- return value !== undefined ? { value: value } : undefined;
- }
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var ModuleInstanceState;
- (function (ModuleInstanceState) {
- ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
- ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
- ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
- })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
- function getModuleInstanceState(node, visited) {
- if (node.body && !node.body.parent) {
- // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
- setParentPointers(node, node.body);
+ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
+ var _a;
+ basePath = ts.normalizeSlashes(basePath);
+ var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
+ if (resolutionStack.indexOf(resolvedPath) >= 0) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArray(__spreadArray([], resolutionStack, true), [resolvedPath], false).join(" -> ")));
+ return { raw: json || convertToObject(sourceFile, errors) };
}
- return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
+ var ownConfig = json ?
+ parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
+ parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
+ if ((_a = ownConfig.options) === null || _a === void 0 ? void 0 : _a.paths) {
+ // If we end up needing to resolve relative paths from 'paths' relative to
+ // the config file location, we'll need to know where that config file was.
+ // Since 'paths' can be inherited from an extended config in another directory,
+ // we wouldn't know which directory to use unless we store it here.
+ ownConfig.options.pathsBasePath = basePath;
+ }
+ 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, resolutionStack, errors, extendedConfigCache);
+ if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
+ var baseRaw_1 = extendedConfig.raw;
+ var raw_1 = ownConfig.raw;
+ var relativeDifference_1;
+ var setPropertyInRawIfNotUndefined = function (propertyName) {
+ if (!raw_1[propertyName] && baseRaw_1[propertyName]) {
+ raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); });
+ }
+ };
+ setPropertyInRawIfNotUndefined("include");
+ setPropertyInRawIfNotUndefined("exclude");
+ setPropertyInRawIfNotUndefined("files");
+ if (raw_1.compileOnSave === undefined) {
+ raw_1.compileOnSave = baseRaw_1.compileOnSave;
+ }
+ ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
+ ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
+ ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
+ ownConfig.watchOptions || extendedConfig.watchOptions;
+ // TODO extend type typeAcquisition
+ }
+ }
+ return ownConfig;
}
- ts.getModuleInstanceState = getModuleInstanceState;
- function getModuleInstanceStateCached(node, visited) {
- if (visited === void 0) { visited = ts.createMap(); }
- var nodeId = "" + ts.getNodeId(node);
- if (visited.has(nodeId)) {
- return visited.get(nodeId) || 0 /* NonInstantiated */;
+ function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
+ if (ts.hasProperty(json, "excludes")) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
- visited.set(nodeId, undefined);
- var result = getModuleInstanceStateWorker(node, visited);
- visited.set(nodeId, result);
- return result;
+ 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);
+ var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
+ json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
+ var extendedConfigPath;
+ if (json.extends) {
+ if (!ts.isString(json.extends)) {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
+ }
+ else {
+ var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
+ extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
+ }
+ }
+ return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
}
- function getModuleInstanceStateWorker(node, visited) {
- // A module is uninstantiated if it contains only
- switch (node.kind) {
- // 1. interface declarations, type alias declarations
- case 246 /* InterfaceDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- return 0 /* NonInstantiated */;
- // 2. const enum declarations
- case 248 /* EnumDeclaration */:
- if (ts.isEnumConst(node)) {
- return 2 /* ConstEnumOnly */;
+ function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
+ var options = getDefaultCompilerOptions(configFileName);
+ var typeAcquisition, typingOptionstypeAcquisition;
+ var watchOptions;
+ var extendedConfigPath;
+ var rootCompilerOptions;
+ var optionsIterator = {
+ onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
+ var currentOption;
+ switch (parentOption) {
+ case "compilerOptions":
+ currentOption = options;
+ break;
+ case "watchOptions":
+ currentOption = (watchOptions || (watchOptions = {}));
+ break;
+ case "typeAcquisition":
+ currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
+ break;
+ case "typingOptions":
+ currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
+ break;
+ default:
+ ts.Debug.fail("Unknown option");
}
- break;
- // 3. non-exported import declarations
- case 254 /* ImportDeclaration */:
- case 253 /* ImportEqualsDeclaration */:
- if (!(ts.hasModifier(node, 1 /* Export */))) {
- return 0 /* NonInstantiated */;
+ currentOption[option.name] = normalizeOptionValue(option, basePath, value);
+ },
+ onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
+ switch (key) {
+ case "extends":
+ var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
+ extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
+ return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
+ });
+ return;
}
- break;
- // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
- case 260 /* ExportDeclaration */:
- var exportDeclaration = node;
- if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
- var state = 0 /* NonInstantiated */;
- for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
- var specifier = _a[_i];
- var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
- if (specifierState > state) {
- state = specifierState;
- }
- if (state === 1 /* Instantiated */) {
- return state;
- }
- }
- return state;
+ },
+ onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
+ if (key === "excludes") {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
- break;
- // 5. other uninstantiated module declarations.
- case 250 /* ModuleBlock */: {
- var state_1 = 0 /* NonInstantiated */;
- ts.forEachChild(node, function (n) {
- var childState = getModuleInstanceStateCached(n, visited);
- switch (childState) {
- case 0 /* NonInstantiated */:
- // child is non-instantiated - continue searching
- return;
- case 2 /* ConstEnumOnly */:
- // child is const enum only - record state and continue searching
- state_1 = 2 /* ConstEnumOnly */;
- return;
- case 1 /* Instantiated */:
- // child is instantiated - record state and stop
- state_1 = 1 /* Instantiated */;
- return true;
- default:
- ts.Debug.assertNever(childState);
- }
- });
- return state_1;
- }
- case 249 /* ModuleDeclaration */:
- return getModuleInstanceState(node, visited);
- case 75 /* Identifier */:
- // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
- // be considered the same as type alias
- if (node.isInJSDocNamespace) {
- return 0 /* NonInstantiated */;
+ if (ts.find(commandOptionsWithoutBuild, function (opt) { return opt.name === key; })) {
+ rootCompilerOptions = ts.append(rootCompilerOptions, keyNode);
}
+ }
+ };
+ var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator);
+ if (!typeAcquisition) {
+ if (typingOptionstypeAcquisition) {
+ typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
+ {
+ enable: typingOptionstypeAcquisition.enableAutoDiscovery,
+ include: typingOptionstypeAcquisition.include,
+ exclude: typingOptionstypeAcquisition.exclude
+ } :
+ typingOptionstypeAcquisition;
+ }
+ else {
+ typeAcquisition = getDefaultTypeAcquisition(configFileName);
+ }
}
- return 1 /* Instantiated */;
+ if (rootCompilerOptions && json && json.compilerOptions === undefined) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], ts.Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, ts.getTextOfPropertyName(rootCompilerOptions[0])));
+ }
+ return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
}
- function getModuleInstanceStateForAliasTarget(specifier, visited) {
- var name = specifier.propertyName || specifier.name;
- var p = specifier.parent;
- while (p) {
- if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
- var statements = p.statements;
- var found = void 0;
- for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
- var statement = statements_1[_i];
- if (ts.nodeHasName(statement, name)) {
- if (!statement.parent) {
- setParentPointers(p, statement);
- }
- var state = getModuleInstanceStateCached(statement, visited);
- if (found === undefined || state > found) {
- found = state;
- }
- if (found === 1 /* Instantiated */) {
- return found;
- }
- }
- }
- if (found !== undefined) {
- return found;
+ function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
+ extendedConfig = ts.normalizeSlashes(extendedConfig);
+ if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
+ var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
+ if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
+ extendedConfigPath = "".concat(extendedConfigPath, ".json");
+ if (!host.fileExists(extendedConfigPath)) {
+ errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
+ return undefined;
}
}
- p = p.parent;
+ return extendedConfigPath;
}
- return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
- }
- var ContainerFlags;
- (function (ContainerFlags) {
- // The current node is not a container, and no container manipulation should happen before
- // recursing into it.
- ContainerFlags[ContainerFlags["None"] = 0] = "None";
- // The current node is a container. It should be set as the current container (and block-
- // container) before recursing into it. The current node does not have locals. Examples:
- //
- // Classes, ObjectLiterals, TypeLiterals, Interfaces...
- ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
- // The current node is a block-scoped-container. It should be set as the current block-
- // container before recursing into it. Examples:
- //
- // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
- ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
- // The current node is the container of a control flow path. The current control flow should
- // be saved and restored, and a new control flow initialized within the container.
- ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
- ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
- ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
- ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
- ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
- ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
- })(ContainerFlags || (ContainerFlags = {}));
- function initFlowNode(node) {
- ts.Debug.attachFlowNodeDebugInfo(node);
- return node;
- }
- var binder = createBinder();
- function bindSourceFile(file, options) {
- ts.performance.mark("beforeBind");
- ts.perfLogger.logStartBindFile("" + file.fileName);
- binder(file, options);
- ts.perfLogger.logStopBindFile();
- ts.performance.mark("afterBind");
- ts.performance.measure("Bind", "beforeBind", "afterBind");
+ // If the path isn't a rooted or relative path, resolve like a module
+ var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
+ if (resolved.resolvedModule) {
+ return resolved.resolvedModule.resolvedFileName;
+ }
+ errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
+ return undefined;
}
- ts.bindSourceFile = bindSourceFile;
- function createBinder() {
- var file;
- var options;
- var languageVersion;
- var parent;
- var container;
- var thisParentContainer; // Container one level up
- var blockScopeContainer;
- var lastContainer;
- var delayedTypeAliases;
- var seenThisKeyword;
- // state used by control flow analysis
- var currentFlow;
- var currentBreakTarget;
- var currentContinueTarget;
- var currentReturnTarget;
- var currentTrueTarget;
- var currentFalseTarget;
- var currentExceptionTarget;
- var preSwitchCaseFlow;
- var activeLabelList;
- var hasExplicitReturn;
- // state used for emit helpers
- var emitFlags;
- // If this file is an external module, then it is automatically in strict-mode according to
- // ES6. If it is not an external module, then we'll determine if it is in strict mode or
- // not depending on if we see "use strict" in certain places or if we hit a class/namespace
- // or if compiler options contain alwaysStrict.
- var inStrictMode;
- var symbolCount = 0;
- var Symbol;
- var classifiableNames;
- var unreachableFlow = { flags: 1 /* Unreachable */ };
- var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
- // state used to aggregate transform flags during bind.
- var subtreeTransformFlags = 0 /* None */;
- var skipTransformFlagAggregation;
- /**
- * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
- * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
- * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
- */
- function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
- return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
+ function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) {
+ var _a;
+ var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
+ var value;
+ var extendedResult;
+ var extendedConfig;
+ if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
+ (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
}
- function bindSourceFile(f, opts) {
- file = f;
- options = opts;
- languageVersion = ts.getEmitScriptTarget(options);
- inStrictMode = bindInStrictMode(file, opts);
- classifiableNames = ts.createUnderscoreEscapedMap();
- symbolCount = 0;
- skipTransformFlagAggregation = file.isDeclarationFile;
- Symbol = ts.objectAllocator.getSymbolConstructor();
- // Attach debugging information if necessary
- ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
- ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
- if (!file.locals) {
- bind(file);
- file.symbolCount = symbolCount;
- file.classifiableNames = classifiableNames;
- delayedBindJSDocTypedefTag();
+ else {
+ extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
+ if (!extendedResult.parseDiagnostics.length) {
+ extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
+ }
+ if (extendedConfigCache) {
+ extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
}
- file = undefined;
- options = undefined;
- languageVersion = undefined;
- parent = undefined;
- container = undefined;
- thisParentContainer = undefined;
- blockScopeContainer = undefined;
- lastContainer = undefined;
- delayedTypeAliases = undefined;
- seenThisKeyword = false;
- currentFlow = undefined;
- currentBreakTarget = undefined;
- currentContinueTarget = undefined;
- currentReturnTarget = undefined;
- currentTrueTarget = undefined;
- currentFalseTarget = undefined;
- currentExceptionTarget = undefined;
- activeLabelList = undefined;
- hasExplicitReturn = false;
- emitFlags = 0 /* None */;
- subtreeTransformFlags = 0 /* None */;
}
- return bindSourceFile;
- function bindInStrictMode(file, opts) {
- if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
- // bind in strict mode source files with alwaysStrict option
- return true;
+ if (sourceFile) {
+ sourceFile.extendedSourceFiles = [extendedResult.fileName];
+ if (extendedResult.extendedSourceFiles) {
+ (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
+ }
+ }
+ if (extendedResult.parseDiagnostics.length) {
+ errors.push.apply(errors, extendedResult.parseDiagnostics);
+ return undefined;
+ }
+ return extendedConfig;
+ }
+ function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
+ if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
+ return false;
+ }
+ var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
+ return typeof result === "boolean" && result;
+ }
+ function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
+ var errors = [];
+ var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
+ return { options: options, errors: errors };
+ }
+ ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
+ function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
+ var errors = [];
+ var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
+ return { options: options, errors: errors };
+ }
+ ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
+ function getDefaultCompilerOptions(configFileName) {
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
+ ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
+ : {};
+ return options;
+ }
+ function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
+ var options = getDefaultCompilerOptions(configFileName);
+ convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
+ return options;
+ }
+ function getDefaultTypeAcquisition(configFileName) {
+ return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ }
+ function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
+ var options = getDefaultTypeAcquisition(configFileName);
+ var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
+ convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
+ return options;
+ }
+ function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
+ return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
+ }
+ function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
+ if (!jsonOptions) {
+ return;
+ }
+ for (var id in jsonOptions) {
+ var opt = optionsNameMap.get(id);
+ if (opt) {
+ (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
}
else {
- return !!file.externalModuleIndicator;
+ errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
}
}
- function createSymbol(flags, name) {
- symbolCount++;
- return new Symbol(flags, name);
- }
- function addDeclarationToSymbol(symbol, node, symbolFlags) {
- symbol.flags |= symbolFlags;
- node.symbol = symbol;
- symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
- if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
- symbol.exports = ts.createSymbolTable();
+ return defaultOptions;
+ }
+ /*@internal*/
+ function convertJsonOption(opt, value, basePath, errors) {
+ if (isCompilerOptionsValue(opt, value)) {
+ var optType = opt.type;
+ if (optType === "list" && ts.isArray(value)) {
+ return convertJsonOptionOfListType(opt, value, basePath, errors);
}
- if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
- symbol.members = ts.createSymbolTable();
+ else if (!ts.isString(optType)) {
+ return convertJsonOptionOfCustomType(opt, value, errors);
}
- // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
- if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
- symbol.constEnumOnlyModule = false;
+ var validatedValue = validateJsonOptionValue(opt, value, errors);
+ return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
+ }
+ else {
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
+ }
+ }
+ ts.convertJsonOption = convertJsonOption;
+ function normalizeOptionValue(option, basePath, value) {
+ if (isNullOrUndefined(value))
+ return undefined;
+ if (option.type === "list") {
+ var listOption_1 = option;
+ if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
+ return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
}
- if (symbolFlags & 111551 /* Value */) {
- ts.setValueDeclaration(symbol, node);
+ return value;
+ }
+ else if (!ts.isString(option.type)) {
+ return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
+ }
+ return normalizeNonListOptionValue(option, basePath, value);
+ }
+ function normalizeNonListOptionValue(option, basePath, value) {
+ if (option.isFilePath) {
+ value = ts.getNormalizedAbsolutePath(value, basePath);
+ if (value === "") {
+ value = ".";
}
}
- // Should not be called on a declaration with a computed property name,
- // unless it is a well known Symbol.
- function getDeclarationName(node) {
- if (node.kind === 259 /* ExportAssignment */) {
- return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
+ return value;
+ }
+ function validateJsonOptionValue(opt, value, errors) {
+ var _a;
+ if (isNullOrUndefined(value))
+ return undefined;
+ var d = (_a = opt.extraValidation) === null || _a === void 0 ? void 0 : _a.call(opt, value);
+ if (!d)
+ return value;
+ errors.push(ts.createCompilerDiagnostic.apply(void 0, d));
+ return undefined;
+ }
+ function convertJsonOptionOfCustomType(opt, value, errors) {
+ if (isNullOrUndefined(value))
+ return undefined;
+ var key = value.toLowerCase();
+ var val = opt.type.get(key);
+ if (val !== undefined) {
+ return validateJsonOptionValue(opt, val, errors);
+ }
+ else {
+ errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
+ }
+ }
+ function convertJsonOptionOfListType(option, values, basePath, errors) {
+ return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
+ }
+ /**
+ * 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 = /(^|\/)\*\*\/?$/;
+ /**
+ * 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 = /^[^*?]*(?=\/[^/]*[*?])/;
+ /**
+ * 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 configFileSpecs 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(configFileSpecs, basePath, options, host, extraFileExtensions) {
+ if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
+ basePath = ts.normalizePath(basePath);
+ var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
+ // 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 = new ts.Map();
+ // 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 = new ts.Map();
+ // Wildcard paths of json files (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 of *.json kind
+ var wildCardJsonFileMap = new ts.Map();
+ var validatedFilesSpec = configFileSpecs.validatedFilesSpec, validatedIncludeSpecs = configFileSpecs.validatedIncludeSpecs, validatedExcludeSpecs = configFileSpecs.validatedExcludeSpecs;
+ // Rather than re-query 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);
+ var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
+ // Literal files are always included verbatim. An "include" or "exclude" specification cannot
+ // remove a literal file.
+ if (validatedFilesSpec) {
+ for (var _i = 0, validatedFilesSpec_1 = validatedFilesSpec; _i < validatedFilesSpec_1.length; _i++) {
+ var fileName = validatedFilesSpec_1[_i];
+ var file = ts.getNormalizedAbsolutePath(fileName, basePath);
+ literalFileMap.set(keyMapper(file), file);
}
- var name = ts.getNameOfDeclaration(node);
- if (name) {
- if (ts.isAmbientModule(node)) {
- var moduleName = ts.getTextOfIdentifierOrLiteral(name);
- return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
- }
- if (name.kind === 154 /* ComputedPropertyName */) {
- var nameExpression = name.expression;
- // treat computed property names where expression is string/numeric literal as just string/numeric literal
- if (ts.isStringOrNumericLiteralLike(nameExpression)) {
- return ts.escapeLeadingUnderscores(nameExpression.text);
+ }
+ var jsonOnlyIncludeRegexes;
+ if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
+ var _loop_6 = function (file) {
+ if (ts.fileExtensionIs(file, ".json" /* Json */)) {
+ // Valid only if *.json specified
+ if (!jsonOnlyIncludeRegexes) {
+ var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
+ var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^".concat(pattern, "$"); });
+ jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
}
- if (ts.isSignedNumericLiteral(nameExpression)) {
- return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
+ var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
+ if (includeIndex !== -1) {
+ var key_1 = keyMapper(file);
+ if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
+ wildCardJsonFileMap.set(key_1, file);
+ }
}
- ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
- return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
+ return "continue";
}
- if (ts.isWellKnownSymbolSyntactically(name)) {
- return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
+ // 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)) {
+ return "continue";
}
- if (ts.isPrivateIdentifier(name)) {
- // containingClass exists because private names only allowed inside classes
- var containingClass = ts.getContainingClass(node);
- if (!containingClass) {
- // we can get here in cases where there is already a parse error.
- return undefined;
- }
- var containingClassSymbol = containingClass.symbol;
- return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
+ // 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)) {
+ wildcardFileMap.set(key, file);
}
- return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
+ };
+ for (var _a = 0, _b = host.readDirectory(basePath, ts.flatten(supportedExtensionsWithJsonIfResolveJsonModule), validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
+ var file = _b[_a];
+ _loop_6(file);
}
- switch (node.kind) {
- case 162 /* Constructor */:
- return "__constructor" /* Constructor */;
- case 170 /* FunctionType */:
- case 165 /* CallSignature */:
- case 305 /* JSDocSignature */:
- return "__call" /* Call */;
- case 171 /* ConstructorType */:
- case 166 /* ConstructSignature */:
- return "__new" /* New */;
- case 167 /* IndexSignature */:
- return "__index" /* Index */;
- case 260 /* ExportDeclaration */:
- return "__export" /* ExportStar */;
- case 290 /* SourceFile */:
- // json file should behave as
- // module.exports = ...
- return "export=" /* ExportEquals */;
- case 209 /* BinaryExpression */:
- if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
- // module.exports = ...
- return "export=" /* ExportEquals */;
- }
- ts.Debug.fail("Unknown binary declaration kind");
- break;
- case 300 /* JSDocFunctionType */:
- return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
- case 156 /* Parameter */:
- // Parameters with names are handled at the top of this function. Parameters
- // without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 300 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
- var functionType = node.parent;
- var index = functionType.parameters.indexOf(node);
- return "arg" + index;
+ }
+ var literalFiles = ts.arrayFrom(literalFileMap.values());
+ var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ return literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values()));
+ }
+ ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
+ /* @internal */
+ function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) {
+ var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs;
+ if (!ts.length(validatedIncludeSpecs) || !ts.length(validatedExcludeSpecs))
+ return false;
+ basePath = ts.normalizePath(basePath);
+ var keyMapper = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
+ if (validatedFilesSpec) {
+ for (var _i = 0, validatedFilesSpec_2 = validatedFilesSpec; _i < validatedFilesSpec_2.length; _i++) {
+ var fileName = validatedFilesSpec_2[_i];
+ if (keyMapper(ts.getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck)
+ return false;
}
}
- function getDisplayName(node) {
- return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
+ return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath);
+ }
+ ts.isExcludedFile = isExcludedFile;
+ function invalidDotDotAfterRecursiveWildcard(s) {
+ // We used to use the regex /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/ to check for this case, but
+ // in v8, that has polynomial performance because the recursive wildcard match - **/ -
+ // can be matched in many arbitrary positions when multiple are present, resulting
+ // in bad backtracking (and we don't care which is matched - just that some /.. segment
+ // comes after some **/ segment).
+ var wildcardIndex = ts.startsWith(s, "**/") ? 0 : s.indexOf("/**/");
+ if (wildcardIndex === -1) {
+ return false;
}
- /**
- * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
- * @param symbolTable - The symbol table which node will be added to.
- * @param parent - node's parent declaration.
- * @param node - The declaration to be added to the symbol table
- * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
- * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
- */
- function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
- ts.Debug.assert(!ts.hasDynamicName(node));
- var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
- // The exported symbol for an export default function/class node is always named "default"
- var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
- var symbol;
- if (name === undefined) {
- symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
+ var lastDotIndex = ts.endsWith(s, "/..") ? s.length : s.lastIndexOf("/../");
+ return lastDotIndex > wildcardIndex;
+ }
+ /* @internal */
+ function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) {
+ return matchesExcludeWorker(pathToCheck, ts.filter(excludeSpecs, function (spec) { return !invalidDotDotAfterRecursiveWildcard(spec); }), useCaseSensitiveFileNames, currentDirectory);
+ }
+ ts.matchesExclude = matchesExclude;
+ function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) {
+ var excludePattern = ts.getRegularExpressionForWildcard(excludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
+ var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
+ if (!excludeRegex)
+ return false;
+ if (excludeRegex.test(pathToCheck))
+ return true;
+ return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
+ }
+ function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) {
+ return specs.filter(function (spec) {
+ if (!ts.isString(spec))
+ return false;
+ var diag = specToDiagnostic(spec, disallowTrailingRecursion);
+ if (diag !== undefined) {
+ errors.push(createDiagnostic.apply(void 0, diag));
}
- else {
- // Check and see if the symbol table already has a symbol with this name. If not,
- // create a new symbol with this name and add it to the table. Note that we don't
- // give the new symbol any flags *yet*. This ensures that it will not conflict
- // with the 'excludes' flags we pass in.
- //
- // If we do get an existing symbol, see if it conflicts with the new symbol we're
- // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
- // the same symbol table. If we have a conflict, report the issue on each
- // declaration we have for this symbol, and then create a new symbol for this
- // declaration.
- //
- // Note that when properties declared in Javascript constructors
- // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
- // Always. This allows the common Javascript pattern of overwriting a prototype method
- // with an bound instance method of the same type: `this.method = this.method.bind(this)`
- //
- // If we created a new symbol, either because we didn't have a symbol with this name
- // in the symbol table, or we conflicted with an existing symbol, then just add this
- // node as the sole declaration of the new symbol.
- //
- // Otherwise, we'll be merging into a compatible existing symbol (for example when
- // you have multiple 'vars' with the same name in the same container). In this case
- // just add this node into the declarations list of the symbol.
- symbol = symbolTable.get(name);
- if (includes & 2885600 /* Classifiable */) {
- classifiableNames.set(name, true);
- }
- if (!symbol) {
- symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
- if (isReplaceableByMethod)
- symbol.isReplaceableByMethod = true;
- }
- else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
- // A symbol already exists, so don't add this as a declaration.
- return symbol;
+ return diag === undefined;
+ });
+ function createDiagnostic(message, spec) {
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
+ }
+ }
+ function specToDiagnostic(spec, disallowTrailingRecursion) {
+ if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
+ return [ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
+ }
+ else if (invalidDotDotAfterRecursiveWildcard(spec)) {
+ return [ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
+ }
+ }
+ /**
+ * Gets directories in a set of include patterns that should be watched for changes.
+ */
+ function getWildcardDirectories(_a, path, useCaseSensitiveFileNames) {
+ var include = _a.validatedIncludeSpecs, exclude = _a.validatedExcludeSpecs;
+ // 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 = {};
+ if (include !== undefined) {
+ var recursiveKeys = [];
+ for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
+ var file = include_1[_i];
+ var spec = ts.normalizePath(ts.combinePaths(path, file));
+ if (excludeRegex && excludeRegex.test(spec)) {
+ continue;
}
- else if (symbol.flags & excludes) {
- if (symbol.isReplaceableByMethod) {
- // Javascript constructor-declared symbols can be discarded in favor of
- // prototype symbols like methods.
- symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
- }
- else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
- // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
- if (ts.isNamedDeclaration(node)) {
- node.name.parent = node;
- }
- // Report errors every position with duplicate declaration
- // Report errors on previous encountered declarations
- var message_1 = symbol.flags & 2 /* BlockScopedVariable */
- ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
- : ts.Diagnostics.Duplicate_identifier_0;
- var messageNeedsName_1 = true;
- if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
- message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
- messageNeedsName_1 = false;
- }
- var multipleDefaultExports_1 = false;
- if (ts.length(symbol.declarations)) {
- // If the current node is a default export of some sort, then check if
- // there are any other default exports that we need to error on.
- // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
- if (isDefaultExport) {
- message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
- messageNeedsName_1 = false;
- multipleDefaultExports_1 = true;
- }
- else {
- // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
- // Error on multiple export default in the following case:
- // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
- // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
- if (symbol.declarations && symbol.declarations.length &&
- (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
- message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
- messageNeedsName_1 = false;
- multipleDefaultExports_1 = true;
- }
- }
+ var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
+ if (match) {
+ var key = match.key, flags = match.flags;
+ var existingFlags = wildcardDirectories[key];
+ if (existingFlags === undefined || existingFlags < flags) {
+ wildcardDirectories[key] = flags;
+ if (flags === 1 /* Recursive */) {
+ recursiveKeys.push(key);
}
- var relatedInformation_1 = [];
- if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
- // export type T; - may have meant export type { T }?
- relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
+ }
+ }
+ }
+ // Remove any subpaths under an existing recursively watched directory.
+ for (var key in wildcardDirectories) {
+ if (ts.hasProperty(wildcardDirectories, key)) {
+ for (var _b = 0, recursiveKeys_1 = recursiveKeys; _b < recursiveKeys_1.length; _b++) {
+ var recursiveKey = recursiveKeys_1[_b];
+ if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
+ delete wildcardDirectories[key];
}
- var declarationName_1 = ts.getNameOfDeclaration(node) || node;
- ts.forEach(symbol.declarations, function (declaration, index) {
- var decl = ts.getNameOfDeclaration(declaration) || declaration;
- var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
- file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
- if (multipleDefaultExports_1) {
- relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
- }
- });
- var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
- file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
- symbol = createSymbol(0 /* None */, name);
}
}
}
- addDeclarationToSymbol(symbol, node, includes);
- if (symbol.parent) {
- ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ return wildcardDirectories;
+ }
+ function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
+ var match = wildcardDirectoryPattern.exec(spec);
+ if (match) {
+ // We check this with a few `indexOf` calls because 3 `indexOf`/`lastIndexOf` calls is
+ // less algorithmically complex (roughly O(3n) worst-case) than the regex we used to use,
+ // \/[^/]*?[*?][^/]*\/ which was polynominal in v8, since arbitrary sequences of wildcard
+ // characters could match any of the central patterns, resulting in bad backtracking.
+ var questionWildcardIndex = spec.indexOf("?");
+ var starWildcardIndex = spec.indexOf("*");
+ var lastDirectorySeperatorIndex = spec.lastIndexOf(ts.directorySeparator);
+ return {
+ key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
+ flags: (questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex)
+ || (starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex)
+ ? 1 /* Recursive */ : 0 /* None */
+ };
+ }
+ if (ts.isImplicitGlob(spec)) {
+ return {
+ key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(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.
+ */
+ function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
+ var extensionGroup = ts.forEach(extensions, function (group) { return ts.fileExtensionIsOneOf(file, group) ? group : undefined; });
+ if (!extensionGroup) {
+ return false;
+ }
+ for (var _i = 0, extensionGroup_1 = extensionGroup; _i < extensionGroup_1.length; _i++) {
+ var ext = extensionGroup_1[_i];
+ if (ts.fileExtensionIs(file, ext)) {
+ return false;
+ }
+ var higherPriorityPath = keyMapper(ts.changeExtension(file, ext));
+ if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
+ if (ext === ".d.ts" /* Dts */ && (ts.fileExtensionIs(file, ".js" /* Js */) || ts.fileExtensionIs(file, ".jsx" /* Jsx */))) {
+ // LEGACY BEHAVIOR: An off-by-one bug somewhere in the extension priority system for wildcard module loading allowed declaration
+ // files to be loaded alongside their js(x) counterparts. We regard this as generally undesirable, but retain the behavior to
+ // prevent breakage.
+ continue;
+ }
+ return true;
}
- else {
- symbol.parent = parent;
+ }
+ 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.
+ */
+ function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
+ var extensionGroup = ts.forEach(extensions, function (group) { return ts.fileExtensionIsOneOf(file, group) ? group : undefined; });
+ if (!extensionGroup) {
+ return;
+ }
+ for (var i = extensionGroup.length - 1; i >= 0; i--) {
+ var ext = extensionGroup[i];
+ if (ts.fileExtensionIs(file, ext)) {
+ return;
}
- return symbol;
+ var lowerPriorityPath = keyMapper(ts.changeExtension(file, ext));
+ wildcardFiles.delete(lowerPriorityPath);
}
- function declareModuleMember(node, symbolFlags, symbolExcludes) {
- var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
- if (symbolFlags & 2097152 /* Alias */) {
- if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- }
- else {
- return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
+ }
+ /**
+ * Produces a cleaned version of compiler options with personally identifying 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) { // Ignore unknown options
+ out[key] = getOptionValueWithEmptyStrings(opts[key], type);
}
}
- else {
- // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
- // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
- //
- // 1. We treat locals and exports of the same name as mutually exclusive within a container.
- // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
- // with the same name in the same container.
- // TODO: Make this a more specific error and decouple it from the exclusion logic.
- // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
- // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
- // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
- // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
- // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
- // and this case is specially handled. Module augmentations should only be merged with original module definition
- // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
- if (ts.isJSDocTypeAlias(node))
- ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
- if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
- if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
+ }
+ return out;
+ }
+ ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
+ function getOptionValueWithEmptyStrings(value, option) {
+ switch (option.type) {
+ case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
+ return "";
+ case "string": // Could be any arbitrary string -- use empty string instead.
+ return "";
+ 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 : "";
+ case "list":
+ var elementType_1 = option.element;
+ return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
+ default:
+ return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
+ if (optionEnumValue === value) {
+ return optionStringValue;
}
- var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
- var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
- local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- node.localSymbol = local;
- return local;
- }
- else {
- return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
- }
+ }); // TODO: GH#18217
+ }
+ }
+ function getDefaultValueForOption(option) {
+ switch (option.type) {
+ case "number":
+ return 1;
+ case "boolean":
+ return true;
+ case "string":
+ return option.isFilePath ? "./" : "";
+ case "list":
+ return [];
+ case "object":
+ return {};
+ default:
+ var iterResult = option.type.keys().next();
+ if (!iterResult.done)
+ return iterResult.value;
+ return ts.Debug.fail("Expected 'option.type' to have entries.");
+ }
+ }
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ function trace(host) {
+ host.trace(ts.formatMessage.apply(undefined, arguments));
+ }
+ ts.trace = trace;
+ /* @internal */
+ function isTraceEnabled(compilerOptions, host) {
+ return !!compilerOptions.traceResolution && host.trace !== undefined;
+ }
+ ts.isTraceEnabled = isTraceEnabled;
+ function withPackageId(packageInfo, r) {
+ var packageId;
+ if (r && packageInfo) {
+ var packageJsonContent = packageInfo.packageJsonContent;
+ if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
+ packageId = {
+ name: packageJsonContent.name,
+ subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
+ version: packageJsonContent.version
+ };
}
}
- // All container nodes are kept on a linked list in declaration order. This list is used by
- // the getLocalNameOfContainer function in the type checker to validate that the local name
- // used for a container is unique.
- function bindContainer(node, containerFlags) {
- // Before we recurse into a node's children, we first save the existing parent, container
- // and block-container. Then after we pop out of processing the children, we restore
- // these saved values.
- var saveContainer = container;
- var saveThisParentContainer = thisParentContainer;
- var savedBlockScopeContainer = blockScopeContainer;
- // Depending on what kind of node this is, we may have to adjust the current container
- // and block-container. If the current node is a container, then it is automatically
- // considered the current block-container as well. Also, for containers that we know
- // may contain locals, we eagerly initialize the .locals field. We do this because
- // it's highly likely that the .locals will be needed to place some child in (for example,
- // a parameter, or variable declaration).
- //
- // However, we do not proactively create the .locals for block-containers because it's
- // totally normal and common for block-containers to never actually have a block-scoped
- // variable in them. We don't want to end up allocating an object for every 'block' we
- // run into when most of them won't be necessary.
- //
- // Finally, if this is a block-container, then we clear out any existing .locals object
- // it may contain within it. This happens in incremental scenarios. Because we can be
- // reusing a node from a previous compilation, that node may have had 'locals' created
- // for it. We must clear this so we don't accidentally move any stale data forward from
- // a previous compilation.
- if (containerFlags & 1 /* IsContainer */) {
- if (node.kind !== 202 /* ArrowFunction */) {
- thisParentContainer = container;
- }
- container = blockScopeContainer = node;
- if (containerFlags & 32 /* HasLocals */) {
- container.locals = ts.createSymbolTable();
- }
- addToContainerChain(container);
+ return r && { path: r.path, extension: r.ext, packageId: packageId };
+ }
+ function noPackageId(r) {
+ return withPackageId(/*packageInfo*/ undefined, r);
+ }
+ function removeIgnoredPackageId(r) {
+ if (r) {
+ ts.Debug.assert(r.packageId === undefined);
+ return { path: r.path, ext: r.extension };
+ }
+ }
+ /**
+ * 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["TSConfig"] = 3] = "TSConfig";
+ Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
+ })(Extensions || (Extensions = {}));
+ /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
+ function resolvedTypeScriptOnly(resolved) {
+ if (!resolved) {
+ return undefined;
+ }
+ ts.Debug.assert(ts.extensionIsTS(resolved.extension));
+ return { fileName: resolved.path, packageId: resolved.packageId };
+ }
+ function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
+ var _a;
+ if (resultFromCache) {
+ (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
+ return resultFromCache;
+ }
+ return {
+ resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
+ failedLookupLocations: failedLookupLocations
+ };
+ }
+ function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
+ if (!ts.hasProperty(jsonContent, fieldName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
}
- else if (containerFlags & 2 /* IsBlockScopedContainer */) {
- blockScopeContainer = node;
- blockScopeContainer.locals = undefined;
+ return;
+ }
+ var value = jsonContent[fieldName];
+ if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
+ if (state.traceEnabled) {
+ // eslint-disable-next-line no-null/no-null
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
}
- if (containerFlags & 4 /* IsControlFlowContainer */) {
- var saveCurrentFlow = currentFlow;
- var saveBreakTarget = currentBreakTarget;
- var saveContinueTarget = currentContinueTarget;
- var saveReturnTarget = currentReturnTarget;
- var saveExceptionTarget = currentExceptionTarget;
- var saveActiveLabelList = activeLabelList;
- var saveHasExplicitReturn = hasExplicitReturn;
- var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
- !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
- // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
- // similarly to break statements that exit to a label just past the statement body.
- if (!isIIFE) {
- currentFlow = initFlowNode({ flags: 2 /* Start */ });
- if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
- currentFlow.node = node;
- }
- }
- // We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property initialization checks.
- currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
- currentExceptionTarget = undefined;
- currentBreakTarget = undefined;
- currentContinueTarget = undefined;
- activeLabelList = undefined;
- hasExplicitReturn = false;
- bindChildren(node);
- // Reset all reachability check related flags on node (for incremental scenarios)
- node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
- if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
- node.flags |= 256 /* HasImplicitReturn */;
- if (hasExplicitReturn)
- node.flags |= 512 /* HasExplicitReturn */;
- node.endFlowNode = currentFlow;
- }
- if (node.kind === 290 /* SourceFile */) {
- node.flags |= emitFlags;
- }
- if (currentReturnTarget) {
- addAntecedent(currentReturnTarget, currentFlow);
- currentFlow = finishFlowLabel(currentReturnTarget);
- if (node.kind === 162 /* Constructor */) {
- node.returnFlowNode = currentFlow;
- }
- }
- if (!isIIFE) {
- currentFlow = saveCurrentFlow;
- }
- currentBreakTarget = saveBreakTarget;
- currentContinueTarget = saveContinueTarget;
- currentReturnTarget = saveReturnTarget;
- currentExceptionTarget = saveExceptionTarget;
- activeLabelList = saveActiveLabelList;
- hasExplicitReturn = saveHasExplicitReturn;
+ return;
+ }
+ return value;
+ }
+ function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
+ var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
+ if (fileName === undefined) {
+ return;
+ }
+ if (!fileName) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
}
- else if (containerFlags & 64 /* IsInterface */) {
- seenThisKeyword = false;
- bindChildren(node);
- node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
+ return;
+ }
+ var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
+ }
+ return path;
+ }
+ function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
+ return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
+ || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
+ }
+ function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
+ return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
+ }
+ function readPackageJsonMainField(jsonContent, baseDirectory, state) {
+ return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
+ }
+ function readPackageJsonTypesVersionsField(jsonContent, state) {
+ var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
+ if (typesVersions === undefined)
+ return;
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
+ }
+ return typesVersions;
+ }
+ function readPackageJsonTypesVersionPaths(jsonContent, state) {
+ var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
+ if (typesVersions === undefined)
+ return;
+ if (state.traceEnabled) {
+ for (var key in typesVersions) {
+ if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
+ }
}
- else {
- bindChildren(node);
+ }
+ var result = getPackageJsonTypesVersionsPaths(typesVersions);
+ if (!result) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
}
- container = saveContainer;
- thisParentContainer = saveThisParentContainer;
- blockScopeContainer = savedBlockScopeContainer;
+ return;
}
- function bindChildren(node) {
- if (skipTransformFlagAggregation) {
- bindChildrenWorker(node);
+ var bestVersionKey = result.version, bestVersionPaths = result.paths;
+ if (typeof bestVersionPaths !== "object") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['".concat(bestVersionKey, "']"), "object", typeof bestVersionPaths);
}
- else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
- skipTransformFlagAggregation = true;
- bindChildrenWorker(node);
- skipTransformFlagAggregation = false;
- subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
+ return;
+ }
+ return result;
+ }
+ var typeScriptVersion;
+ /* @internal */
+ function getPackageJsonTypesVersionsPaths(typesVersions) {
+ if (!typeScriptVersion)
+ typeScriptVersion = new ts.Version(ts.version);
+ for (var key in typesVersions) {
+ if (!ts.hasProperty(typesVersions, key))
+ continue;
+ var keyRange = ts.VersionRange.tryParse(key);
+ if (keyRange === undefined) {
+ continue;
}
- else {
- var savedSubtreeTransformFlags = subtreeTransformFlags;
- subtreeTransformFlags = 0;
- bindChildrenWorker(node);
- subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
+ // return the first entry whose range matches the current compiler version.
+ if (keyRange.test(typeScriptVersion)) {
+ return { version: key, paths: typesVersions[key] };
}
}
- function bindEachFunctionsFirst(nodes) {
- bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
- bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
+ }
+ ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
+ function getEffectiveTypeRoots(options, host) {
+ if (options.typeRoots) {
+ return options.typeRoots;
}
- function bindEach(nodes, bindFunction) {
- if (bindFunction === void 0) { bindFunction = bind; }
- if (nodes === undefined) {
- return;
+ var currentDirectory;
+ if (options.configFilePath) {
+ currentDirectory = ts.getDirectoryPath(options.configFilePath);
+ }
+ else if (host.getCurrentDirectory) {
+ currentDirectory = host.getCurrentDirectory();
+ }
+ if (currentDirectory !== undefined) {
+ return getDefaultTypeRoots(currentDirectory, host);
+ }
+ }
+ 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) {
+ var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
+ if (host.directoryExists(atTypes)) {
+ (typeRoots || (typeRoots = [])).push(atTypes);
+ }
+ return undefined;
+ });
+ return typeRoots;
+ }
+ var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
+ function arePathsEqual(path1, path2, host) {
+ var useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
+ return ts.comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */;
+ }
+ /**
+ * @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, redirectedReference, cache) {
+ var traceEnabled = isTraceEnabled(options, host);
+ if (redirectedReference) {
+ options = redirectedReference.commandLine.options;
+ }
+ var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined;
+ var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined;
+ var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName, /*mode*/ undefined);
+ if (result) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile);
+ if (redirectedReference)
+ trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
+ trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory);
+ traceResult(result);
}
- if (skipTransformFlagAggregation) {
- ts.forEach(nodes, bindFunction);
+ return result;
+ }
+ var typeRoots = getEffectiveTypeRoots(options, host);
+ if (traceEnabled) {
+ if (containingFile === undefined) {
+ if (typeRoots === undefined) {
+ trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
+ }
+ else {
+ trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
+ }
}
else {
- var savedSubtreeTransformFlags = subtreeTransformFlags;
- subtreeTransformFlags = 0 /* None */;
- var nodeArrayFlags = 0 /* None */;
- for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
- var node = nodes_2[_i];
- bindFunction(node);
- nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
+ if (typeRoots === undefined) {
+ trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
+ }
+ else {
+ trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
}
- nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
- subtreeTransformFlags |= savedSubtreeTransformFlags;
+ }
+ if (redirectedReference) {
+ trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
}
}
- function bindEachChild(node) {
- ts.forEachChild(node, bind, bindEach);
+ var failedLookupLocations = [];
+ var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.AllFeatures, conditions: ["node", "require", "types"] };
+ var resolved = primaryLookup();
+ var primary = true;
+ if (!resolved) {
+ resolved = secondaryLookup();
+ primary = false;
}
- function bindChildrenWorker(node) {
- if (checkUnreachable(node)) {
- bindEachChild(node);
- bindJSDoc(node);
- return;
+ var resolvedTypeReferenceDirective;
+ if (resolved) {
+ var fileName = resolved.fileName, packageId = resolved.packageId;
+ var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
+ resolvedTypeReferenceDirective = {
+ primary: primary,
+ resolvedFileName: resolvedFileName,
+ originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName,
+ packageId: packageId,
+ isExternalLibraryImport: pathContainsNodeModules(fileName),
+ };
+ }
+ result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
+ perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ undefined, result);
+ if (traceEnabled)
+ traceResult(result);
+ return result;
+ function traceResult(result) {
+ var _a;
+ if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
}
- if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
- node.flowNode = currentFlow;
+ else if (result.resolvedTypeReferenceDirective.packageId) {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary);
}
- switch (node.kind) {
- case 229 /* WhileStatement */:
- bindWhileStatement(node);
- break;
- case 228 /* DoStatement */:
- bindDoStatement(node);
- break;
- case 230 /* ForStatement */:
- bindForStatement(node);
- break;
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- bindForInOrForOfStatement(node);
- break;
- case 227 /* IfStatement */:
- bindIfStatement(node);
- break;
- case 235 /* ReturnStatement */:
- case 239 /* ThrowStatement */:
- bindReturnOrThrow(node);
- break;
- case 234 /* BreakStatement */:
- case 233 /* ContinueStatement */:
- bindBreakOrContinueStatement(node);
- break;
- case 240 /* TryStatement */:
- bindTryStatement(node);
- break;
- case 237 /* SwitchStatement */:
- bindSwitchStatement(node);
- break;
- case 251 /* CaseBlock */:
- bindCaseBlock(node);
- break;
- case 277 /* CaseClause */:
- bindCaseClause(node);
- break;
- case 226 /* ExpressionStatement */:
- bindExpressionStatement(node);
- break;
- case 238 /* LabeledStatement */:
- bindLabeledStatement(node);
- break;
- case 207 /* PrefixUnaryExpression */:
- bindPrefixUnaryExpressionFlow(node);
- break;
- case 208 /* PostfixUnaryExpression */:
- bindPostfixUnaryExpressionFlow(node);
- break;
- case 209 /* BinaryExpression */:
- bindBinaryExpressionFlow(node);
- break;
- case 203 /* DeleteExpression */:
- bindDeleteExpressionFlow(node);
- break;
- case 210 /* ConditionalExpression */:
- bindConditionalExpressionFlow(node);
- break;
- case 242 /* VariableDeclaration */:
- bindVariableDeclarationFlow(node);
- break;
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- bindAccessExpressionFlow(node);
- break;
- case 196 /* CallExpression */:
- bindCallExpressionFlow(node);
- break;
- case 218 /* NonNullExpression */:
- bindNonNullExpressionFlow(node);
- break;
- case 322 /* JSDocTypedefTag */:
- case 315 /* JSDocCallbackTag */:
- case 316 /* JSDocEnumTag */:
- bindJSDocTypeAlias(node);
- break;
- // In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 290 /* SourceFile */: {
- bindEachFunctionsFirst(node.statements);
- bind(node.endOfFileToken);
- break;
- }
- case 223 /* Block */:
- case 250 /* ModuleBlock */:
- bindEachFunctionsFirst(node.statements);
- break;
- default:
- bindEachChild(node);
- break;
+ else {
+ trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary);
}
- bindJSDoc(node);
}
- function isNarrowingExpression(expr) {
- switch (expr.kind) {
- case 75 /* Identifier */:
- case 104 /* ThisKeyword */:
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- return containsNarrowableReference(expr);
- case 196 /* CallExpression */:
- return hasNarrowableArgument(expr);
- case 200 /* ParenthesizedExpression */:
- return isNarrowingExpression(expr.expression);
- case 209 /* BinaryExpression */:
- return isNarrowingBinaryExpression(expr);
- case 207 /* PrefixUnaryExpression */:
- return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
- case 204 /* TypeOfExpression */:
- return isNarrowingExpression(expr.expression);
+ function primaryLookup() {
+ // Check primary library paths
+ if (typeRoots && typeRoots.length) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
+ }
+ return ts.firstDefined(typeRoots, function (typeRoot) {
+ var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
+ var candidateDirectory = ts.getDirectoryPath(candidate);
+ var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
+ if (!directoryExists && traceEnabled) {
+ trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
+ }
+ return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
+ });
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
+ }
}
- return false;
}
- function isNarrowableReference(expr) {
- return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
- (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
- ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
+ 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_4;
+ if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
+ var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
+ result_4 = searchResult && searchResult.value;
+ }
+ else {
+ var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
+ result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
+ }
+ return resolvedTypeScriptOnly(result_4);
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
+ }
+ }
}
- function containsNarrowableReference(expr) {
- return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
+ }
+ 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;
}
- function hasNarrowableArgument(expr) {
- if (expr.arguments) {
- for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
- var argument = _a[_i];
- if (containsNarrowableReference(argument)) {
- return true;
+ // Walk the primary type lookup locations
+ var result = [];
+ if (host.directoryExists && host.getDirectories) {
+ var typeRoots = getEffectiveTypeRoots(options, host);
+ if (typeRoots) {
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
+ if (host.directoryExists(root)) {
+ for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
+ var typeDirectivePath = _b[_a];
+ var normalized = ts.normalizePath(typeDirectivePath);
+ var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
+ // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
+ // See `createNotNeededPackageJSON` in the types-publisher` repo.
+ // eslint-disable-next-line no-null/no-null
+ var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
+ if (!isNotNeededPackage) {
+ var baseFileName = ts.getBaseFileName(normalized);
+ // At this stage, skip results with leading dot.
+ if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
+ // Return just the type directive names
+ result.push(baseFileName);
+ }
+ }
+ }
}
}
}
- if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
- containsNarrowableReference(expr.expression.expression)) {
- return true;
- }
- return false;
}
- function isNarrowingTypeofOperands(expr1, expr2) {
- return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
+ return result;
+ }
+ ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
+ /*@internal*/
+ function createCacheWithRedirects(options) {
+ var ownMap = new ts.Map();
+ var redirectsMap = new ts.Map();
+ return {
+ getOwnMap: getOwnMap,
+ redirectsMap: redirectsMap,
+ getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
+ clear: clear,
+ setOwnOptions: setOwnOptions,
+ setOwnMap: setOwnMap
+ };
+ function getOwnMap() {
+ return ownMap;
}
- function isNarrowableInOperands(left, right) {
- return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
+ function setOwnOptions(newOptions) {
+ options = newOptions;
}
- function isNarrowingBinaryExpression(expr) {
- switch (expr.operatorToken.kind) {
- case 62 /* EqualsToken */:
- return containsNarrowableReference(expr.left);
- case 34 /* EqualsEqualsToken */:
- case 35 /* ExclamationEqualsToken */:
- case 36 /* EqualsEqualsEqualsToken */:
- case 37 /* ExclamationEqualsEqualsToken */:
- return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
- isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
- case 98 /* InstanceOfKeyword */:
- return isNarrowableOperand(expr.left);
- case 97 /* InKeyword */:
- return isNarrowableInOperands(expr.left, expr.right);
- case 27 /* CommaToken */:
- return isNarrowingExpression(expr.right);
- }
- return false;
+ function setOwnMap(newOwnMap) {
+ ownMap = newOwnMap;
}
- function isNarrowableOperand(expr) {
- switch (expr.kind) {
- case 200 /* ParenthesizedExpression */:
- return isNarrowableOperand(expr.expression);
- case 209 /* BinaryExpression */:
- switch (expr.operatorToken.kind) {
- case 62 /* EqualsToken */:
- return isNarrowableOperand(expr.left);
- case 27 /* CommaToken */:
- return isNarrowableOperand(expr.right);
- }
+ function getOrCreateMapOfCacheRedirects(redirectedReference) {
+ if (!redirectedReference) {
+ return ownMap;
}
- return containsNarrowableReference(expr);
+ var path = redirectedReference.sourceFile.path;
+ var redirects = redirectsMap.get(path);
+ if (!redirects) {
+ // Reuse map if redirected reference map uses same resolution
+ redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new ts.Map() : ownMap;
+ redirectsMap.set(path, redirects);
+ }
+ return redirects;
}
- function createBranchLabel() {
- return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
+ function clear() {
+ ownMap.clear();
+ redirectsMap.clear();
}
- function createLoopLabel() {
- return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
+ }
+ ts.createCacheWithRedirects = createCacheWithRedirects;
+ function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) {
+ var cache;
+ return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries };
+ function getPackageJsonInfo(packageJsonPath) {
+ return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName));
}
- function createReduceLabel(target, antecedents, antecedent) {
- return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
+ function setPackageJsonInfo(packageJsonPath, info) {
+ (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info);
}
- function setFlowNodeReferenced(flow) {
- // On first reference we set the Referenced flag, thereafter we set the Shared flag
- flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
+ function clear() {
+ cache = undefined;
}
- function addAntecedent(label, antecedent) {
- if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
- (label.antecedents || (label.antecedents = [])).push(antecedent);
- setFlowNodeReferenced(antecedent);
- }
+ function entries() {
+ var iter = cache === null || cache === void 0 ? void 0 : cache.entries();
+ return iter ? ts.arrayFrom(iter) : [];
}
- function createFlowCondition(flags, antecedent, expression) {
- if (antecedent.flags & 1 /* Unreachable */) {
- return antecedent;
- }
- if (!expression) {
- return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
- }
- if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
- expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
- !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
- return unreachableFlow;
- }
- if (!isNarrowingExpression(expression)) {
- return antecedent;
- }
- setFlowNodeReferenced(antecedent);
- return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
+ }
+ function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
+ var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
+ var result = cache.get(key);
+ if (!result) {
+ result = create();
+ cache.set(key, result);
}
- function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
- setFlowNodeReferenced(antecedent);
- return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
+ return result;
+ }
+ function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) {
+ if (!options.configFile)
+ return;
+ if (directoryToModuleNameMap.redirectsMap.size === 0) {
+ // The own map will be for projectCompilerOptions
+ ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0);
+ ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0);
+ ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0);
+ directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap());
+ moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap());
}
- function createFlowMutation(flags, antecedent, node) {
- setFlowNodeReferenced(antecedent);
- var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
- if (currentExceptionTarget) {
- addAntecedent(currentExceptionTarget, result);
+ else {
+ // Set correct own map
+ ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0);
+ var ref = {
+ sourceFile: options.configFile,
+ commandLine: { options: options }
+ };
+ directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
+ moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
+ }
+ directoryToModuleNameMap.setOwnOptions(options);
+ moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options);
+ }
+ function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) {
+ return {
+ getOrCreateCacheForDirectory: getOrCreateCacheForDirectory,
+ clear: clear,
+ update: update,
+ };
+ function clear() {
+ directoryToModuleNameMap.clear();
+ }
+ function update(options) {
+ updateRedirectsMap(options, directoryToModuleNameMap);
+ }
+ function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
+ var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
+ return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return createModeAwareCache(); });
+ }
+ }
+ /* @internal */
+ function createModeAwareCache() {
+ var underlying = new ts.Map();
+ var memoizedReverseKeys = new ts.Map();
+ var cache = {
+ get: function (specifier, mode) {
+ return underlying.get(getUnderlyingCacheKey(specifier, mode));
+ },
+ set: function (specifier, mode, value) {
+ underlying.set(getUnderlyingCacheKey(specifier, mode), value);
+ return cache;
+ },
+ delete: function (specifier, mode) {
+ underlying.delete(getUnderlyingCacheKey(specifier, mode));
+ return cache;
+ },
+ has: function (specifier, mode) {
+ return underlying.has(getUnderlyingCacheKey(specifier, mode));
+ },
+ forEach: function (cb) {
+ return underlying.forEach(function (elem, key) {
+ var _a = memoizedReverseKeys.get(key), specifier = _a[0], mode = _a[1];
+ return cb(elem, specifier, mode);
+ });
+ },
+ size: function () {
+ return underlying.size;
}
+ };
+ return cache;
+ function getUnderlyingCacheKey(specifier, mode) {
+ var result = mode === undefined ? specifier : "".concat(mode, "|").concat(specifier);
+ memoizedReverseKeys.set(result, [specifier, mode]);
return result;
}
- function createFlowCall(antecedent, node) {
- setFlowNodeReferenced(antecedent);
- return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
+ }
+ ts.createModeAwareCache = createModeAwareCache;
+ /* @internal */
+ function zipToModeAwareCache(file, keys, values) {
+ ts.Debug.assert(keys.length === values.length);
+ var map = createModeAwareCache();
+ for (var i = 0; i < keys.length; ++i) {
+ map.set(keys[i], ts.getModeForResolutionAtIndex(file, i), values[i]);
}
- function finishFlowLabel(flow) {
- var antecedents = flow.antecedents;
- if (!antecedents) {
- return unreachableFlow;
- }
- if (antecedents.length === 1) {
- return antecedents[0];
- }
- return flow;
+ return map;
+ }
+ ts.zipToModeAwareCache = zipToModeAwareCache;
+ function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) {
+ var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options)));
+ moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options));
+ var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName);
+ return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } });
+ function clear() {
+ preDirectoryResolutionCache.clear();
+ moduleNameToDirectoryMap.clear();
+ packageJsonInfoCache.clear();
}
- function isStatementCondition(node) {
- var parent = node.parent;
- switch (parent.kind) {
- case 227 /* IfStatement */:
- case 229 /* WhileStatement */:
- case 228 /* DoStatement */:
- return parent.expression === node;
- case 230 /* ForStatement */:
- case 210 /* ConditionalExpression */:
- return parent.condition === node;
- }
- return false;
+ function update(options) {
+ updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap);
}
- function isLogicalExpression(node) {
- while (true) {
- if (node.kind === 200 /* ParenthesizedExpression */) {
- node = node.expression;
+ function getOrCreateCacheForModuleName(nonRelativeModuleName, mode, redirectedReference) {
+ ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
+ return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, mode === undefined ? nonRelativeModuleName : "".concat(mode, "|").concat(nonRelativeModuleName), createPerModuleNameCache);
+ }
+ function createPerModuleNameCache() {
+ var directoryPathMap = new ts.Map();
+ return { get: get, set: set };
+ 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;
}
- else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
- node = node.operand;
+ directoryPathMap.set(path, result);
+ var resolvedFileName = result.resolvedModule &&
+ (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
+ // find common prefix between directory and resolved file name
+ // this common prefix should be the shortest path that has the same resolution
+ // directory: /a/b/c/d/e
+ // resolvedFileName: /a/b/foo.d.ts
+ // commonPrefix: /a/b
+ // for failed lookups cache the result for every directory up to root
+ var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
+ var current = path;
+ while (current !== commonPrefix) {
+ var parent = ts.getDirectoryPath(current);
+ if (parent === current || directoryPathMap.has(parent)) {
+ break;
+ }
+ directoryPathMap.set(parent, result);
+ current = parent;
}
- else {
- return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
- node.operatorToken.kind === 56 /* BarBarToken */ ||
- node.operatorToken.kind === 60 /* QuestionQuestionToken */);
+ }
+ function getCommonPrefix(directory, resolution) {
+ var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
+ // find first position where directory and resolution differs
+ var i = 0;
+ var limit = Math.min(directory.length, resolutionDirectory.length);
+ while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
+ i++;
+ }
+ if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
+ return directory;
+ }
+ var rootLength = ts.getRootLength(directory);
+ if (i < rootLength) {
+ return undefined;
+ }
+ var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
+ if (sep === -1) {
+ return undefined;
}
+ return directory.substr(0, Math.max(sep, rootLength));
}
}
- function isTopLevelLogicalExpression(node) {
- while (ts.isParenthesizedExpression(node.parent) ||
- ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
- node = node.parent;
- }
- return !isStatementCondition(node) &&
- !isLogicalExpression(node.parent) &&
- !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) {
+ var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options)));
+ packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName));
+ return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear });
+ function clear() {
+ preDirectoryResolutionCache.clear();
+ packageJsonInfoCache.clear();
}
- function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
- var savedTrueTarget = currentTrueTarget;
- var savedFalseTarget = currentFalseTarget;
- currentTrueTarget = trueTarget;
- currentFalseTarget = falseTarget;
- action(value);
- currentTrueTarget = savedTrueTarget;
- currentFalseTarget = savedFalseTarget;
+ }
+ ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache;
+ function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
+ if (!perFolderCache)
+ return undefined;
+ return perFolderCache.get(moduleName, mode);
+ }
+ ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (redirectedReference) {
+ compilerOptions = redirectedReference.commandLine.options;
}
- function bindCondition(node, trueTarget, falseTarget) {
- doWithConditionalBranches(bind, node, trueTarget, falseTarget);
- if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
- addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
- addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
+ if (redirectedReference) {
+ trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
}
}
- function bindIterativeStatement(node, breakTarget, continueTarget) {
- var saveBreakTarget = currentBreakTarget;
- var saveContinueTarget = currentContinueTarget;
- currentBreakTarget = breakTarget;
- currentContinueTarget = continueTarget;
- bind(node);
- currentBreakTarget = saveBreakTarget;
- currentContinueTarget = saveContinueTarget;
- }
- function setContinueTarget(node, target) {
- var label = activeLabelList;
- while (label && node.parent.kind === 238 /* LabeledStatement */) {
- label.continueTarget = target;
- label = label.next;
- node = node.parent;
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
+ var result = perFolderCache && perFolderCache.get(moduleName, resolutionMode);
+ if (result) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
- return target;
- }
- function bindWhileStatement(node) {
- var preWhileLabel = setContinueTarget(node, createLoopLabel());
- var preBodyLabel = createBranchLabel();
- var postWhileLabel = createBranchLabel();
- addAntecedent(preWhileLabel, currentFlow);
- currentFlow = preWhileLabel;
- bindCondition(node.expression, preBodyLabel, postWhileLabel);
- currentFlow = finishFlowLabel(preBodyLabel);
- bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
- addAntecedent(preWhileLabel, currentFlow);
- currentFlow = finishFlowLabel(postWhileLabel);
- }
- function bindDoStatement(node) {
- var preDoLabel = createLoopLabel();
- var preConditionLabel = setContinueTarget(node, createBranchLabel());
- var postDoLabel = createBranchLabel();
- addAntecedent(preDoLabel, currentFlow);
- currentFlow = preDoLabel;
- bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
- addAntecedent(preConditionLabel, currentFlow);
- currentFlow = finishFlowLabel(preConditionLabel);
- bindCondition(node.expression, preDoLabel, postDoLabel);
- currentFlow = finishFlowLabel(postDoLabel);
}
- function bindForStatement(node) {
- var preLoopLabel = setContinueTarget(node, createLoopLabel());
- var preBodyLabel = createBranchLabel();
- var postLoopLabel = createBranchLabel();
- bind(node.initializer);
- addAntecedent(preLoopLabel, currentFlow);
- currentFlow = preLoopLabel;
- bindCondition(node.condition, preBodyLabel, postLoopLabel);
- currentFlow = finishFlowLabel(preBodyLabel);
- bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
- bind(node.incrementor);
- addAntecedent(preLoopLabel, currentFlow);
- currentFlow = finishFlowLabel(postLoopLabel);
+ else {
+ var moduleResolution = compilerOptions.moduleResolution;
+ if (moduleResolution === undefined) {
+ switch (ts.getEmitModuleKind(compilerOptions)) {
+ case ts.ModuleKind.CommonJS:
+ moduleResolution = ts.ModuleResolutionKind.NodeJs;
+ break;
+ case ts.ModuleKind.Node12:
+ moduleResolution = ts.ModuleResolutionKind.Node12;
+ break;
+ case ts.ModuleKind.NodeNext:
+ moduleResolution = ts.ModuleResolutionKind.NodeNext;
+ break;
+ default:
+ moduleResolution = ts.ModuleResolutionKind.Classic;
+ break;
+ }
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
+ }
+ }
+ ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.Node12:
+ result = node12ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
+ break;
+ case ts.ModuleResolutionKind.NodeNext:
+ result = nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
+ break;
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
+ break;
+ default:
+ return ts.Debug.fail("Unexpected moduleResolution: ".concat(moduleResolution));
+ }
+ if (result && result.resolvedModule)
+ ts.perfLogger.logInfoEvent("Module \"".concat(moduleName, "\" resolved to \"").concat(result.resolvedModule.resolvedFileName, "\""));
+ ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
+ if (perFolderCache) {
+ perFolderCache.set(moduleName, resolutionMode, result);
+ if (!ts.isExternalModuleNameRelative(moduleName)) {
+ // put result in per-module name cache
+ cache.getOrCreateCacheForModuleName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result);
+ }
+ }
}
- function bindForInOrForOfStatement(node) {
- var preLoopLabel = setContinueTarget(node, createLoopLabel());
- var postLoopLabel = createBranchLabel();
- bind(node.expression);
- addAntecedent(preLoopLabel, currentFlow);
- currentFlow = preLoopLabel;
- if (node.kind === 232 /* ForOfStatement */) {
- bind(node.awaitModifier);
+ if (traceEnabled) {
+ if (result.resolvedModule) {
+ if (result.resolvedModule.packageId) {
+ trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, ts.packageIdToString(result.resolvedModule.packageId));
+ }
+ else {
+ trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
+ }
}
- addAntecedent(postLoopLabel, currentFlow);
- bind(node.initializer);
- if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
- bindAssignmentTargetFlow(node.initializer);
+ else {
+ trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
}
- bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
- addAntecedent(preLoopLabel, currentFlow);
- currentFlow = finishFlowLabel(postLoopLabel);
}
- function bindIfStatement(node) {
- var thenLabel = createBranchLabel();
- var elseLabel = createBranchLabel();
- var postIfLabel = createBranchLabel();
- bindCondition(node.expression, thenLabel, elseLabel);
- currentFlow = finishFlowLabel(thenLabel);
- bind(node.thenStatement);
- addAntecedent(postIfLabel, currentFlow);
- currentFlow = finishFlowLabel(elseLabel);
- bind(node.elseStatement);
- addAntecedent(postIfLabel, currentFlow);
- currentFlow = finishFlowLabel(postIfLabel);
+ 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/ to '/root/components/folder1/',
+ * // it is rooted so it will be final candidate location
+ * }
+ *
+ * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
+ * they were in the same location. For example lets say there are two files
+ * '/local/src/content/file1.ts'
+ * '/shared/components/contracts/src/content/protocols/file2.ts'
+ * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
+ * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
+ * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
+ * root dirs were merged together.
+ * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
+ * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
+ * '/local/src/content/protocols/file2' and try to load it - failure.
+ * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
+ * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
+ * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
+ */
+ function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
+ var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
+ if (resolved)
+ return resolved.value;
+ if (!ts.isExternalModuleNameRelative(moduleName)) {
+ return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
+ }
+ else {
+ return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
}
- function bindReturnOrThrow(node) {
- bind(node.expression);
- if (node.kind === 235 /* ReturnStatement */) {
- hasExplicitReturn = true;
- if (currentReturnTarget) {
- addAntecedent(currentReturnTarget, currentFlow);
+ }
+ function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
+ var _a;
+ var _b = state.compilerOptions, baseUrl = _b.baseUrl, paths = _b.paths, configFile = _b.configFile;
+ if (paths && !ts.pathIsRelative(moduleName)) {
+ if (state.traceEnabled) {
+ if (baseUrl) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
}
+ trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
- currentFlow = unreachableFlow;
+ var baseDirectory = ts.getPathsBasePath(state.compilerOptions, state.host); // Always defined when 'paths' is defined
+ var pathPatterns = (configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) ? (_a = configFile.configFileSpecs).pathPatterns || (_a.pathPatterns = ts.tryParsePatterns(paths)) : undefined;
+ return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, /*onlyRecordFailures*/ false, state);
}
- function findActiveLabel(name) {
- for (var label = activeLabelList; label; label = label.next) {
- if (label.name === name) {
- return label;
- }
- }
+ }
+ function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
+ if (!state.compilerOptions.rootDirs) {
return undefined;
}
- function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
- var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
- if (flowLabel) {
- addAntecedent(flowLabel, currentFlow);
- currentFlow = unreachableFlow;
- }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
}
- function bindBreakOrContinueStatement(node) {
- bind(node.label);
- if (node.label) {
- var activeLabel = findActiveLabel(node.label.escapedText);
- if (activeLabel) {
- activeLabel.referenced = true;
- bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
- }
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ var matchedRootDir;
+ var matchedNormalizedPrefix;
+ for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
+ var rootDir = _a[_i];
+ // rootDirs are expected to be absolute
+ // in case of tsconfig.json this will happen automatically - compiler will expand relative names
+ // using location of tsconfig.json as base location
+ var normalizedRoot = ts.normalizePath(rootDir);
+ if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
+ normalizedRoot += ts.directorySeparator;
}
- else {
- bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
+ var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
+ (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
}
- }
- function bindTryStatement(node) {
- // We conservatively assume that *any* code in the try block can cause an exception, but we only need
- // to track code that causes mutations (because only mutations widen the possible control flow type of
- // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
- // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
- // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
- // represent exceptions that occur before any mutations.
- var saveReturnTarget = currentReturnTarget;
- var saveExceptionTarget = currentExceptionTarget;
- var normalExitLabel = createBranchLabel();
- var returnLabel = createBranchLabel();
- var exceptionLabel = createBranchLabel();
- if (node.finallyBlock) {
- currentReturnTarget = returnLabel;
+ if (isLongestMatchingPrefix) {
+ matchedNormalizedPrefix = normalizedRoot;
+ matchedRootDir = rootDir;
}
- addAntecedent(exceptionLabel, currentFlow);
- currentExceptionTarget = exceptionLabel;
- bind(node.tryBlock);
- addAntecedent(normalExitLabel, currentFlow);
- if (node.catchClause) {
- // Start of catch clause is the target of exceptions from try block.
- currentFlow = finishFlowLabel(exceptionLabel);
- // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
- // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
- // acts like a second try block.
- exceptionLabel = createBranchLabel();
- addAntecedent(exceptionLabel, currentFlow);
- currentExceptionTarget = exceptionLabel;
- bind(node.catchClause);
- addAntecedent(normalExitLabel, currentFlow);
+ }
+ if (matchedNormalizedPrefix) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
}
- currentReturnTarget = saveReturnTarget;
- currentExceptionTarget = saveExceptionTarget;
- if (node.finallyBlock) {
- // Possible ways control can reach the finally block:
- // 1) Normal completion of try block of a try-finally or try-catch-finally
- // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
- // 3) Return in try or catch block of a try-finally or try-catch-finally
- // 4) Exception in try block of a try-finally
- // 5) Exception in catch block of a try-catch-finally
- // When analyzing a control flow graph that starts inside a finally block we want to consider all
- // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
- // the finally block, we only want to consider the first two (if we're past a finally block then it
- // must have completed normally). Likewise, when analyzing a control flow graph from return statements
- // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
- // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
- // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
- // node, the pre-finally label is temporarily switched to the reduced antecedent set.
- var finallyLabel = createBranchLabel();
- finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
- currentFlow = finallyLabel;
- bind(node.finallyBlock);
- if (currentFlow.flags & 1 /* Unreachable */) {
- // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
- currentFlow = unreachableFlow;
- }
- else {
- // If we have an IIFE return target and return statements in the try or catch blocks, add a control
- // flow that goes back through the finally block and back through only the return statements.
- if (currentReturnTarget && returnLabel.antecedents) {
- addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
- }
- // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
- // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
- // result in an unreachable current control flow.
- currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
- }
+ var suffix = candidate.substr(matchedNormalizedPrefix.length);
+ // first - try to load from a initial location
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
}
- else {
- currentFlow = finishFlowLabel(normalExitLabel);
+ var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
+ if (resolvedFileName) {
+ return resolvedFileName;
}
- }
- function bindSwitchStatement(node) {
- var postSwitchLabel = createBranchLabel();
- bind(node.expression);
- var saveBreakTarget = currentBreakTarget;
- var savePreSwitchCaseFlow = preSwitchCaseFlow;
- currentBreakTarget = postSwitchLabel;
- preSwitchCaseFlow = currentFlow;
- bind(node.caseBlock);
- addAntecedent(postSwitchLabel, currentFlow);
- var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
- // We mark a switch statement as possibly exhaustive if it has no default clause and if all
- // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
- // this property in control flow analysis, it's there only for backwards compatibility.
- node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
- if (!hasDefault) {
- addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
}
- currentBreakTarget = saveBreakTarget;
- preSwitchCaseFlow = savePreSwitchCaseFlow;
- currentFlow = finishFlowLabel(postSwitchLabel);
- }
- function bindCaseBlock(node) {
- var savedSubtreeTransformFlags = subtreeTransformFlags;
- subtreeTransformFlags = 0;
- var clauses = node.clauses;
- var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
- var fallthroughFlow = unreachableFlow;
- for (var i = 0; i < clauses.length; i++) {
- var clauseStart = i;
- while (!clauses[i].statements.length && i + 1 < clauses.length) {
- bind(clauses[i]);
- i++;
+ // then try to resolve using remaining entries in rootDirs
+ for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
+ var rootDir = _c[_b];
+ if (rootDir === matchedRootDir) {
+ // skip the initially matched entry
+ continue;
}
- var preCaseLabel = createBranchLabel();
- addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
- addAntecedent(preCaseLabel, fallthroughFlow);
- currentFlow = finishFlowLabel(preCaseLabel);
- var clause = clauses[i];
- bind(clause);
- fallthroughFlow = currentFlow;
- if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
- clause.fallthroughFlowNode = currentFlow;
+ var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
+ }
+ var baseDirectory = ts.getDirectoryPath(candidate_1);
+ var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
+ if (resolvedFileName_1) {
+ return resolvedFileName_1;
}
}
- clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
- subtreeTransformFlags |= savedSubtreeTransformFlags;
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
+ }
}
- function bindCaseClause(node) {
- var saveCurrentFlow = currentFlow;
- currentFlow = preSwitchCaseFlow;
- bind(node.expression);
- currentFlow = saveCurrentFlow;
- bindEach(node.statements);
+ return undefined;
+ }
+ function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
+ var baseUrl = state.compilerOptions.baseUrl;
+ if (!baseUrl) {
+ return undefined;
}
- function bindExpressionStatement(node) {
- bind(node.expression);
- // A top level call expression with a dotted function name and at least one argument
- // is potentially an assertion and is therefore included in the control flow.
- if (node.expression.kind === 196 /* CallExpression */) {
- var call = node.expression;
- if (ts.isDottedName(call.expression)) {
- currentFlow = createFlowCall(currentFlow, call);
- }
- }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
}
- function bindLabeledStatement(node) {
- var postStatementLabel = createBranchLabel();
- activeLabelList = {
- next: activeLabelList,
- name: node.label.escapedText,
- breakTarget: postStatementLabel,
- continueTarget: undefined,
- referenced: false
- };
- bind(node.label);
- bind(node.statement);
- if (!activeLabelList.referenced && !options.allowUnusedLabels) {
- errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
- }
- activeLabelList = activeLabelList.next;
- addAntecedent(postStatementLabel, currentFlow);
- currentFlow = finishFlowLabel(postStatementLabel);
+ var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
}
- function bindDestructuringTargetFlow(node) {
- if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
- bindAssignmentTargetFlow(node.left);
- }
- else {
- bindAssignmentTargetFlow(node);
- }
+ return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ }
+ /**
+ * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
+ * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
+ * Throws an error if the module can't be resolved.
+ */
+ /* @internal */
+ function resolveJSModule(moduleName, initialDir, host) {
+ var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
+ if (!resolvedModule) {
+ throw new Error("Could not resolve JS module '".concat(moduleName, "' starting at '").concat(initialDir, "'. Looked in: ").concat(failedLookupLocations.join(", ")));
}
- function bindAssignmentTargetFlow(node) {
- if (isNarrowableReference(node)) {
- currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
+ return resolvedModule.resolvedFileName;
+ }
+ ts.resolveJSModule = resolveJSModule;
+ /* @internal */
+ function tryResolveJSModule(moduleName, initialDir, host) {
+ return tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
+ }
+ ts.tryResolveJSModule = tryResolveJSModule;
+ /* @internal */
+ var NodeResolutionFeatures;
+ (function (NodeResolutionFeatures) {
+ NodeResolutionFeatures[NodeResolutionFeatures["None"] = 0] = "None";
+ // resolving `#local` names in your own package.json
+ NodeResolutionFeatures[NodeResolutionFeatures["Imports"] = 2] = "Imports";
+ // resolving `your-own-name` from your own package.json
+ NodeResolutionFeatures[NodeResolutionFeatures["SelfName"] = 4] = "SelfName";
+ // respecting the `.exports` member of packages' package.json files and its (conditional) mappings of export names
+ NodeResolutionFeatures[NodeResolutionFeatures["Exports"] = 8] = "Exports";
+ // allowing `*` in the LHS of an export to be followed by more content, eg `"./whatever/*.js"`
+ // not currently backported to node 12 - https://github.com/nodejs/Release/issues/690
+ NodeResolutionFeatures[NodeResolutionFeatures["ExportsPatternTrailers"] = 16] = "ExportsPatternTrailers";
+ NodeResolutionFeatures[NodeResolutionFeatures["AllFeatures"] = 30] = "AllFeatures";
+ NodeResolutionFeatures[NodeResolutionFeatures["EsmMode"] = 32] = "EsmMode";
+ })(NodeResolutionFeatures || (NodeResolutionFeatures = {}));
+ function node12ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
+ return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.Imports | NodeResolutionFeatures.SelfName | NodeResolutionFeatures.Exports, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
+ }
+ function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
+ return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.AllFeatures, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
+ }
+ function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features
+ var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0;
+ return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference);
+ }
+ var jsOnlyExtensions = [Extensions.JavaScript];
+ var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
+ var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false);
+ var tsconfigExtensions = [Extensions.TSConfig];
+ function tryResolveJSModuleWorker(moduleName, initialDir, host) {
+ return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
+ }
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
+ return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
+ var _a, _b;
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ // conditions are only used by the node12/nodenext resolver - there's no priority order in the list,
+ //it's essentially a set (priority is determined by object insertion order in the object we look at).
+ var state = {
+ compilerOptions: compilerOptions,
+ host: host,
+ traceEnabled: traceEnabled,
+ failedLookupLocations: failedLookupLocations,
+ packageJsonInfoCache: cache,
+ features: features,
+ conditions: features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]
+ };
+ var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
+ return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache);
+ function tryResolve(extensions) {
+ var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
+ var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
+ if (resolved) {
+ return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
}
- else if (node.kind === 192 /* ArrayLiteralExpression */) {
- for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
- var e = _a[_i];
- if (e.kind === 213 /* SpreadElement */) {
- bindAssignmentTargetFlow(e.expression);
- }
- else {
- bindDestructuringTargetFlow(e);
- }
+ if (!ts.isExternalModuleNameRelative(moduleName)) {
+ var resolved_1;
+ if (features & NodeResolutionFeatures.Imports && ts.startsWith(moduleName, "#")) {
+ resolved_1 = loadModuleFromImports(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
}
- }
- else if (node.kind === 193 /* ObjectLiteralExpression */) {
- for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
- var p = _c[_b];
- if (p.kind === 281 /* PropertyAssignment */) {
- bindDestructuringTargetFlow(p.initializer);
- }
- else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
- bindAssignmentTargetFlow(p.name);
- }
- else if (p.kind === 283 /* SpreadAssignment */) {
- bindAssignmentTargetFlow(p.expression);
+ if (!resolved_1 && features & NodeResolutionFeatures.SelfName) {
+ resolved_1 = loadModuleFromSelfNameReference(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
+ }
+ if (!resolved_1) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
}
+ resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
}
- }
- }
- function bindLogicalExpression(node, trueTarget, falseTarget) {
- var preRightLabel = createBranchLabel();
- if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
- bindCondition(node.left, preRightLabel, falseTarget);
+ if (!resolved_1)
+ return undefined;
+ var resolvedValue = resolved_1.value;
+ if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
+ var path = realPath(resolvedValue.path, host, traceEnabled);
+ var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path;
+ resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
+ }
+ // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
+ return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
}
else {
- bindCondition(node.left, trueTarget, preRightLabel);
+ var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
+ var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
+ // Treat explicit "node_modules" import as an external library import.
+ return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
}
- currentFlow = finishFlowLabel(preRightLabel);
- bind(node.operatorToken);
- bindCondition(node.right, trueTarget, falseTarget);
}
- function bindPrefixUnaryExpressionFlow(node) {
- if (node.operator === 53 /* ExclamationToken */) {
- var saveTrueTarget = currentTrueTarget;
- currentTrueTarget = currentFalseTarget;
- currentFalseTarget = saveTrueTarget;
- bindEachChild(node);
- currentFalseTarget = currentTrueTarget;
- currentTrueTarget = saveTrueTarget;
- }
- else {
- bindEachChild(node);
- if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
- bindAssignmentTargetFlow(node.operand);
- }
- }
+ }
+ function realPath(path, host, traceEnabled) {
+ if (!host.realpath) {
+ return path;
}
- function bindPostfixUnaryExpressionFlow(node) {
- bindEachChild(node);
- if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
- bindAssignmentTargetFlow(node.operand);
- }
+ var real = ts.normalizePath(host.realpath(path));
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
}
- var BindBinaryExpressionFlowState;
- (function (BindBinaryExpressionFlowState) {
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
- })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
- function bindBinaryExpressionFlow(node) {
- var workStacks = {
- expr: [node],
- state: [1 /* MaybeBindLeft */],
- inStrictMode: [undefined],
- parent: [undefined],
- subtreeFlags: [undefined]
- };
- var stackIndex = 0;
- while (stackIndex >= 0) {
- node = workStacks.expr[stackIndex];
- switch (workStacks.state[stackIndex]) {
- case 0 /* BindThenBindChildren */: {
- // This state is used only when recuring, to emulate the work that `bind` does before
- // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
- node.parent = parent;
- var saveInStrictMode = inStrictMode;
- bindWorker(node);
- var saveParent = parent;
- parent = node;
- var subtreeFlagsState = void 0;
- // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
- // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
- if (skipTransformFlagAggregation) {
- // do nothing extra
- }
- else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
- skipTransformFlagAggregation = true;
- subtreeFlagsState = -1;
- }
- else {
- var savedSubtreeTransformFlags = subtreeTransformFlags;
- subtreeTransformFlags = 0;
- subtreeFlagsState = savedSubtreeTransformFlags;
- }
- advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
- break;
- }
- case 1 /* MaybeBindLeft */: {
- var operator = node.operatorToken.kind;
- // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
- // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
- // For now, though, since the common cases are chained `+`, leaving it recursive is fine
- if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
- if (isTopLevelLogicalExpression(node)) {
- var postExpressionLabel = createBranchLabel();
- bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
- currentFlow = finishFlowLabel(postExpressionLabel);
- }
- else {
- bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
- }
- completeNode();
- }
- else {
- advanceState(2 /* BindToken */);
- maybeBind(node.left);
- }
- break;
- }
- case 2 /* BindToken */: {
- advanceState(3 /* BindRight */);
- maybeBind(node.operatorToken);
- break;
- }
- case 3 /* BindRight */: {
- advanceState(4 /* FinishBind */);
- maybeBind(node.right);
- break;
- }
- case 4 /* FinishBind */: {
- var operator = node.operatorToken.kind;
- if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
- bindAssignmentTargetFlow(node.left);
- if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
- var elementAccess = node.left;
- if (isNarrowableOperand(elementAccess.expression)) {
- currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
- }
- }
- }
- completeNode();
- break;
+ ts.Debug.assert(host.fileExists(real), "".concat(path, " linked to nonexistent file ").concat(real));
+ return real;
+ }
+ function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
+ }
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
+ if (!onlyRecordFailures) {
+ var parentOfCandidate = ts.getDirectoryPath(candidate);
+ if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
}
- default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
- }
- }
- /**
- * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
- * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
- */
- function advanceState(state, isInStrictMode, parent, subtreeFlags) {
- workStacks.state[stackIndex] = state;
- if (isInStrictMode !== undefined) {
- workStacks.inStrictMode[stackIndex] = isInStrictMode;
- }
- if (parent !== undefined) {
- workStacks.parent[stackIndex] = parent;
- }
- if (subtreeFlags !== undefined) {
- workStacks.subtreeFlags[stackIndex] = subtreeFlags;
+ onlyRecordFailures = true;
}
}
- function completeNode() {
- if (workStacks.inStrictMode[stackIndex] !== undefined) {
- if (workStacks.subtreeFlags[stackIndex] === -1) {
- skipTransformFlagAggregation = false;
- subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
- }
- else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
- subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
- }
- inStrictMode = workStacks.inStrictMode[stackIndex];
- parent = workStacks.parent[stackIndex];
- }
- stackIndex--;
+ var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
+ if (resolvedFromFile) {
+ var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined;
+ var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
+ return withPackageId(packageInfo, resolvedFromFile);
}
- /**
- * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
- */
- function maybeBind(node) {
- if (node && ts.isBinaryExpression(node)) {
- stackIndex++;
- workStacks.expr[stackIndex] = node;
- workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
- workStacks.inStrictMode[stackIndex] = undefined;
- workStacks.parent[stackIndex] = undefined;
- workStacks.subtreeFlags[stackIndex] = undefined;
- }
- else {
- bind(node);
+ }
+ if (!onlyRecordFailures) {
+ var candidateExists = ts.directoryProbablyExists(candidate, state.host);
+ if (!candidateExists) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
}
+ onlyRecordFailures = true;
}
}
- function bindDeleteExpressionFlow(node) {
- bindEachChild(node);
- if (node.expression.kind === 194 /* PropertyAccessExpression */) {
- bindAssignmentTargetFlow(node.expression);
- }
+ return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
+ }
+ /*@internal*/
+ ts.nodeModulesPathPart = "/node_modules/";
+ /*@internal*/
+ function pathContainsNodeModules(path) {
+ return ts.stringContains(path, ts.nodeModulesPathPart);
+ }
+ ts.pathContainsNodeModules = pathContainsNodeModules;
+ /**
+ * This will be called on the successfully resolved path from `loadModuleFromFile`.
+ * (Not needed for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
+ *
+ * packageDirectory is the directory of the package itself.
+ * For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
+ * For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
+ * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
+ * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
+ */
+ /* @internal */
+ function parseNodeModuleFromPath(resolved) {
+ var path = ts.normalizePath(resolved);
+ var idx = path.lastIndexOf(ts.nodeModulesPathPart);
+ if (idx === -1) {
+ return undefined;
}
- function bindConditionalExpressionFlow(node) {
- var trueLabel = createBranchLabel();
- var falseLabel = createBranchLabel();
- var postExpressionLabel = createBranchLabel();
- bindCondition(node.condition, trueLabel, falseLabel);
- currentFlow = finishFlowLabel(trueLabel);
- bind(node.questionToken);
- bind(node.whenTrue);
- addAntecedent(postExpressionLabel, currentFlow);
- currentFlow = finishFlowLabel(falseLabel);
- bind(node.colonToken);
- bind(node.whenFalse);
- addAntecedent(postExpressionLabel, currentFlow);
- currentFlow = finishFlowLabel(postExpressionLabel);
+ var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
+ var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
+ if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
+ indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
+ }
+ return path.slice(0, indexAfterPackageName);
+ }
+ ts.parseNodeModuleFromPath = parseNodeModuleFromPath;
+ function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
+ var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
+ return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
+ }
+ function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
+ return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
+ }
+ /**
+ * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
+ * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
+ */
+ function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
+ var extension = extensionLess ? candidate.substring(extensionLess.length) : "";
+ return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, extension, onlyRecordFailures, state);
}
- function bindInitializedVariableFlow(node) {
- var name = !ts.isOmittedExpression(node) ? node.name : undefined;
- if (ts.isBindingPattern(name)) {
- for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
- var child = _a[_i];
- bindInitializedVariableFlow(child);
- }
- }
- else {
- currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
+ // esm mode resolutions don't include automatic extension lookup (without additional flags, at least)
+ if (!(state.features & NodeResolutionFeatures.EsmMode)) {
+ // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, "", onlyRecordFailures, state);
+ if (resolvedByAddingExtension) {
+ return resolvedByAddingExtension;
}
}
- function bindVariableDeclarationFlow(node) {
- bindEachChild(node);
- if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
- bindInitializedVariableFlow(node);
+ return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
+ }
+ function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state) {
+ // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
+ // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
+ if (ts.hasJSFileExtension(candidate) || (ts.fileExtensionIs(candidate, ".json" /* Json */) && state.compilerOptions.resolveJsonModule)) {
+ var extensionless = ts.removeFileExtension(candidate);
+ var extension = candidate.substring(extensionless.length);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
}
+ return tryAddingExtensions(extensionless, extensions, extension, onlyRecordFailures, state);
}
- function bindJSDocTypeAlias(node) {
- node.tagName.parent = node;
- if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
- setParentPointers(node, node.fullName);
- }
+ }
+ function loadJSOrExactTSFileName(extensions, candidate, onlyRecordFailures, state) {
+ if ((extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) && ts.fileExtensionIsOneOf(candidate, [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */])) {
+ var result = tryFile(candidate, onlyRecordFailures, state);
+ return result !== undefined ? { path: candidate, ext: ts.forEach([".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */], function (e) { return ts.fileExtensionIs(candidate, e) ? e : undefined; }) } : undefined;
}
- function bindJSDocClassTag(node) {
- bindEachChild(node);
- var host = ts.getHostSignatureFromJSDoc(node);
- if (host && host.kind !== 161 /* MethodDeclaration */) {
- addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
+ return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
+ }
+ /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
+ function tryAddingExtensions(candidate, extensions, originalExtension, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
+ var directory = ts.getDirectoryPath(candidate);
+ if (directory) {
+ onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
}
}
- function bindOptionalExpression(node, trueTarget, falseTarget) {
- doWithConditionalBranches(bind, node, trueTarget, falseTarget);
- if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
- addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
- addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
- }
+ switch (extensions) {
+ case Extensions.DtsOnly:
+ switch (originalExtension) {
+ case ".mjs" /* Mjs */:
+ case ".mts" /* Mts */:
+ case ".d.mts" /* Dmts */:
+ return tryExtension(".d.mts" /* Dmts */);
+ case ".cjs" /* Cjs */:
+ case ".cts" /* Cts */:
+ case ".d.cts" /* Dcts */:
+ return tryExtension(".d.cts" /* Dcts */);
+ case ".json" /* Json */:
+ candidate += ".json" /* Json */;
+ return tryExtension(".d.ts" /* Dts */);
+ default: return tryExtension(".d.ts" /* Dts */);
+ }
+ case Extensions.TypeScript:
+ switch (originalExtension) {
+ case ".mjs" /* Mjs */:
+ case ".mts" /* Mts */:
+ case ".d.mts" /* Dmts */:
+ return tryExtension(".mts" /* Mts */) || tryExtension(".d.mts" /* Dmts */);
+ case ".cjs" /* Cjs */:
+ case ".cts" /* Cts */:
+ case ".d.cts" /* Dcts */:
+ return tryExtension(".cts" /* Cts */) || tryExtension(".d.cts" /* Dcts */);
+ case ".json" /* Json */:
+ candidate += ".json" /* Json */;
+ return tryExtension(".d.ts" /* Dts */);
+ default:
+ return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
+ }
+ case Extensions.JavaScript:
+ switch (originalExtension) {
+ case ".mjs" /* Mjs */:
+ case ".mts" /* Mts */:
+ case ".d.mts" /* Dmts */:
+ return tryExtension(".mjs" /* Mjs */);
+ case ".cjs" /* Cjs */:
+ case ".cts" /* Cts */:
+ case ".d.cts" /* Dcts */:
+ return tryExtension(".cjs" /* Cjs */);
+ case ".json" /* Json */:
+ return tryExtension(".json" /* Json */);
+ default:
+ return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
+ }
+ case Extensions.TSConfig:
+ case Extensions.Json:
+ return tryExtension(".json" /* Json */);
}
- function bindOptionalChainRest(node) {
- switch (node.kind) {
- case 194 /* PropertyAccessExpression */:
- bind(node.questionDotToken);
- bind(node.name);
- break;
- case 195 /* ElementAccessExpression */:
- bind(node.questionDotToken);
- bind(node.argumentExpression);
- break;
- case 196 /* CallExpression */:
- bind(node.questionDotToken);
- bindEach(node.typeArguments);
- bindEach(node.arguments);
- break;
- }
+ function tryExtension(ext) {
+ var path = tryFile(candidate + ext, onlyRecordFailures, state);
+ return path === undefined ? undefined : { path: path, ext: ext };
}
- function bindOptionalChain(node, trueTarget, falseTarget) {
- // For an optional chain, we emulate the behavior of a logical expression:
- //
- // a?.b -> a && a.b
- // a?.b.c -> a && a.b.c
- // a?.b?.c -> a && a.b && a.b.c
- // a?.[x = 1] -> a && a[x = 1]
- //
- // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
- // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
- // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
- // chain node. We then treat the entire node as the right side of the expression.
- var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
- bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
- if (preChainLabel) {
- currentFlow = finishFlowLabel(preChainLabel);
+ }
+ /** Return the file if it exists. */
+ function tryFile(fileName, onlyRecordFailures, state) {
+ if (!onlyRecordFailures) {
+ if (state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
}
- doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
- if (ts.isOutermostOptionalChain(node)) {
- addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
- addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
}
}
- function bindOptionalChainFlow(node) {
- if (isTopLevelLogicalExpression(node)) {
- var postExpressionLabel = createBranchLabel();
- bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
- currentFlow = finishFlowLabel(postExpressionLabel);
- }
- else {
- bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
+ state.failedLookupLocations.push(fileName);
+ return undefined;
+ }
+ function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
+ if (considerPackageJson === void 0) { considerPackageJson = true; }
+ var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
+ var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
+ var versionPaths = packageInfo && packageInfo.versionPaths;
+ return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
+ }
+ /**
+ * A function for locating the package.json scope for a given path
+ */
+ /*@internal*/
+ function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) {
+ var state = {
+ host: host,
+ compilerOptions: options,
+ traceEnabled: isTraceEnabled(options, host),
+ failedLookupLocations: [],
+ packageJsonInfoCache: packageJsonInfoCache,
+ features: 0,
+ conditions: [],
+ };
+ var parts = ts.getPathComponents(fileName);
+ parts.pop();
+ while (parts.length > 0) {
+ var pkg = getPackageJsonInfo(ts.getPathFromPathComponents(parts), /*onlyRecordFailures*/ false, state);
+ if (pkg) {
+ return pkg;
}
+ parts.pop();
}
- function bindNonNullExpressionFlow(node) {
- if (ts.isOptionalChain(node)) {
- bindOptionalChainFlow(node);
+ return undefined;
+ }
+ ts.getPackageScopeForPath = getPackageScopeForPath;
+ /*@internal*/
+ function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
+ var _a, _b, _c;
+ var host = state.host, traceEnabled = state.traceEnabled;
+ var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
+ if (onlyRecordFailures) {
+ state.failedLookupLocations.push(packageJsonPath);
+ return undefined;
+ }
+ var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath);
+ if (existing !== undefined) {
+ if (typeof existing !== "boolean") {
+ if (traceEnabled)
+ trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
+ return existing;
}
else {
- bindEachChild(node);
+ if (existing && traceEnabled)
+ trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath);
+ state.failedLookupLocations.push(packageJsonPath);
+ return undefined;
}
}
- function bindAccessExpressionFlow(node) {
- if (ts.isOptionalChain(node)) {
- bindOptionalChainFlow(node);
+ var directoryExists = ts.directoryProbablyExists(packageDirectory, host);
+ if (directoryExists && host.fileExists(packageJsonPath)) {
+ var packageJsonContent = ts.readJson(packageJsonPath, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
- else {
- bindEachChild(node);
+ var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
+ var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
+ (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
+ return result;
+ }
+ else {
+ if (directoryExists && traceEnabled) {
+ trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
}
+ (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists);
+ // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
+ state.failedLookupLocations.push(packageJsonPath);
}
- function bindCallExpressionFlow(node) {
- if (ts.isOptionalChain(node)) {
- bindOptionalChainFlow(node);
+ }
+ ts.getPackageJsonInfo = getPackageJsonInfo;
+ function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
+ var packageFile;
+ if (jsonContent) {
+ switch (extensions) {
+ case Extensions.JavaScript:
+ case Extensions.Json:
+ packageFile = readPackageJsonMainField(jsonContent, candidate, state);
+ break;
+ case Extensions.TypeScript:
+ // When resolving typescript modules, try resolving using main field as well
+ packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
+ break;
+ case Extensions.DtsOnly:
+ packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
+ break;
+ case Extensions.TSConfig:
+ packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
+ break;
+ default:
+ return ts.Debug.assertNever(extensions);
}
- else {
- // If the target of the call expression is a function expression or arrow function we have
- // an immediately invoked function expression (IIFE). Initialize the flowNode property to
- // the current control flow (which includes evaluation of the IIFE arguments).
- var expr = ts.skipParentheses(node.expression);
- if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
- bindEach(node.typeArguments);
- bindEach(node.arguments);
- bind(node.expression);
+ }
+ var loader = function (extensions, candidate, onlyRecordFailures, state) {
+ var fromFile = tryFile(candidate, onlyRecordFailures, state);
+ if (fromFile) {
+ var resolved = resolvedIfExtensionMatches(extensions, fromFile);
+ if (resolved) {
+ return noPackageId(resolved);
}
- else {
- bindEachChild(node);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
}
}
- if (node.expression.kind === 194 /* PropertyAccessExpression */) {
- var propertyAccess = node.expression;
- if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
- currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
- }
+ // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
+ var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
+ // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
+ return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
+ };
+ var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
+ var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
+ var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
+ if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
+ var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName);
}
- }
- function getContainerFlags(node) {
- switch (node.kind) {
- case 214 /* ClassExpression */:
- case 245 /* ClassDeclaration */:
- case 248 /* EnumDeclaration */:
- case 193 /* ObjectLiteralExpression */:
- case 173 /* TypeLiteral */:
- case 304 /* JSDocTypeLiteral */:
- case 274 /* JsxAttributes */:
- return 1 /* IsContainer */;
- case 246 /* InterfaceDeclaration */:
- return 1 /* IsContainer */ | 64 /* IsInterface */;
- case 249 /* ModuleDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- case 186 /* MappedType */:
- return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 290 /* SourceFile */:
- return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
- case 161 /* MethodDeclaration */:
- if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
- return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
- }
- // falls through
- case 162 /* Constructor */:
- case 244 /* FunctionDeclaration */:
- case 160 /* MethodSignature */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 165 /* CallSignature */:
- case 305 /* JSDocSignature */:
- case 300 /* JSDocFunctionType */:
- case 170 /* FunctionType */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- case 171 /* ConstructorType */:
- return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
- case 250 /* ModuleBlock */:
- return 4 /* IsControlFlowContainer */;
- case 159 /* PropertyDeclaration */:
- return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
- case 280 /* CatchClause */:
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- case 232 /* ForOfStatement */:
- case 251 /* CaseBlock */:
- return 2 /* IsBlockScopedContainer */;
- case 223 /* Block */:
- // do not treat blocks directly inside a function as a block-scoped-container.
- // Locals that reside in this block should go to the function locals. Otherwise 'x'
- // would not appear to be a redeclaration of a block scoped local in the following
- // example:
- //
- // function foo() {
- // var x;
- // let x;
- // }
- //
- // If we placed 'var x' into the function locals and 'let x' into the locals of
- // the block, then there would be no collision.
- //
- // By not creating a new block-scoped-container here, we ensure that both 'var x'
- // and 'let x' go into the Function-container's locals, and we do get a collision
- // conflict.
- return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
+ var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, /*pathPatterns*/ undefined, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
+ if (result) {
+ return removeIgnoredPackageId(result.value);
}
- return 0 /* None */;
}
- function addToContainerChain(next) {
- if (lastContainer) {
- lastContainer.nextContainer = next;
- }
- lastContainer = next;
+ // It won't have a `packageId` set, because we disabled `considerPackageJson`.
+ var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
+ if (packageFileResult)
+ return packageFileResult;
+ // esm mode resolutions don't do package `index` lookups
+ if (!(state.features & NodeResolutionFeatures.EsmMode)) {
+ return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
}
- function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
- switch (container.kind) {
- // Modules, source files, and classes need specialized handling for how their
- // members are declared (for example, a member of a class will go into a specific
- // symbol table depending on if it is static or not). We defer to specialized
- // handlers to take care of declaring these child members.
- case 249 /* ModuleDeclaration */:
- return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 290 /* SourceFile */:
- return declareSourceFileMember(node, symbolFlags, symbolExcludes);
- case 214 /* ClassExpression */:
- case 245 /* ClassDeclaration */:
- return declareClassMember(node, symbolFlags, symbolExcludes);
- case 248 /* EnumDeclaration */:
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- case 173 /* TypeLiteral */:
- case 304 /* JSDocTypeLiteral */:
- case 193 /* ObjectLiteralExpression */:
- case 246 /* InterfaceDeclaration */:
- case 274 /* JsxAttributes */:
- // Interface/Object-types always have their children added to the 'members' of
- // their container. They are only accessible through an instance of their
- // container, and are never in scope otherwise (even inside the body of the
- // object / type / interface declaring them). An exception is type parameters,
- // which are in scope without qualification (similar to 'locals').
- return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- case 170 /* FunctionType */:
- case 171 /* ConstructorType */:
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 305 /* JSDocSignature */:
- case 167 /* IndexSignature */:
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- case 300 /* JSDocFunctionType */:
- case 322 /* JSDocTypedefTag */:
- case 315 /* JSDocCallbackTag */:
- case 247 /* TypeAliasDeclaration */:
- case 186 /* MappedType */:
- // All the children of these container types are never visible through another
- // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
- // they're only accessed 'lexically' (i.e. from code that exists underneath
- // their container in the tree). To accomplish this, we simply add their declared
- // symbol to the 'locals' of the container. These symbols can then be found as
- // the type checker walks up the containers, checking them for matching names.
- return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
- }
+ }
+ /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
+ function resolvedIfExtensionMatches(extensions, path) {
+ var ext = ts.tryGetExtensionFromPath(path);
+ return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
+ }
+ /** True if `extension` is one of the supported `extensions`. */
+ function extensionIsOk(extensions, extension) {
+ switch (extensions) {
+ case Extensions.JavaScript:
+ return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
+ case Extensions.TSConfig:
+ case Extensions.Json:
+ return extension === ".json" /* Json */;
+ case Extensions.TypeScript:
+ return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
+ case Extensions.DtsOnly:
+ return extension === ".d.ts" /* Dts */;
}
- function declareClassMember(node, symbolFlags, symbolExcludes) {
- return ts.hasModifier(node, 32 /* Static */)
- ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
- : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ }
+ /* @internal */
+ function parsePackageName(moduleName) {
+ var idx = moduleName.indexOf(ts.directorySeparator);
+ if (moduleName[0] === "@") {
+ idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
}
- function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
- return ts.isExternalModule(file)
- ? declareModuleMember(node, symbolFlags, symbolExcludes)
- : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
+ return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
+ }
+ ts.parsePackageName = parsePackageName;
+ /* @internal */
+ function allKeysStartWithDot(obj) {
+ return ts.every(ts.getOwnKeys(obj), function (k) { return ts.startsWith(k, "."); });
+ }
+ ts.allKeysStartWithDot = allKeysStartWithDot;
+ function noKeyStartsWithDot(obj) {
+ return !ts.some(ts.getOwnKeys(obj), function (k) { return ts.startsWith(k, "."); });
+ }
+ function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
+ var _a, _b;
+ var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
+ var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
+ var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions);
+ if (!scope || !scope.packageJsonContent.exports) {
+ return undefined;
}
- function hasExportDeclarations(node) {
- var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
- return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
+ if (typeof scope.packageJsonContent.name !== "string") {
+ return undefined;
}
- function setExportContextFlag(node) {
- // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
- // declarations with export modifiers) is an export context in which declarations are implicitly exported.
- if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
- node.flags |= 64 /* ExportContext */;
+ var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
+ var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
+ if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
+ return undefined;
+ }
+ var trailingParts = parts.slice(nameParts.length);
+ return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
+ }
+ function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
+ if (!scope.packageJsonContent.exports) {
+ return undefined;
+ }
+ if (subpath === ".") {
+ var mainExport = void 0;
+ if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
+ mainExport = scope.packageJsonContent.exports;
}
- else {
- node.flags &= ~64 /* ExportContext */;
+ else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
+ mainExport = scope.packageJsonContent.exports["."];
+ }
+ if (mainExport) {
+ var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
+ return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
}
}
- function bindModuleDeclaration(node) {
- setExportContextFlag(node);
- if (ts.isAmbientModule(node)) {
- if (ts.hasModifier(node, 1 /* Export */)) {
- errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
- }
- if (ts.isModuleAugmentationExternal(node)) {
- declareModuleSymbol(node);
- }
- else {
- var pattern = void 0;
- if (node.name.kind === 10 /* StringLiteral */) {
- var text = node.name.text;
- if (ts.hasZeroOrOneAsteriskCharacter(text)) {
- pattern = ts.tryParsePattern(text);
- }
- else {
- errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
- }
- }
- var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
- file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
+ else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
+ if (typeof scope.packageJsonContent.exports !== "object") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
+ return toSearchResult(/*value*/ undefined);
}
- else {
- var state = declareModuleSymbol(node);
- if (state !== 0 /* NonInstantiated */) {
- var symbol = node.symbol;
- // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
- symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
- // Current must be `const enum` only
- && state === 2 /* ConstEnumOnly */
- // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
- && symbol.constEnumOnlyModule !== false;
- }
+ var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
+ if (result) {
+ return result;
}
}
- function declareModuleSymbol(node) {
- var state = getModuleInstanceState(node);
- var instantiated = state !== 0 /* NonInstantiated */;
- declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
- return state;
- }
- function bindFunctionOrConstructorType(node) {
- // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
- // to the one we would get for: { <...>(...): T }
- //
- // We do that by making an anonymous type literal symbol, and then setting the function
- // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
- // from an actual type literal symbol you would have gotten had you used the long form.
- var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
- addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
- var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
- addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
- typeLiteralSymbol.members = ts.createSymbolTable();
- typeLiteralSymbol.members.set(symbol.escapedName, symbol);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
- function bindObjectLiteralExpression(node) {
- var ElementKind;
- (function (ElementKind) {
- ElementKind[ElementKind["Property"] = 1] = "Property";
- ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
- })(ElementKind || (ElementKind = {}));
- if (inStrictMode && !ts.isAssignmentTarget(node)) {
- var seen = ts.createUnderscoreEscapedMap();
- for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
- var prop = _a[_i];
- if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
- continue;
- }
- var identifier = prop.name;
- // ECMA-262 11.1.5 Object Initializer
- // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
- // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
- // IsDataDescriptor(propId.descriptor) is true.
- // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
- // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
- // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
- // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
- var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
- ? 1 /* Property */
- : 2 /* Accessor */;
- var existingKind = seen.get(identifier.escapedText);
- if (!existingKind) {
- seen.set(identifier.escapedText, currentKind);
- continue;
- }
- if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
- var span = ts.getErrorSpanForNode(file, identifier);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
- }
- }
+ return toSearchResult(/*value*/ undefined);
+ }
+ function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) {
+ var _a, _b;
+ if (moduleName === "#" || ts.startsWith(moduleName, "#/")) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName);
}
- return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
- }
- function bindJsxAttributes(node) {
- return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
- }
- function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
- return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ return toSearchResult(/*value*/ undefined);
}
- function bindAnonymousDeclaration(node, symbolFlags, name) {
- var symbol = createSymbol(symbolFlags, name);
- if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
- symbol.parent = container.symbol;
+ var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
+ var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
+ var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions);
+ if (!scope) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath);
}
- addDeclarationToSymbol(symbol, node, symbolFlags);
- return symbol;
+ return toSearchResult(/*value*/ undefined);
}
- function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
- switch (blockScopeContainer.kind) {
- case 249 /* ModuleDeclaration */:
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- case 290 /* SourceFile */:
- if (ts.isExternalOrCommonJsModule(container)) {
- declareModuleMember(node, symbolFlags, symbolExcludes);
- break;
- }
- // falls through
- default:
- if (!blockScopeContainer.locals) {
- blockScopeContainer.locals = ts.createSymbolTable();
- addToContainerChain(blockScopeContainer);
- }
- declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
+ if (!scope.packageJsonContent.imports) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
+ return toSearchResult(/*value*/ undefined);
}
- function delayedBindJSDocTypedefTag() {
- if (!delayedTypeAliases) {
- return;
- }
- var saveContainer = container;
- var saveLastContainer = lastContainer;
- var saveBlockScopeContainer = blockScopeContainer;
- var saveParent = parent;
- var saveCurrentFlow = currentFlow;
- for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
- var typeAlias = delayedTypeAliases_1[_i];
- var host = ts.getJSDocHost(typeAlias);
- container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
- blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
- currentFlow = initFlowNode({ flags: 2 /* Start */ });
- parent = typeAlias;
- bind(typeAlias.typeExpression);
- var declName = ts.getNameOfDeclaration(typeAlias);
- if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
- // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
- var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
- if (isTopLevel) {
- bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
- var oldContainer = container;
- switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
- case 1 /* ExportsProperty */:
- case 2 /* ModuleExports */:
- if (!ts.isExternalOrCommonJsModule(file)) {
- container = undefined;
- }
- else {
- container = file;
- }
- break;
- case 4 /* ThisProperty */:
- container = declName.parent.expression;
- break;
- case 3 /* PrototypeProperty */:
- container = declName.parent.expression.name;
- break;
- case 5 /* Property */:
- container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
- : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
- : declName.parent.expression;
- break;
- case 0 /* None */:
- return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
- }
- if (container) {
- declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
- }
- container = oldContainer;
+ var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
+ if (result) {
+ return result;
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1, moduleName, scope.packageDirectory);
+ }
+ return toSearchResult(/*value*/ undefined);
+ }
+ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) {
+ var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);
+ if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) {
+ var target = lookupTable[moduleName];
+ return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false);
+ }
+ var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; });
+ for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) {
+ var potentialTarget = expandingKeys_1[_i];
+ if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) {
+ var target = lookupTable[potentialTarget];
+ var starPos = potentialTarget.indexOf("*");
+ var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos));
+ return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true);
+ }
+ else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) {
+ var target = lookupTable[potentialTarget];
+ var subpath = moduleName.substring(potentialTarget.length - 1);
+ return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true);
+ }
+ else if (ts.startsWith(moduleName, potentialTarget)) {
+ var target = lookupTable[potentialTarget];
+ var subpath = moduleName.substring(potentialTarget.length);
+ return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false);
+ }
+ }
+ function matchesPatternWithTrailer(target, name) {
+ if (ts.endsWith(target, "*"))
+ return false; // handled by next case in loop
+ var starPos = target.indexOf("*");
+ if (starPos === -1)
+ return false; // handled by last case in loop
+ return ts.startsWith(name, target.substring(0, starPos)) && ts.endsWith(name, target.substring(starPos + 1));
+ }
+ }
+ /**
+ * Gets the self-recursive function specialized to retrieving the targeted import/export element for the given resolution configuration
+ */
+ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) {
+ return loadModuleFromTargetImportOrExport;
+ function loadModuleFromTargetImportOrExport(target, subpath, pattern) {
+ var _a, _b;
+ if (typeof target === "string") {
+ if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
}
+ return toSearchResult(/*value*/ undefined);
}
- else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
- parent = typeAlias.parent;
- bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
+ if (!ts.startsWith(target, "./")) {
+ if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) {
+ var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath;
+ var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference);
+ return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined);
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
+ }
+ return toSearchResult(/*value*/ undefined);
+ }
+ var parts = ts.pathIsRelative(target) ? ts.getPathComponents(target).slice(1) : ts.getPathComponents(target);
+ var partsAfterFirst = parts.slice(1);
+ if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
+ }
+ return toSearchResult(/*value*/ undefined);
+ }
+ var resolvedTarget = ts.combinePaths(scope.packageDirectory, target);
+ // TODO: Assert that `resolvedTarget` is actually within the package directory? That's what the spec says.... but I'm not sure we need
+ // to be in the business of validating everyone's import and export map correctness.
+ var subpathParts = ts.getPathComponents(subpath);
+ if (subpathParts.indexOf("..") >= 0 || subpathParts.indexOf(".") >= 0 || subpathParts.indexOf("node_modules") >= 0) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
+ }
+ return toSearchResult(/*value*/ undefined);
+ }
+ var finalPath = ts.getNormalizedAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath, (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
+ return toSearchResult(withPackageId(scope, loadJSOrExactTSFileName(extensions, finalPath, /*onlyRecordFailures*/ false, state)));
+ }
+ else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null
+ if (!Array.isArray(target)) {
+ for (var _i = 0, _c = ts.getOwnKeys(target); _i < _c.length; _i++) {
+ var key = _c[_i];
+ if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) {
+ var subTarget = target[key];
+ var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern);
+ if (result) {
+ return result;
+ }
+ }
+ }
+ return undefined;
}
else {
- bind(typeAlias.fullName);
+ if (!ts.length(target)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
+ }
+ return toSearchResult(/*value*/ undefined);
+ }
+ for (var _d = 0, target_1 = target; _d < target_1.length; _d++) {
+ var elem = target_1[_d];
+ var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern);
+ if (result) {
+ return result;
+ }
+ }
}
}
- container = saveContainer;
- lastContainer = saveLastContainer;
- blockScopeContainer = saveBlockScopeContainer;
- parent = saveParent;
- currentFlow = saveCurrentFlow;
+ else if (target === null) { // eslint-disable-line no-null/no-null
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_explicitly_maps_specifier_1_to_null, scope.packageDirectory, moduleName);
+ }
+ return toSearchResult(/*value*/ undefined);
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
+ }
+ return toSearchResult(/*value*/ undefined);
}
- // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
- // check for reserved words used as identifiers in strict mode code.
- function checkStrictModeIdentifier(node) {
- if (inStrictMode &&
- node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
- node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
- !ts.isIdentifierName(node) &&
- !(node.flags & 8388608 /* Ambient */) &&
- !(node.flags & 4194304 /* JSDoc */)) {
- // Report error only if there are no parse errors in file
- if (!file.parseDiagnostics.length) {
- file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
+ }
+ /* @internal */
+ function isApplicableVersionedTypesKey(conditions, key) {
+ if (conditions.indexOf("types") === -1)
+ return false; // only apply versioned types conditions if the types condition is applied
+ if (!ts.startsWith(key, "types@"))
+ return false;
+ var range = ts.VersionRange.tryParse(key.substring("types@".length));
+ if (!range)
+ return false;
+ return range.test(ts.version);
+ }
+ ts.isApplicableVersionedTypesKey = isApplicableVersionedTypesKey;
+ function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
+ return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
+ }
+ function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
+ // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
+ return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
+ }
+ function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
+ var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, state.features === 0 ? undefined : state.features & NodeResolutionFeatures.EsmMode ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS, redirectedReference);
+ return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
+ if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
+ var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
+ if (resolutionFromCache) {
+ return resolutionFromCache;
}
+ return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference));
}
+ });
+ }
+ function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
+ if (!nodeModulesFolderExists && state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
}
- function getStrictModeIdentifierMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
+ var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state, cache, redirectedReference);
+ if (packageResult) {
+ return packageResult;
+ }
+ if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
+ var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
+ var nodeModulesAtTypesExists = nodeModulesFolderExists;
+ if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
+ }
+ nodeModulesAtTypesExists = false;
}
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
+ return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state, cache, redirectedReference);
+ }
+ }
+ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) {
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
+ // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
+ var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
+ // But only if we're not respecting export maps (if we are, we might redirect around this location)
+ if (!(state.features & NodeResolutionFeatures.Exports)) {
+ if (packageInfo) {
+ var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
+ if (fromFile) {
+ return noPackageId(fromFile);
+ }
+ var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
+ return withPackageId(packageInfo, fromDirectory);
}
- return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
}
- // The binder visits every node, so this is a good place to check for
- // the reserved private name (there is only one)
- function checkPrivateIdentifier(node) {
- if (node.escapedText === "#constructor") {
- // Report error only if there are no parse errors in file
- if (!file.parseDiagnostics.length) {
- file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
+ var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
+ var loader = function (extensions, candidate, onlyRecordFailures, state) {
+ var _a;
+ // package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
+ if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
+ return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
+ }
+ var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
+ loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
+ return withPackageId(packageInfo, pathAndExtension);
+ };
+ if (rest !== "") { // If "rest" is empty, we just did this search above.
+ var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
+ // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
+ packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
+ if (packageInfo && packageInfo.versionPaths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
+ }
+ var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
+ var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
+ if (fromPaths) {
+ return fromPaths.value;
}
}
}
- function checkStrictModeBinaryExpression(node) {
- if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
- // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
- // Assignment operator(11.13) or of a PostfixExpression(11.3)
- checkStrictModeEvalOrArguments(node, node.left);
+ return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
+ }
+ function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, onlyRecordFailures, state) {
+ pathPatterns || (pathPatterns = ts.tryParsePatterns(paths));
+ var matchedPattern = ts.matchPatternOrExact(pathPatterns, moduleName);
+ if (matchedPattern) {
+ var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
+ var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
}
+ var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
+ var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
+ // When baseUrl is not specified, the command line parser resolves relative paths to the config file location.
+ var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ // A path mapping may have an extension, in contrast to an import, which should omit it.
+ var extension = ts.tryGetExtensionFromPath(subst);
+ if (extension !== undefined) {
+ var path_1 = tryFile(candidate, onlyRecordFailures, state);
+ if (path_1 !== undefined) {
+ return noPackageId({ path: path_1, ext: extension });
+ }
+ }
+ return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ });
+ return { value: resolved };
}
- function checkStrictModeCatchClause(node) {
- // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
- // Catch production is eval or arguments
- if (inStrictMode && node.variableDeclaration) {
- checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
+ }
+ /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
+ var mangledScopedPackageSeparator = "__";
+ /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
+ function mangleScopedPackageNameWithTrace(packageName, state) {
+ var mangled = mangleScopedPackageName(packageName);
+ if (state.traceEnabled && mangled !== packageName) {
+ trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
+ }
+ return mangled;
+ }
+ /* @internal */
+ function getTypesPackageName(packageName) {
+ return "@types/".concat(mangleScopedPackageName(packageName));
+ }
+ ts.getTypesPackageName = getTypesPackageName;
+ /* @internal */
+ function mangleScopedPackageName(packageName) {
+ if (ts.startsWith(packageName, "@")) {
+ var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
+ if (replaceSlash !== packageName) {
+ return replaceSlash.slice(1); // Take off the "@"
}
}
- function checkStrictModeDeleteExpression(node) {
- // Grammar checking
- if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
- // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
- // UnaryExpression is a direct reference to a variable, function argument, or function name
- var span = ts.getErrorSpanForNode(file, node.expression);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
+ return packageName;
+ }
+ ts.mangleScopedPackageName = mangleScopedPackageName;
+ /* @internal */
+ function getPackageNameFromTypesPackageName(mangledName) {
+ var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
+ if (withoutAtTypePrefix !== mangledName) {
+ return unmangleScopedPackageName(withoutAtTypePrefix);
+ }
+ return mangledName;
+ }
+ ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
+ /* @internal */
+ function unmangleScopedPackageName(typesPackageName) {
+ return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
+ "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
+ typesPackageName;
+ }
+ ts.unmangleScopedPackageName = unmangleScopedPackageName;
+ function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
+ var result = cache && cache.get(containingDirectory);
+ if (result) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
+ state.resultFromCache = result;
+ return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
- function isEvalOrArgumentsIdentifier(node) {
- return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
+ }
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [] };
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
+ // No originalPath because classic resolution doesn't resolve realPath
+ return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
+ function tryResolve(extensions) {
+ var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
+ if (resolvedUsingSettings) {
+ return { value: resolvedUsingSettings };
+ }
+ if (!ts.isExternalModuleNameRelative(moduleName)) {
+ var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, /*mode*/ undefined, redirectedReference);
+ // Climb up parent directories looking for a module.
+ var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
+ var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
+ if (resolutionFromCache) {
+ return resolutionFromCache;
+ }
+ var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
+ return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
+ });
+ if (resolved_3) {
+ return resolved_3;
+ }
+ if (extensions === Extensions.TypeScript) {
+ // If we didn't find the file normally, look it up in @types.
+ return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
+ }
+ }
+ else {
+ var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
+ return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
+ }
}
- function checkStrictModeEvalOrArguments(contextNode, name) {
- if (name && name.kind === 75 /* Identifier */) {
- var identifier = name;
- if (isEvalOrArgumentsIdentifier(identifier)) {
- // We check first if the name is inside class declaration or class expression; if so give explicit message
- // otherwise report generic error message.
- var span = ts.getErrorSpanForNode(file, name);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
+ }
+ ts.classicNameResolver = classicNameResolver;
+ /**
+ * A host may load a module from a global cache of typings.
+ * This is the minumum code needed to expose that functionality; the rest is in the host.
+ */
+ /* @internal */
+ function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) {
+ var traceEnabled = isTraceEnabled(compilerOptions, host);
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
+ }
+ var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [] };
+ var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined);
+ return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
+ }
+ ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
+ /**
+ * Wraps value to SearchResult.
+ * @returns undefined if value is undefined or { value } otherwise
+ */
+ function toSearchResult(value) {
+ return value !== undefined ? { value: value } : undefined;
+ }
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var ModuleInstanceState;
+ (function (ModuleInstanceState) {
+ ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
+ ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
+ ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
+ })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
+ function getModuleInstanceState(node, visited) {
+ if (node.body && !node.body.parent) {
+ // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
+ ts.setParent(node.body, node);
+ ts.setParentRecursive(node.body, /*incremental*/ false);
+ }
+ return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
+ }
+ ts.getModuleInstanceState = getModuleInstanceState;
+ function getModuleInstanceStateCached(node, visited) {
+ if (visited === void 0) { visited = new ts.Map(); }
+ var nodeId = ts.getNodeId(node);
+ if (visited.has(nodeId)) {
+ return visited.get(nodeId) || 0 /* NonInstantiated */;
+ }
+ visited.set(nodeId, undefined);
+ var result = getModuleInstanceStateWorker(node, visited);
+ visited.set(nodeId, result);
+ return result;
+ }
+ function getModuleInstanceStateWorker(node, visited) {
+ // A module is uninstantiated if it contains only
+ switch (node.kind) {
+ // 1. interface declarations, type alias declarations
+ case 257 /* InterfaceDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ return 0 /* NonInstantiated */;
+ // 2. const enum declarations
+ case 259 /* EnumDeclaration */:
+ if (ts.isEnumConst(node)) {
+ return 2 /* ConstEnumOnly */;
+ }
+ break;
+ // 3. non-exported import declarations
+ case 265 /* ImportDeclaration */:
+ case 264 /* ImportEqualsDeclaration */:
+ if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) {
+ return 0 /* NonInstantiated */;
+ }
+ break;
+ // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
+ case 271 /* ExportDeclaration */:
+ var exportDeclaration = node;
+ if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 272 /* NamedExports */) {
+ var state = 0 /* NonInstantiated */;
+ for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
+ var specifier = _a[_i];
+ var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
+ if (specifierState > state) {
+ state = specifierState;
+ }
+ if (state === 1 /* Instantiated */) {
+ return state;
+ }
+ }
+ return state;
+ }
+ break;
+ // 5. other uninstantiated module declarations.
+ case 261 /* ModuleBlock */: {
+ var state_1 = 0 /* NonInstantiated */;
+ ts.forEachChild(node, function (n) {
+ var childState = getModuleInstanceStateCached(n, visited);
+ switch (childState) {
+ case 0 /* NonInstantiated */:
+ // child is non-instantiated - continue searching
+ return;
+ case 2 /* ConstEnumOnly */:
+ // child is const enum only - record state and continue searching
+ state_1 = 2 /* ConstEnumOnly */;
+ return;
+ case 1 /* Instantiated */:
+ // child is instantiated - record state and stop
+ state_1 = 1 /* Instantiated */;
+ return true;
+ default:
+ ts.Debug.assertNever(childState);
+ }
+ });
+ return state_1;
+ }
+ case 260 /* ModuleDeclaration */:
+ return getModuleInstanceState(node, visited);
+ case 79 /* Identifier */:
+ // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
+ // be considered the same as type alias
+ if (node.isInJSDocNamespace) {
+ return 0 /* NonInstantiated */;
+ }
+ }
+ return 1 /* Instantiated */;
+ }
+ function getModuleInstanceStateForAliasTarget(specifier, visited) {
+ var name = specifier.propertyName || specifier.name;
+ var p = specifier.parent;
+ while (p) {
+ if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
+ var statements = p.statements;
+ var found = void 0;
+ for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
+ var statement = statements_2[_i];
+ if (ts.nodeHasName(statement, name)) {
+ if (!statement.parent) {
+ ts.setParent(statement, p);
+ ts.setParentRecursive(statement, /*incremental*/ false);
+ }
+ var state = getModuleInstanceStateCached(statement, visited);
+ if (found === undefined || state > found) {
+ found = state;
+ }
+ if (found === 1 /* Instantiated */) {
+ return found;
+ }
+ }
+ }
+ if (found !== undefined) {
+ return found;
}
}
+ p = p.parent;
+ }
+ return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
+ }
+ var ContainerFlags;
+ (function (ContainerFlags) {
+ // The current node is not a container, and no container manipulation should happen before
+ // recursing into it.
+ ContainerFlags[ContainerFlags["None"] = 0] = "None";
+ // The current node is a container. It should be set as the current container (and block-
+ // container) before recursing into it. The current node does not have locals. Examples:
+ //
+ // Classes, ObjectLiterals, TypeLiterals, Interfaces...
+ ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
+ // The current node is a block-scoped-container. It should be set as the current block-
+ // container before recursing into it. Examples:
+ //
+ // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
+ ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
+ // The current node is the container of a control flow path. The current control flow should
+ // be saved and restored, and a new control flow initialized within the container.
+ ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
+ ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
+ ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
+ ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
+ ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
+ ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethodOrAccessor"] = 128] = "IsObjectLiteralOrClassExpressionMethodOrAccessor";
+ })(ContainerFlags || (ContainerFlags = {}));
+ function initFlowNode(node) {
+ ts.Debug.attachFlowNodeDebugInfo(node);
+ return node;
+ }
+ var binder = createBinder();
+ function bindSourceFile(file, options) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
+ ts.performance.mark("beforeBind");
+ ts.perfLogger.logStartBindFile("" + file.fileName);
+ binder(file, options);
+ ts.perfLogger.logStopBindFile();
+ ts.performance.mark("afterBind");
+ ts.performance.measure("Bind", "beforeBind", "afterBind");
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
+ }
+ ts.bindSourceFile = bindSourceFile;
+ function createBinder() {
+ var file;
+ var options;
+ var languageVersion;
+ var parent;
+ var container;
+ var thisParentContainer; // Container one level up
+ var blockScopeContainer;
+ var lastContainer;
+ var delayedTypeAliases;
+ var seenThisKeyword;
+ // state used by control flow analysis
+ var currentFlow;
+ var currentBreakTarget;
+ var currentContinueTarget;
+ var currentReturnTarget;
+ var currentTrueTarget;
+ var currentFalseTarget;
+ var currentExceptionTarget;
+ var preSwitchCaseFlow;
+ var activeLabelList;
+ var hasExplicitReturn;
+ // state used for emit helpers
+ var emitFlags;
+ // If this file is an external module, then it is automatically in strict-mode according to
+ // ES6. If it is not an external module, then we'll determine if it is in strict mode or
+ // not depending on if we see "use strict" in certain places or if we hit a class/namespace
+ // or if compiler options contain alwaysStrict.
+ var inStrictMode;
+ // If we are binding an assignment pattern, we will bind certain expressions differently.
+ var inAssignmentPattern = false;
+ var symbolCount = 0;
+ var Symbol;
+ var classifiableNames;
+ var unreachableFlow = { flags: 1 /* Unreachable */ };
+ var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
+ var bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
+ /**
+ * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
+ * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
+ * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
+ */
+ function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
+ return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
+ }
+ function bindSourceFile(f, opts) {
+ file = f;
+ options = opts;
+ languageVersion = ts.getEmitScriptTarget(options);
+ inStrictMode = bindInStrictMode(file, opts);
+ classifiableNames = new ts.Set();
+ symbolCount = 0;
+ Symbol = ts.objectAllocator.getSymbolConstructor();
+ // Attach debugging information if necessary
+ ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
+ ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
+ if (!file.locals) {
+ bind(file);
+ file.symbolCount = symbolCount;
+ file.classifiableNames = classifiableNames;
+ delayedBindJSDocTypedefTag();
+ }
+ file = undefined;
+ options = undefined;
+ languageVersion = undefined;
+ parent = undefined;
+ container = undefined;
+ thisParentContainer = undefined;
+ blockScopeContainer = undefined;
+ lastContainer = undefined;
+ delayedTypeAliases = undefined;
+ seenThisKeyword = false;
+ currentFlow = undefined;
+ currentBreakTarget = undefined;
+ currentContinueTarget = undefined;
+ currentReturnTarget = undefined;
+ currentTrueTarget = undefined;
+ currentFalseTarget = undefined;
+ currentExceptionTarget = undefined;
+ activeLabelList = undefined;
+ hasExplicitReturn = false;
+ inAssignmentPattern = false;
+ emitFlags = 0 /* None */;
}
- function getStrictModeEvalOrArgumentsMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
+ return bindSourceFile;
+ function bindInStrictMode(file, opts) {
+ if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
+ // bind in strict mode source files with alwaysStrict option
+ return true;
}
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
+ else {
+ return !!file.externalModuleIndicator;
}
- return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
}
- function checkStrictModeFunctionName(node) {
- if (inStrictMode) {
- // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
- checkStrictModeEvalOrArguments(node, node.name);
- }
+ function createSymbol(flags, name) {
+ symbolCount++;
+ return new Symbol(flags, name);
}
- function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
- // Provide specialized messages to help the user understand why we think they're in
- // strict mode.
- if (ts.getContainingClass(node)) {
- return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;
+ function addDeclarationToSymbol(symbol, node, symbolFlags) {
+ symbol.flags |= symbolFlags;
+ node.symbol = symbol;
+ symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
+ if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
+ symbol.exports = ts.createSymbolTable();
}
- if (file.externalModuleIndicator) {
- return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
+ if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
+ symbol.members = ts.createSymbolTable();
}
- return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
- }
- function checkStrictModeFunctionDeclaration(node) {
- if (languageVersion < 2 /* ES2015 */) {
- // Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
- blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
- !ts.isFunctionLike(blockScopeContainer)) {
- // We check first if the name is inside class declaration or class expression; if so give explicit message
- // otherwise report generic error message.
- var errorSpan = ts.getErrorSpanForNode(file, node);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
- }
+ // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
+ if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
+ symbol.constEnumOnlyModule = false;
}
- }
- function checkStrictModeNumericLiteral(node) {
- if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
- file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
+ if (symbolFlags & 111551 /* Value */) {
+ ts.setValueDeclaration(symbol, node);
}
}
- function checkStrictModePostfixUnaryExpression(node) {
- // Grammar checking
- // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
- // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
- // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.operand);
+ // Should not be called on a declaration with a computed property name,
+ // unless it is a well known Symbol.
+ function getDeclarationName(node) {
+ if (node.kind === 270 /* ExportAssignment */) {
+ return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
}
- }
- function checkStrictModePrefixUnaryExpression(node) {
- // Grammar checking
- if (inStrictMode) {
- if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
- checkStrictModeEvalOrArguments(node, node.operand);
+ var name = ts.getNameOfDeclaration(node);
+ if (name) {
+ if (ts.isAmbientModule(node)) {
+ var moduleName = ts.getTextOfIdentifierOrLiteral(name);
+ return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"".concat(moduleName, "\""));
+ }
+ if (name.kind === 161 /* ComputedPropertyName */) {
+ var nameExpression = name.expression;
+ // treat computed property names where expression is string/numeric literal as just string/numeric literal
+ if (ts.isStringOrNumericLiteralLike(nameExpression)) {
+ return ts.escapeLeadingUnderscores(nameExpression.text);
+ }
+ if (ts.isSignedNumericLiteral(nameExpression)) {
+ return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
+ }
+ else {
+ ts.Debug.fail("Only computed properties with literal names have declaration names");
+ }
+ }
+ if (ts.isPrivateIdentifier(name)) {
+ // containingClass exists because private names only allowed inside classes
+ var containingClass = ts.getContainingClass(node);
+ if (!containingClass) {
+ // we can get here in cases where there is already a parse error.
+ return undefined;
+ }
+ var containingClassSymbol = containingClass.symbol;
+ return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
}
+ return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
- }
- function checkStrictModeWithStatement(node) {
- // Grammar checking for withStatement
- if (inStrictMode) {
- errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
+ switch (node.kind) {
+ case 170 /* Constructor */:
+ return "__constructor" /* Constructor */;
+ case 178 /* FunctionType */:
+ case 173 /* CallSignature */:
+ case 321 /* JSDocSignature */:
+ return "__call" /* Call */;
+ case 179 /* ConstructorType */:
+ case 174 /* ConstructSignature */:
+ return "__new" /* New */;
+ case 175 /* IndexSignature */:
+ return "__index" /* Index */;
+ case 271 /* ExportDeclaration */:
+ return "__export" /* ExportStar */;
+ case 303 /* SourceFile */:
+ // json file should behave as
+ // module.exports = ...
+ return "export=" /* ExportEquals */;
+ case 220 /* BinaryExpression */:
+ if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
+ // module.exports = ...
+ return "export=" /* ExportEquals */;
+ }
+ ts.Debug.fail("Unknown binary declaration kind");
+ break;
+ case 315 /* JSDocFunctionType */:
+ return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
+ case 163 /* Parameter */:
+ // Parameters with names are handled at the top of this function. Parameters
+ // without names can only come from JSDocFunctionTypes.
+ ts.Debug.assert(node.parent.kind === 315 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); });
+ var functionType = node.parent;
+ var index = functionType.parameters.indexOf(node);
+ return "arg" + index;
}
}
- function checkStrictModeLabeledStatement(node) {
- // Grammar checking for labeledStatement
- if (inStrictMode && options.target >= 2 /* ES2015 */) {
- if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
- errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
+ function getDisplayName(node) {
+ return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
+ }
+ /**
+ * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
+ * @param symbolTable - The symbol table which node will be added to.
+ * @param parent - node's parent declaration.
+ * @param node - The declaration to be added to the symbol table
+ * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
+ * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
+ */
+ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod, isComputedName) {
+ ts.Debug.assert(isComputedName || !ts.hasDynamicName(node));
+ var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
+ // The exported symbol for an export default function/class node is always named "default"
+ var name = isComputedName ? "__computed" /* Computed */
+ : isDefaultExport && parent ? "default" /* Default */
+ : getDeclarationName(node);
+ var symbol;
+ if (name === undefined) {
+ symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
+ }
+ else {
+ // Check and see if the symbol table already has a symbol with this name. If not,
+ // create a new symbol with this name and add it to the table. Note that we don't
+ // give the new symbol any flags *yet*. This ensures that it will not conflict
+ // with the 'excludes' flags we pass in.
+ //
+ // If we do get an existing symbol, see if it conflicts with the new symbol we're
+ // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
+ // the same symbol table. If we have a conflict, report the issue on each
+ // declaration we have for this symbol, and then create a new symbol for this
+ // declaration.
+ //
+ // Note that when properties declared in Javascript constructors
+ // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
+ // Always. This allows the common Javascript pattern of overwriting a prototype method
+ // with an bound instance method of the same type: `this.method = this.method.bind(this)`
+ //
+ // If we created a new symbol, either because we didn't have a symbol with this name
+ // in the symbol table, or we conflicted with an existing symbol, then just add this
+ // node as the sole declaration of the new symbol.
+ //
+ // Otherwise, we'll be merging into a compatible existing symbol (for example when
+ // you have multiple 'vars' with the same name in the same container). In this case
+ // just add this node into the declarations list of the symbol.
+ symbol = symbolTable.get(name);
+ if (includes & 2885600 /* Classifiable */) {
+ classifiableNames.add(name);
+ }
+ if (!symbol) {
+ symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
+ if (isReplaceableByMethod)
+ symbol.isReplaceableByMethod = true;
+ }
+ else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
+ // A symbol already exists, so don't add this as a declaration.
+ return symbol;
+ }
+ else if (symbol.flags & excludes) {
+ if (symbol.isReplaceableByMethod) {
+ // Javascript constructor-declared symbols can be discarded in favor of
+ // prototype symbols like methods.
+ symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
+ }
+ else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
+ // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
+ if (ts.isNamedDeclaration(node)) {
+ ts.setParent(node.name, node);
+ }
+ // Report errors every position with duplicate declaration
+ // Report errors on previous encountered declarations
+ var message_1 = symbol.flags & 2 /* BlockScopedVariable */
+ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
+ : ts.Diagnostics.Duplicate_identifier_0;
+ var messageNeedsName_1 = true;
+ if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
+ message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
+ messageNeedsName_1 = false;
+ }
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
+ // If the current node is a default export of some sort, then check if
+ // there are any other default exports that we need to error on.
+ // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
+ if (isDefaultExport) {
+ message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
+ messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
+ }
+ else {
+ // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
+ // Error on multiple export default in the following case:
+ // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
+ // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
+ if (symbol.declarations && symbol.declarations.length &&
+ (node.kind === 270 /* ExportAssignment */ && !node.isExportEquals)) {
+ message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
+ messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
+ }
+ }
+ }
+ var relatedInformation_1 = [];
+ if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
+ // export type T; - may have meant export type { T }?
+ relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { ".concat(ts.unescapeLeadingUnderscores(node.name.escapedText), " }")));
+ }
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInformation_1, false)));
+ symbol = createSymbol(0 /* None */, name);
+ }
}
}
- }
- function errorOnFirstToken(node, message, arg0, arg1, arg2) {
- var span = ts.getSpanOfTokenAtPosition(file, node.pos);
- file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
- }
- function errorOrSuggestionOnNode(isError, node, message) {
- errorOrSuggestionOnRange(isError, node, node, message);
- }
- function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
- addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
- }
- function addErrorOrSuggestionDiagnostic(isError, range, message) {
- var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
- if (isError) {
- file.bindDiagnostics.push(diag);
+ addDeclarationToSymbol(symbol, node, includes);
+ if (symbol.parent) {
+ ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
}
else {
- file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
+ symbol.parent = parent;
}
+ return symbol;
}
- function bind(node) {
- if (!node) {
- return;
- }
- node.parent = parent;
- var saveInStrictMode = inStrictMode;
- // Even though in the AST the jsdoc @typedef node belongs to the current node,
- // its symbol might be in the same scope with the current node's symbol. Consider:
- //
- // /** @typedef {string | number} MyType */
- // function foo();
- //
- // Here the current node is "foo", which is a container, but the scope of "MyType" should
- // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
- // and skip binding this tag later when binding all the other jsdoc tags.
- // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
- // and then potentially add the symbol to an appropriate symbol table. Possible
- // destination symbol tables are:
- //
- // 1) The 'exports' table of the current container's symbol.
- // 2) The 'members' table of the current container's symbol.
- // 3) The 'locals' table of the current container.
- //
- // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
- // (like TypeLiterals for example) will not be put in any table.
- bindWorker(node);
- // Then we recurse into the children of the node to bind them as well. For certain
- // symbols we do specialized work when we recurse. For example, we'll keep track of
- // the current 'container' node when it changes. This helps us know which symbol table
- // a local should go into for example. Since terminal nodes are known not to have
- // children, as an optimization we don't process those.
- if (node.kind > 152 /* LastToken */) {
- var saveParent = parent;
- parent = node;
- var containerFlags = getContainerFlags(node);
- if (containerFlags === 0 /* None */) {
- bindChildren(node);
+ function declareModuleMember(node, symbolFlags, symbolExcludes) {
+ var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node);
+ if (symbolFlags & 2097152 /* Alias */) {
+ if (node.kind === 274 /* ExportSpecifier */ || (node.kind === 264 /* ImportEqualsDeclaration */ && hasExportModifier)) {
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
}
else {
- bindContainer(node, containerFlags);
+ return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
- parent = saveParent;
- }
- else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
- subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
- var saveParent = parent;
- if (node.kind === 1 /* EndOfFileToken */)
- parent = node;
- bindJSDoc(node);
- parent = saveParent;
}
- inStrictMode = saveInStrictMode;
- }
- function bindJSDoc(node) {
- if (ts.hasJSDocNodes(node)) {
- if (ts.isInJSFile(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var j = _a[_i];
- bind(j);
+ else {
+ // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
+ // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
+ //
+ // 1. We treat locals and exports of the same name as mutually exclusive within a container.
+ // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
+ // with the same name in the same container.
+ // TODO: Make this a more specific error and decouple it from the exclusion logic.
+ // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
+ // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
+ // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
+ // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
+ // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
+ // and this case is specially handled. Module augmentations should only be merged with original module definition
+ // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
+ if (ts.isJSDocTypeAlias(node))
+ ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
+ if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) {
+ if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
}
+ var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
+ var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
+ local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ node.localSymbol = local;
+ return local;
}
else {
- for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
- var j = _c[_b];
- setParentPointers(node, j);
- }
+ return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
}
- function updateStrictModeStatementList(statements) {
- if (!inStrictMode) {
- for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
- var statement = statements_2[_i];
- if (!ts.isPrologueDirective(statement)) {
- return;
- }
- if (isUseStrictPrologueDirective(statement)) {
- inStrictMode = true;
- return;
- }
- }
+ function jsdocTreatAsExported(node) {
+ if (node.parent && ts.isModuleDeclaration(node)) {
+ node = node.parent;
}
+ if (!ts.isJSDocTypeAlias(node))
+ return false;
+ // jsdoc typedef handling is a bit of a doozy, but to summarize, treat the typedef as exported if:
+ // 1. It has an explicit name (since by default typedefs are always directly exported, either at the top level or in a container), or
+ if (!ts.isJSDocEnumTag(node) && !!node.fullName)
+ return true;
+ // 2. The thing a nameless typedef pulls its name from is implicitly a direct export (either by assignment or actual export flag).
+ var declName = ts.getNameOfDeclaration(node);
+ if (!declName)
+ return false;
+ if (ts.isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent))
+ return true;
+ if (ts.isDeclaration(declName.parent) && ts.getCombinedModifierFlags(declName.parent) & 1 /* Export */)
+ return true;
+ // This could potentially be simplified by having `delayedBindJSDocTypedefTag` pass in an override for `hasExportModifier`, since it should
+ // already have calculated and branched on most of this.
+ return false;
}
- /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
- function isUseStrictPrologueDirective(node) {
- var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
- // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
- // string to contain unicode escapes (as per ES5).
- return nodeText === '"use strict"' || nodeText === "'use strict'";
- }
- function bindWorker(node) {
- switch (node.kind) {
- /* Strict mode checks */
- case 75 /* Identifier */:
- // for typedef type names with namespaces, bind the new jsdoc type symbol here
- // because it requires all containing namespaces to be in effect, namely the
- // current "blockScopeContainer" needs to be set to its immediate namespace parent.
- if (node.isInJSDocNamespace) {
- var parentNode = node.parent;
- while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
- parentNode = parentNode.parent;
- }
- bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
- break;
- }
- // falls through
- case 104 /* ThisKeyword */:
- if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
- node.flowNode = currentFlow;
- }
- return checkStrictModeIdentifier(node);
- case 76 /* PrivateIdentifier */:
- return checkPrivateIdentifier(node);
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- var expr = node;
- if (currentFlow && isNarrowableReference(expr)) {
- expr.flowNode = currentFlow;
- }
- if (ts.isSpecialPropertyDeclaration(expr)) {
- bindSpecialPropertyDeclaration(expr);
- }
- if (ts.isInJSFile(expr) &&
- file.commonJsModuleIndicator &&
- ts.isModuleExportsAccessExpression(expr) &&
- !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
- declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
- }
- break;
- case 209 /* BinaryExpression */:
- var specialKind = ts.getAssignmentDeclarationKind(node);
- switch (specialKind) {
- case 1 /* ExportsProperty */:
- bindExportsPropertyAssignment(node);
- break;
- case 2 /* ModuleExports */:
- bindModuleExportsAssignment(node);
- break;
- case 3 /* PrototypeProperty */:
- bindPrototypePropertyAssignment(node.left, node);
- break;
- case 6 /* Prototype */:
- bindPrototypeAssignment(node);
- break;
- case 4 /* ThisProperty */:
- bindThisPropertyAssignment(node);
- break;
- case 5 /* Property */:
- bindSpecialPropertyAssignment(node);
- break;
- case 0 /* None */:
- // Nothing to do
- break;
- default:
- ts.Debug.fail("Unknown binary expression special property assignment kind");
- }
- return checkStrictModeBinaryExpression(node);
- case 280 /* CatchClause */:
- return checkStrictModeCatchClause(node);
- case 203 /* DeleteExpression */:
- return checkStrictModeDeleteExpression(node);
- case 8 /* NumericLiteral */:
- return checkStrictModeNumericLiteral(node);
- case 208 /* PostfixUnaryExpression */:
- return checkStrictModePostfixUnaryExpression(node);
- case 207 /* PrefixUnaryExpression */:
- return checkStrictModePrefixUnaryExpression(node);
- case 236 /* WithStatement */:
- return checkStrictModeWithStatement(node);
- case 238 /* LabeledStatement */:
- return checkStrictModeLabeledStatement(node);
- case 183 /* ThisType */:
- seenThisKeyword = true;
- return;
- case 168 /* TypePredicate */:
- break; // Binding the children will handle everything
- case 155 /* TypeParameter */:
- return bindTypeParameter(node);
- case 156 /* Parameter */:
- return bindParameter(node);
- case 242 /* VariableDeclaration */:
- return bindVariableDeclarationOrBindingElement(node);
- case 191 /* BindingElement */:
- node.flowNode = currentFlow;
- return bindVariableDeclarationOrBindingElement(node);
- case 159 /* PropertyDeclaration */:
- case 158 /* PropertySignature */:
- return bindPropertyWorker(node);
- case 281 /* PropertyAssignment */:
- case 282 /* ShorthandPropertyAssignment */:
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
- case 284 /* EnumMember */:
- return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
- case 161 /* MethodDeclaration */:
- case 160 /* MethodSignature */:
- // If this is an ObjectLiteralExpression method, then it sits in the same space
- // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
- // so that it will conflict with any other object literal members with the same
- // name.
- return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
- case 244 /* FunctionDeclaration */:
- return bindFunctionDeclaration(node);
- case 162 /* Constructor */:
- return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
- case 163 /* GetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
- case 164 /* SetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
- case 170 /* FunctionType */:
- case 300 /* JSDocFunctionType */:
- case 305 /* JSDocSignature */:
- case 171 /* ConstructorType */:
- return bindFunctionOrConstructorType(node);
- case 173 /* TypeLiteral */:
- case 304 /* JSDocTypeLiteral */:
- case 186 /* MappedType */:
- return bindAnonymousTypeWorker(node);
- case 310 /* JSDocClassTag */:
- return bindJSDocClassTag(node);
- case 193 /* ObjectLiteralExpression */:
- return bindObjectLiteralExpression(node);
- case 201 /* FunctionExpression */:
- case 202 /* ArrowFunction */:
- return bindFunctionExpression(node);
- case 196 /* CallExpression */:
- var assignmentKind = ts.getAssignmentDeclarationKind(node);
- switch (assignmentKind) {
- case 7 /* ObjectDefinePropertyValue */:
- return bindObjectDefinePropertyAssignment(node);
- case 8 /* ObjectDefinePropertyExports */:
- return bindObjectDefinePropertyExport(node);
- case 9 /* ObjectDefinePrototypeProperty */:
- return bindObjectDefinePrototypeProperty(node);
- case 0 /* None */:
- break; // Nothing to do
- default:
- return ts.Debug.fail("Unknown call expression assignment declaration kind");
+ // All container nodes are kept on a linked list in declaration order. This list is used by
+ // the getLocalNameOfContainer function in the type checker to validate that the local name
+ // used for a container is unique.
+ function bindContainer(node, containerFlags) {
+ // Before we recurse into a node's children, we first save the existing parent, container
+ // and block-container. Then after we pop out of processing the children, we restore
+ // these saved values.
+ var saveContainer = container;
+ var saveThisParentContainer = thisParentContainer;
+ var savedBlockScopeContainer = blockScopeContainer;
+ // Depending on what kind of node this is, we may have to adjust the current container
+ // and block-container. If the current node is a container, then it is automatically
+ // considered the current block-container as well. Also, for containers that we know
+ // may contain locals, we eagerly initialize the .locals field. We do this because
+ // it's highly likely that the .locals will be needed to place some child in (for example,
+ // a parameter, or variable declaration).
+ //
+ // However, we do not proactively create the .locals for block-containers because it's
+ // totally normal and common for block-containers to never actually have a block-scoped
+ // variable in them. We don't want to end up allocating an object for every 'block' we
+ // run into when most of them won't be necessary.
+ //
+ // Finally, if this is a block-container, then we clear out any existing .locals object
+ // it may contain within it. This happens in incremental scenarios. Because we can be
+ // reusing a node from a previous compilation, that node may have had 'locals' created
+ // for it. We must clear this so we don't accidentally move any stale data forward from
+ // a previous compilation.
+ if (containerFlags & 1 /* IsContainer */) {
+ if (node.kind !== 213 /* ArrowFunction */) {
+ thisParentContainer = container;
+ }
+ container = blockScopeContainer = node;
+ if (containerFlags & 32 /* HasLocals */) {
+ container.locals = ts.createSymbolTable();
+ }
+ addToContainerChain(container);
+ }
+ else if (containerFlags & 2 /* IsBlockScopedContainer */) {
+ blockScopeContainer = node;
+ blockScopeContainer.locals = undefined;
+ }
+ if (containerFlags & 4 /* IsControlFlowContainer */) {
+ var saveCurrentFlow = currentFlow;
+ var saveBreakTarget = currentBreakTarget;
+ var saveContinueTarget = currentContinueTarget;
+ var saveReturnTarget = currentReturnTarget;
+ var saveExceptionTarget = currentExceptionTarget;
+ var saveActiveLabelList = activeLabelList;
+ var saveHasExplicitReturn = hasExplicitReturn;
+ var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasSyntacticModifier(node, 256 /* Async */) &&
+ !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
+ // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
+ // similarly to break statements that exit to a label just past the statement body.
+ if (!isIIFE) {
+ currentFlow = initFlowNode({ flags: 2 /* Start */ });
+ if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) {
+ currentFlow.node = node;
}
- if (ts.isInJSFile(node)) {
- bindCallExpression(node);
+ }
+ // We create a return control flow graph for IIFEs and constructors. For constructors
+ // we use the return control flow graph in strict property initialization checks.
+ currentReturnTarget = isIIFE || node.kind === 170 /* Constructor */ || node.kind === 169 /* ClassStaticBlockDeclaration */ || (ts.isInJSFile(node) && (node.kind === 255 /* FunctionDeclaration */ || node.kind === 212 /* FunctionExpression */)) ? createBranchLabel() : undefined;
+ currentExceptionTarget = undefined;
+ currentBreakTarget = undefined;
+ currentContinueTarget = undefined;
+ activeLabelList = undefined;
+ hasExplicitReturn = false;
+ bindChildren(node);
+ // Reset all reachability check related flags on node (for incremental scenarios)
+ node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
+ if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
+ node.flags |= 256 /* HasImplicitReturn */;
+ if (hasExplicitReturn)
+ node.flags |= 512 /* HasExplicitReturn */;
+ node.endFlowNode = currentFlow;
+ }
+ if (node.kind === 303 /* SourceFile */) {
+ node.flags |= emitFlags;
+ node.endFlowNode = currentFlow;
+ }
+ if (currentReturnTarget) {
+ addAntecedent(currentReturnTarget, currentFlow);
+ currentFlow = finishFlowLabel(currentReturnTarget);
+ if (node.kind === 170 /* Constructor */ || node.kind === 169 /* ClassStaticBlockDeclaration */ || (ts.isInJSFile(node) && (node.kind === 255 /* FunctionDeclaration */ || node.kind === 212 /* FunctionExpression */))) {
+ node.returnFlowNode = currentFlow;
}
+ }
+ if (!isIIFE) {
+ currentFlow = saveCurrentFlow;
+ }
+ currentBreakTarget = saveBreakTarget;
+ currentContinueTarget = saveContinueTarget;
+ currentReturnTarget = saveReturnTarget;
+ currentExceptionTarget = saveExceptionTarget;
+ activeLabelList = saveActiveLabelList;
+ hasExplicitReturn = saveHasExplicitReturn;
+ }
+ else if (containerFlags & 64 /* IsInterface */) {
+ seenThisKeyword = false;
+ bindChildren(node);
+ node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
+ }
+ else {
+ bindChildren(node);
+ }
+ container = saveContainer;
+ thisParentContainer = saveThisParentContainer;
+ blockScopeContainer = savedBlockScopeContainer;
+ }
+ function bindEachFunctionsFirst(nodes) {
+ bindEach(nodes, function (n) { return n.kind === 255 /* FunctionDeclaration */ ? bind(n) : undefined; });
+ bindEach(nodes, function (n) { return n.kind !== 255 /* FunctionDeclaration */ ? bind(n) : undefined; });
+ }
+ function bindEach(nodes, bindFunction) {
+ if (bindFunction === void 0) { bindFunction = bind; }
+ if (nodes === undefined) {
+ return;
+ }
+ ts.forEach(nodes, bindFunction);
+ }
+ function bindEachChild(node) {
+ ts.forEachChild(node, bind, bindEach);
+ }
+ function bindChildren(node) {
+ var saveInAssignmentPattern = inAssignmentPattern;
+ // Most nodes aren't valid in an assignment pattern, so we clear the value here
+ // and set it before we descend into nodes that could actually be part of an assignment pattern.
+ inAssignmentPattern = false;
+ if (checkUnreachable(node)) {
+ bindEachChild(node);
+ bindJSDoc(node);
+ inAssignmentPattern = saveInAssignmentPattern;
+ return;
+ }
+ if (node.kind >= 236 /* FirstStatement */ && node.kind <= 252 /* LastStatement */ && !options.allowUnreachableCode) {
+ node.flowNode = currentFlow;
+ }
+ switch (node.kind) {
+ case 240 /* WhileStatement */:
+ bindWhileStatement(node);
break;
- // Members of classes, interfaces, and modules
- case 214 /* ClassExpression */:
- case 245 /* ClassDeclaration */:
- // All classes are automatically in strict mode in ES6.
- inStrictMode = true;
- return bindClassLikeDeclaration(node);
- case 246 /* InterfaceDeclaration */:
- return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
- case 247 /* TypeAliasDeclaration */:
- return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
- case 248 /* EnumDeclaration */:
- return bindEnumDeclaration(node);
- case 249 /* ModuleDeclaration */:
- return bindModuleDeclaration(node);
- // Jsx-attributes
- case 274 /* JsxAttributes */:
- return bindJsxAttributes(node);
- case 273 /* JsxAttribute */:
- return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
- // Imports and exports
- case 253 /* ImportEqualsDeclaration */:
- case 256 /* NamespaceImport */:
- case 258 /* ImportSpecifier */:
- case 263 /* ExportSpecifier */:
- return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
- case 252 /* NamespaceExportDeclaration */:
- return bindNamespaceExportDeclaration(node);
- case 255 /* ImportClause */:
- return bindImportClause(node);
- case 260 /* ExportDeclaration */:
- return bindExportDeclaration(node);
- case 259 /* ExportAssignment */:
- return bindExportAssignment(node);
- case 290 /* SourceFile */:
- updateStrictModeStatementList(node.statements);
- return bindSourceFileIfExternalModule();
- case 223 /* Block */:
- if (!ts.isFunctionLike(node.parent)) {
+ case 239 /* DoStatement */:
+ bindDoStatement(node);
+ break;
+ case 241 /* ForStatement */:
+ bindForStatement(node);
+ break;
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ bindForInOrForOfStatement(node);
+ break;
+ case 238 /* IfStatement */:
+ bindIfStatement(node);
+ break;
+ case 246 /* ReturnStatement */:
+ case 250 /* ThrowStatement */:
+ bindReturnOrThrow(node);
+ break;
+ case 245 /* BreakStatement */:
+ case 244 /* ContinueStatement */:
+ bindBreakOrContinueStatement(node);
+ break;
+ case 251 /* TryStatement */:
+ bindTryStatement(node);
+ break;
+ case 248 /* SwitchStatement */:
+ bindSwitchStatement(node);
+ break;
+ case 262 /* CaseBlock */:
+ bindCaseBlock(node);
+ break;
+ case 288 /* CaseClause */:
+ bindCaseClause(node);
+ break;
+ case 237 /* ExpressionStatement */:
+ bindExpressionStatement(node);
+ break;
+ case 249 /* LabeledStatement */:
+ bindLabeledStatement(node);
+ break;
+ case 218 /* PrefixUnaryExpression */:
+ bindPrefixUnaryExpressionFlow(node);
+ break;
+ case 219 /* PostfixUnaryExpression */:
+ bindPostfixUnaryExpressionFlow(node);
+ break;
+ case 220 /* BinaryExpression */:
+ if (ts.isDestructuringAssignment(node)) {
+ // Carry over whether we are in an assignment pattern to
+ // binary expressions that could actually be an initializer
+ inAssignmentPattern = saveInAssignmentPattern;
+ bindDestructuringAssignmentFlow(node);
return;
}
+ bindBinaryExpressionFlow(node);
+ break;
+ case 214 /* DeleteExpression */:
+ bindDeleteExpressionFlow(node);
+ break;
+ case 221 /* ConditionalExpression */:
+ bindConditionalExpressionFlow(node);
+ break;
+ case 253 /* VariableDeclaration */:
+ bindVariableDeclarationFlow(node);
+ break;
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ bindAccessExpressionFlow(node);
+ break;
+ case 207 /* CallExpression */:
+ bindCallExpressionFlow(node);
+ break;
+ case 229 /* NonNullExpression */:
+ bindNonNullExpressionFlow(node);
+ break;
+ case 343 /* JSDocTypedefTag */:
+ case 336 /* JSDocCallbackTag */:
+ case 337 /* JSDocEnumTag */:
+ bindJSDocTypeAlias(node);
+ break;
+ // In source files and blocks, bind functions first to match hoisting that occurs at runtime
+ case 303 /* SourceFile */: {
+ bindEachFunctionsFirst(node.statements);
+ bind(node.endOfFileToken);
+ break;
+ }
+ case 234 /* Block */:
+ case 261 /* ModuleBlock */:
+ bindEachFunctionsFirst(node.statements);
+ break;
+ case 202 /* BindingElement */:
+ bindBindingElementFlow(node);
+ break;
+ case 204 /* ObjectLiteralExpression */:
+ case 203 /* ArrayLiteralExpression */:
+ case 294 /* PropertyAssignment */:
+ case 224 /* SpreadElement */:
+ // Carry over whether we are in an assignment pattern of Object and Array literals
+ // as well as their children that are valid assignment targets.
+ inAssignmentPattern = saveInAssignmentPattern;
// falls through
- case 250 /* ModuleBlock */:
- return updateStrictModeStatementList(node.statements);
- case 317 /* JSDocParameterTag */:
- if (node.parent.kind === 305 /* JSDocSignature */) {
- return bindParameter(node);
- }
- if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
- break;
- }
- // falls through
- case 323 /* JSDocPropertyTag */:
- var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
- 4 /* Property */ | 16777216 /* Optional */ :
- 4 /* Property */;
- return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 322 /* JSDocTypedefTag */:
- case 315 /* JSDocCallbackTag */:
- case 316 /* JSDocEnumTag */:
- return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
+ default:
+ bindEachChild(node);
+ break;
}
+ bindJSDoc(node);
+ inAssignmentPattern = saveInAssignmentPattern;
}
- function bindPropertyWorker(node) {
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
+ function isNarrowingExpression(expr) {
+ switch (expr.kind) {
+ case 79 /* Identifier */:
+ case 80 /* PrivateIdentifier */:
+ case 108 /* ThisKeyword */:
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ return containsNarrowableReference(expr);
+ case 207 /* CallExpression */:
+ return hasNarrowableArgument(expr);
+ case 211 /* ParenthesizedExpression */:
+ case 229 /* NonNullExpression */:
+ return isNarrowingExpression(expr.expression);
+ case 220 /* BinaryExpression */:
+ return isNarrowingBinaryExpression(expr);
+ case 218 /* PrefixUnaryExpression */:
+ return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
+ case 215 /* TypeOfExpression */:
+ return isNarrowingExpression(expr.expression);
+ }
+ return false;
}
- function bindAnonymousTypeWorker(node) {
- return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
+ function isNarrowableReference(expr) {
+ return ts.isDottedName(expr)
+ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression)
+ || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right)
+ || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression)
+ || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left);
}
- function bindSourceFileIfExternalModule() {
- setExportContextFlag(file);
- if (ts.isExternalModule(file)) {
- bindSourceFileAsExternalModule();
+ function containsNarrowableReference(expr) {
+ return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
+ }
+ function hasNarrowableArgument(expr) {
+ if (expr.arguments) {
+ for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
+ var argument = _a[_i];
+ if (containsNarrowableReference(argument)) {
+ return true;
+ }
+ }
}
- else if (ts.isJsonSourceFile(file)) {
- bindSourceFileAsExternalModule();
- // Create symbol equivalent for the module.exports = {}
- var originalSymbol = file.symbol;
- declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
- file.symbol = originalSymbol;
+ if (expr.expression.kind === 205 /* PropertyAccessExpression */ &&
+ containsNarrowableReference(expr.expression.expression)) {
+ return true;
}
+ return false;
}
- function bindSourceFileAsExternalModule() {
- bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
+ function isNarrowingTypeofOperands(expr1, expr2) {
+ return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
}
- function bindExportAssignment(node) {
- if (!container.symbol || !container.symbol.exports) {
- // Export assignment in some sort of block construct
- bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
- }
- else {
- var flags = ts.exportAssignmentIsAlias(node)
- // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
- ? 2097152 /* Alias */
- // An export default clause with any other expression exports a value
- : 4 /* Property */;
- // If there is an `export default x;` alias declaration, can't `export default` anything else.
- // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
- var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
- if (node.isExportEquals) {
- // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
- ts.setValueDeclaration(symbol, node);
- }
+ function isNarrowingBinaryExpression(expr) {
+ switch (expr.operatorToken.kind) {
+ case 63 /* EqualsToken */:
+ case 75 /* BarBarEqualsToken */:
+ case 76 /* AmpersandAmpersandEqualsToken */:
+ case 77 /* QuestionQuestionEqualsToken */:
+ return containsNarrowableReference(expr.left);
+ case 34 /* EqualsEqualsToken */:
+ case 35 /* ExclamationEqualsToken */:
+ case 36 /* EqualsEqualsEqualsToken */:
+ case 37 /* ExclamationEqualsEqualsToken */:
+ return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
+ isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
+ case 102 /* InstanceOfKeyword */:
+ return isNarrowableOperand(expr.left);
+ case 101 /* InKeyword */:
+ return isNarrowingExpression(expr.right);
+ case 27 /* CommaToken */:
+ return isNarrowingExpression(expr.right);
}
+ return false;
}
- function bindNamespaceExportDeclaration(node) {
- if (node.modifiers && node.modifiers.length) {
- file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
- }
- var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
- : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
- : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
- : undefined;
- if (diag) {
- file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
+ function isNarrowableOperand(expr) {
+ switch (expr.kind) {
+ case 211 /* ParenthesizedExpression */:
+ return isNarrowableOperand(expr.expression);
+ case 220 /* BinaryExpression */:
+ switch (expr.operatorToken.kind) {
+ case 63 /* EqualsToken */:
+ return isNarrowableOperand(expr.left);
+ case 27 /* CommaToken */:
+ return isNarrowableOperand(expr.right);
+ }
}
- else {
- file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
- declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ return containsNarrowableReference(expr);
+ }
+ function createBranchLabel() {
+ return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
+ }
+ function createLoopLabel() {
+ return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
+ }
+ function createReduceLabel(target, antecedents, antecedent) {
+ return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
+ }
+ function setFlowNodeReferenced(flow) {
+ // On first reference we set the Referenced flag, thereafter we set the Shared flag
+ flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
+ }
+ function addAntecedent(label, antecedent) {
+ if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
+ (label.antecedents || (label.antecedents = [])).push(antecedent);
+ setFlowNodeReferenced(antecedent);
}
}
- function bindExportDeclaration(node) {
- if (!container.symbol || !container.symbol.exports) {
- // Export * in some sort of block construct
- bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
+ function createFlowCondition(flags, antecedent, expression) {
+ if (antecedent.flags & 1 /* Unreachable */) {
+ return antecedent;
}
- else if (!node.exportClause) {
- // All export * declarations are collected in an __export symbol
- declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
+ if (!expression) {
+ return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
}
- else if (ts.isNamespaceExport(node.exportClause)) {
- // declareSymbol walks up parents to find name text, parent _must_ be set
- // but won't be set by the normal binder walk until `bindChildren` later on.
- node.exportClause.parent = node;
- declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ if ((expression.kind === 110 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
+ expression.kind === 95 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
+ !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
+ return unreachableFlow;
}
- }
- function bindImportClause(node) {
- if (node.name) {
- declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ if (!isNarrowingExpression(expression)) {
+ return antecedent;
}
+ setFlowNodeReferenced(antecedent);
+ return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
}
- function setCommonJsModuleIndicator(node) {
- if (file.externalModuleIndicator) {
- return false;
- }
- if (!file.commonJsModuleIndicator) {
- file.commonJsModuleIndicator = node;
- bindSourceFileAsExternalModule();
+ function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
+ setFlowNodeReferenced(antecedent);
+ return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
+ }
+ function createFlowMutation(flags, antecedent, node) {
+ setFlowNodeReferenced(antecedent);
+ var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
+ if (currentExceptionTarget) {
+ addAntecedent(currentExceptionTarget, result);
}
- return true;
+ return result;
}
- function bindObjectDefinePropertyExport(node) {
- if (!setCommonJsModuleIndicator(node)) {
- return;
+ function createFlowCall(antecedent, node) {
+ setFlowNodeReferenced(antecedent);
+ return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
+ }
+ function finishFlowLabel(flow) {
+ var antecedents = flow.antecedents;
+ if (!antecedents) {
+ return unreachableFlow;
}
- var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
- if (symbol) {
- addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
- }
- return symbol;
- });
- if (symbol) {
- var flags = 4 /* Property */ | 1048576 /* ExportValue */;
- declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
+ if (antecedents.length === 1) {
+ return antecedents[0];
}
+ return flow;
}
- function bindExportsPropertyAssignment(node) {
- // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
- // expression is the declaration
- if (!setCommonJsModuleIndicator(node)) {
- return;
+ function isStatementCondition(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 238 /* IfStatement */:
+ case 240 /* WhileStatement */:
+ case 239 /* DoStatement */:
+ return parent.expression === node;
+ case 241 /* ForStatement */:
+ case 221 /* ConditionalExpression */:
+ return parent.condition === node;
}
- var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
- if (symbol) {
- addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
+ return false;
+ }
+ function isLogicalExpression(node) {
+ while (true) {
+ if (node.kind === 211 /* ParenthesizedExpression */) {
+ node = node.expression;
+ }
+ else if (node.kind === 218 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
+ node = node.operand;
+ }
+ else {
+ return node.kind === 220 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
+ node.operatorToken.kind === 56 /* BarBarToken */ ||
+ node.operatorToken.kind === 60 /* QuestionQuestionToken */);
}
- return symbol;
- });
- if (symbol) {
- var flags = ts.isClassExpression(node.right) ?
- 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
- 4 /* Property */ | 1048576 /* ExportValue */;
- declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
}
}
- function bindModuleExportsAssignment(node) {
- // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
- // is still pointing to 'module.exports'.
- // We do not want to consider this as 'export=' since a module can have only one of these.
- // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
- if (!setCommonJsModuleIndicator(node)) {
- return;
+ function isLogicalAssignmentExpression(node) {
+ node = ts.skipParentheses(node);
+ return ts.isBinaryExpression(node) && ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind);
+ }
+ function isTopLevelLogicalExpression(node) {
+ while (ts.isParenthesizedExpression(node.parent) ||
+ ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
+ node = node.parent;
}
- var assignedExpression = ts.getRightMostAssignedExpression(node.right);
- if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
- return;
+ return !isStatementCondition(node) &&
+ !isLogicalAssignmentExpression(node.parent) &&
+ !isLogicalExpression(node.parent) &&
+ !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
+ }
+ function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
+ var savedTrueTarget = currentTrueTarget;
+ var savedFalseTarget = currentFalseTarget;
+ currentTrueTarget = trueTarget;
+ currentFalseTarget = falseTarget;
+ action(value);
+ currentTrueTarget = savedTrueTarget;
+ currentFalseTarget = savedFalseTarget;
+ }
+ function bindCondition(node, trueTarget, falseTarget) {
+ doWithConditionalBranches(bind, node, trueTarget, falseTarget);
+ if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
+ addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
+ addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
}
- // 'module.exports = expr' assignment
- var flags = ts.exportAssignmentIsAlias(node)
- ? 2097152 /* Alias */
- : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
- var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
- ts.setValueDeclaration(symbol, node);
}
- function bindThisPropertyAssignment(node) {
- ts.Debug.assert(ts.isInJSFile(node));
- // private identifiers *must* be declared (even in JS files)
- var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
- || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
- if (hasPrivateIdentifier) {
- return;
+ function bindIterativeStatement(node, breakTarget, continueTarget) {
+ var saveBreakTarget = currentBreakTarget;
+ var saveContinueTarget = currentContinueTarget;
+ currentBreakTarget = breakTarget;
+ currentContinueTarget = continueTarget;
+ bind(node);
+ currentBreakTarget = saveBreakTarget;
+ currentContinueTarget = saveContinueTarget;
+ }
+ function setContinueTarget(node, target) {
+ var label = activeLabelList;
+ while (label && node.parent.kind === 249 /* LabeledStatement */) {
+ label.continueTarget = target;
+ label = label.next;
+ node = node.parent;
}
- var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- switch (thisContainer.kind) {
- case 244 /* FunctionDeclaration */:
- case 201 /* FunctionExpression */:
- var constructorSymbol = thisContainer.symbol;
- // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
- if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
- var l = thisContainer.parent.left;
- if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
- constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
- }
- }
- if (constructorSymbol && constructorSymbol.valueDeclaration) {
- // Declare a 'member' if the container is an ES5 class or ES6 constructor
- constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
- // It's acceptable for multiple 'this' assignments of the same identifier to occur
- if (ts.hasDynamicName(node)) {
- bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
- }
- else {
- declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
- }
- addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
- }
- break;
- case 162 /* Constructor */:
- case 159 /* PropertyDeclaration */:
- case 161 /* MethodDeclaration */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- // this.foo assignment in a JavaScript class
- // Bind this property to the containing class
- var containingClass = thisContainer.parent;
- var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
- if (ts.hasDynamicName(node)) {
- bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
- }
- else {
- declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
- }
- break;
- case 290 /* SourceFile */:
- // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
- if (ts.hasDynamicName(node)) {
- break;
- }
- else if (thisContainer.commonJsModuleIndicator) {
- declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
- }
- break;
- default:
- ts.Debug.failBadSyntaxKind(thisContainer);
+ return target;
+ }
+ function bindWhileStatement(node) {
+ var preWhileLabel = setContinueTarget(node, createLoopLabel());
+ var preBodyLabel = createBranchLabel();
+ var postWhileLabel = createBranchLabel();
+ addAntecedent(preWhileLabel, currentFlow);
+ currentFlow = preWhileLabel;
+ bindCondition(node.expression, preBodyLabel, postWhileLabel);
+ currentFlow = finishFlowLabel(preBodyLabel);
+ bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
+ addAntecedent(preWhileLabel, currentFlow);
+ currentFlow = finishFlowLabel(postWhileLabel);
+ }
+ function bindDoStatement(node) {
+ var preDoLabel = createLoopLabel();
+ var preConditionLabel = setContinueTarget(node, createBranchLabel());
+ var postDoLabel = createBranchLabel();
+ addAntecedent(preDoLabel, currentFlow);
+ currentFlow = preDoLabel;
+ bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
+ addAntecedent(preConditionLabel, currentFlow);
+ currentFlow = finishFlowLabel(preConditionLabel);
+ bindCondition(node.expression, preDoLabel, postDoLabel);
+ currentFlow = finishFlowLabel(postDoLabel);
+ }
+ function bindForStatement(node) {
+ var preLoopLabel = setContinueTarget(node, createLoopLabel());
+ var preBodyLabel = createBranchLabel();
+ var postLoopLabel = createBranchLabel();
+ bind(node.initializer);
+ addAntecedent(preLoopLabel, currentFlow);
+ currentFlow = preLoopLabel;
+ bindCondition(node.condition, preBodyLabel, postLoopLabel);
+ currentFlow = finishFlowLabel(preBodyLabel);
+ bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
+ bind(node.incrementor);
+ addAntecedent(preLoopLabel, currentFlow);
+ currentFlow = finishFlowLabel(postLoopLabel);
+ }
+ function bindForInOrForOfStatement(node) {
+ var preLoopLabel = setContinueTarget(node, createLoopLabel());
+ var postLoopLabel = createBranchLabel();
+ bind(node.expression);
+ addAntecedent(preLoopLabel, currentFlow);
+ currentFlow = preLoopLabel;
+ if (node.kind === 243 /* ForOfStatement */) {
+ bind(node.awaitModifier);
}
+ addAntecedent(postLoopLabel, currentFlow);
+ bind(node.initializer);
+ if (node.initializer.kind !== 254 /* VariableDeclarationList */) {
+ bindAssignmentTargetFlow(node.initializer);
+ }
+ bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
+ addAntecedent(preLoopLabel, currentFlow);
+ currentFlow = finishFlowLabel(postLoopLabel);
}
- function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
- bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
- addLateBoundAssignmentDeclarationToSymbol(node, symbol);
+ function bindIfStatement(node) {
+ var thenLabel = createBranchLabel();
+ var elseLabel = createBranchLabel();
+ var postIfLabel = createBranchLabel();
+ bindCondition(node.expression, thenLabel, elseLabel);
+ currentFlow = finishFlowLabel(thenLabel);
+ bind(node.thenStatement);
+ addAntecedent(postIfLabel, currentFlow);
+ currentFlow = finishFlowLabel(elseLabel);
+ bind(node.elseStatement);
+ addAntecedent(postIfLabel, currentFlow);
+ currentFlow = finishFlowLabel(postIfLabel);
}
- function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
- if (symbol) {
- var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
- members.set("" + ts.getNodeId(node), node);
+ function bindReturnOrThrow(node) {
+ bind(node.expression);
+ if (node.kind === 246 /* ReturnStatement */) {
+ hasExplicitReturn = true;
+ if (currentReturnTarget) {
+ addAntecedent(currentReturnTarget, currentFlow);
+ }
}
+ currentFlow = unreachableFlow;
}
- function bindSpecialPropertyDeclaration(node) {
- if (node.expression.kind === 104 /* ThisKeyword */) {
- bindThisPropertyAssignment(node);
- }
- else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
- if (ts.isPrototypeAccess(node.expression)) {
- bindPrototypePropertyAssignment(node, node.parent);
- }
- else {
- bindStaticPropertyAssignment(node);
+ function findActiveLabel(name) {
+ for (var label = activeLabelList; label; label = label.next) {
+ if (label.name === name) {
+ return label;
}
}
+ return undefined;
}
- /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
- function bindPrototypeAssignment(node) {
- node.left.parent = node;
- node.right.parent = node;
- bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
- }
- function bindObjectDefinePrototypeProperty(node) {
- var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
- if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
- // Ensure the namespace symbol becomes class-like
- addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
+ function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
+ var flowLabel = node.kind === 245 /* BreakStatement */ ? breakTarget : continueTarget;
+ if (flowLabel) {
+ addAntecedent(flowLabel, currentFlow);
+ currentFlow = unreachableFlow;
}
- bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
- }
- /**
- * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
- * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
- */
- function bindPrototypePropertyAssignment(lhs, parent) {
- // Look up the function in the local scope, since prototype assignments should
- // follow the function declaration
- var classPrototype = lhs.expression;
- var constructorFunction = classPrototype.expression;
- // Fix up parent pointers since we're going to use these nodes before we bind into them
- lhs.parent = parent;
- constructorFunction.parent = classPrototype;
- classPrototype.parent = lhs;
- bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
- }
- function bindObjectDefinePropertyAssignment(node) {
- var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
- namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
- bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
- function bindSpecialPropertyAssignment(node) {
- // Class declarations in Typescript do not allow property declarations
- var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
- if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
- return;
- }
- // Fix up parent pointers since we're going to use these nodes before we bind into them
- node.left.parent = node;
- node.right.parent = node;
- if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
- // This can be an alias for the 'exports' or 'module.exports' names, e.g.
- // var util = module.exports;
- // util.property = function ...
- bindExportsPropertyAssignment(node);
- }
- else if (ts.hasDynamicName(node)) {
- bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
- var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
- addLateBoundAssignmentDeclarationToSymbol(node, sym);
+ function bindBreakOrContinueStatement(node) {
+ bind(node.label);
+ if (node.label) {
+ var activeLabel = findActiveLabel(node.label.escapedText);
+ if (activeLabel) {
+ activeLabel.referenced = true;
+ bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
+ }
}
else {
- bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
+ bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
}
}
- /**
- * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared.
- * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
- */
- function bindStaticPropertyAssignment(node) {
- ts.Debug.assert(!ts.isIdentifier(node));
- node.expression.parent = node;
- bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
- }
- function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
- if (isToplevel && !isPrototypeProperty) {
- // make symbols or add declarations for intermediate containers
- var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
- var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
- namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
- if (symbol) {
- addDeclarationToSymbol(symbol, id, flags_1);
- return symbol;
+ function bindTryStatement(node) {
+ // We conservatively assume that *any* code in the try block can cause an exception, but we only need
+ // to track code that causes mutations (because only mutations widen the possible control flow type of
+ // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
+ // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
+ // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
+ // represent exceptions that occur before any mutations.
+ var saveReturnTarget = currentReturnTarget;
+ var saveExceptionTarget = currentExceptionTarget;
+ var normalExitLabel = createBranchLabel();
+ var returnLabel = createBranchLabel();
+ var exceptionLabel = createBranchLabel();
+ if (node.finallyBlock) {
+ currentReturnTarget = returnLabel;
+ }
+ addAntecedent(exceptionLabel, currentFlow);
+ currentExceptionTarget = exceptionLabel;
+ bind(node.tryBlock);
+ addAntecedent(normalExitLabel, currentFlow);
+ if (node.catchClause) {
+ // Start of catch clause is the target of exceptions from try block.
+ currentFlow = finishFlowLabel(exceptionLabel);
+ // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
+ // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
+ // acts like a second try block.
+ exceptionLabel = createBranchLabel();
+ addAntecedent(exceptionLabel, currentFlow);
+ currentExceptionTarget = exceptionLabel;
+ bind(node.catchClause);
+ addAntecedent(normalExitLabel, currentFlow);
+ }
+ currentReturnTarget = saveReturnTarget;
+ currentExceptionTarget = saveExceptionTarget;
+ if (node.finallyBlock) {
+ // Possible ways control can reach the finally block:
+ // 1) Normal completion of try block of a try-finally or try-catch-finally
+ // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
+ // 3) Return in try or catch block of a try-finally or try-catch-finally
+ // 4) Exception in try block of a try-finally
+ // 5) Exception in catch block of a try-catch-finally
+ // When analyzing a control flow graph that starts inside a finally block we want to consider all
+ // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
+ // the finally block, we only want to consider the first two (if we're past a finally block then it
+ // must have completed normally). Likewise, when analyzing a control flow graph from return statements
+ // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
+ // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
+ // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
+ // node, the pre-finally label is temporarily switched to the reduced antecedent set.
+ var finallyLabel = createBranchLabel();
+ finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
+ currentFlow = finallyLabel;
+ bind(node.finallyBlock);
+ if (currentFlow.flags & 1 /* Unreachable */) {
+ // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
+ currentFlow = unreachableFlow;
+ }
+ else {
+ // If we have an IIFE return target and return statements in the try or catch blocks, add a control
+ // flow that goes back through the finally block and back through only the return statements.
+ if (currentReturnTarget && returnLabel.antecedents) {
+ addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
}
- else {
- var table = parent ? parent.exports :
- file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
- return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
+ // If we have an outer exception target (i.e. a containing try-finally or try-catch-finally), add a
+ // control flow that goes back through the finally blok and back through each possible exception source.
+ if (currentExceptionTarget && exceptionLabel.antecedents) {
+ addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedents, currentFlow));
}
- });
+ // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
+ // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
+ // result in an unreachable current control flow.
+ currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
+ }
}
- if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
- addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
+ else {
+ currentFlow = finishFlowLabel(normalExitLabel);
}
- return namespaceSymbol;
}
- function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
- if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
- return;
- }
- // Set up the members collection if it doesn't exist already
- var symbolTable = isPrototypeProperty ?
- (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
- (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
- var includes = 0 /* None */;
- var excludes = 0 /* None */;
- // Method-like
- if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
- includes = 8192 /* Method */;
- excludes = 103359 /* MethodExcludes */;
+ function bindSwitchStatement(node) {
+ var postSwitchLabel = createBranchLabel();
+ bind(node.expression);
+ var saveBreakTarget = currentBreakTarget;
+ var savePreSwitchCaseFlow = preSwitchCaseFlow;
+ currentBreakTarget = postSwitchLabel;
+ preSwitchCaseFlow = currentFlow;
+ bind(node.caseBlock);
+ addAntecedent(postSwitchLabel, currentFlow);
+ var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 289 /* DefaultClause */; });
+ // We mark a switch statement as possibly exhaustive if it has no default clause and if all
+ // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
+ // this property in control flow analysis, it's there only for backwards compatibility.
+ node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
+ if (!hasDefault) {
+ addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
}
- // Maybe accessor-like
- else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
- if (ts.some(declaration.arguments[2].properties, function (p) {
- var id = ts.getNameOfDeclaration(p);
- return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
- })) {
- // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
- // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
- includes |= 65536 /* SetAccessor */ | 4 /* Property */;
- excludes |= 78783 /* SetAccessorExcludes */;
+ currentBreakTarget = saveBreakTarget;
+ preSwitchCaseFlow = savePreSwitchCaseFlow;
+ currentFlow = finishFlowLabel(postSwitchLabel);
+ }
+ function bindCaseBlock(node) {
+ var clauses = node.clauses;
+ var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
+ var fallthroughFlow = unreachableFlow;
+ for (var i = 0; i < clauses.length; i++) {
+ var clauseStart = i;
+ while (!clauses[i].statements.length && i + 1 < clauses.length) {
+ bind(clauses[i]);
+ i++;
}
- if (ts.some(declaration.arguments[2].properties, function (p) {
- var id = ts.getNameOfDeclaration(p);
- return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
- })) {
- includes |= 32768 /* GetAccessor */ | 4 /* Property */;
- excludes |= 46015 /* GetAccessorExcludes */;
+ var preCaseLabel = createBranchLabel();
+ addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
+ addAntecedent(preCaseLabel, fallthroughFlow);
+ currentFlow = finishFlowLabel(preCaseLabel);
+ var clause = clauses[i];
+ bind(clause);
+ fallthroughFlow = currentFlow;
+ if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
+ clause.fallthroughFlowNode = currentFlow;
}
}
- if (includes === 0 /* None */) {
- includes = 4 /* Property */;
- excludes = 0 /* PropertyExcludes */;
- }
- declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
}
- function isTopLevelNamespaceAssignment(propertyAccess) {
- return ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
- : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
+ function bindCaseClause(node) {
+ var saveCurrentFlow = currentFlow;
+ currentFlow = preSwitchCaseFlow;
+ bind(node.expression);
+ currentFlow = saveCurrentFlow;
+ bindEach(node.statements);
}
- function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
- var namespaceSymbol = lookupSymbolForPropertyAccess(name);
- var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
- namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
- bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
+ function bindExpressionStatement(node) {
+ bind(node.expression);
+ maybeBindExpressionFlowIfCall(node.expression);
}
- /**
- * Javascript expando values are:
- * - Functions
- * - classes
- * - namespaces
- * - variables initialized with function expressions
- * - with class expressions
- * - with empty object literals
- * - with non-empty object literals if assigned to the prototype property
- */
- function isExpandoSymbol(symbol) {
- if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
- return true;
+ function maybeBindExpressionFlowIfCall(node) {
+ // A top level or LHS of comma expression call expression with a dotted function name and at least one argument
+ // is potentially an assertion and is therefore included in the control flow.
+ if (node.kind === 207 /* CallExpression */) {
+ var call = node;
+ if (call.expression.kind !== 106 /* SuperKeyword */ && ts.isDottedName(call.expression)) {
+ currentFlow = createFlowCall(currentFlow, call);
+ }
}
- var node = symbol.valueDeclaration;
- if (node && ts.isCallExpression(node)) {
- return !!ts.getAssignedExpandoInitializer(node);
+ }
+ function bindLabeledStatement(node) {
+ var postStatementLabel = createBranchLabel();
+ activeLabelList = {
+ next: activeLabelList,
+ name: node.label.escapedText,
+ breakTarget: postStatementLabel,
+ continueTarget: undefined,
+ referenced: false
+ };
+ bind(node.label);
+ bind(node.statement);
+ if (!activeLabelList.referenced && !options.allowUnusedLabels) {
+ errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
}
- var init = !node ? undefined :
- ts.isVariableDeclaration(node) ? node.initializer :
- ts.isBinaryExpression(node) ? node.right :
- ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
- undefined;
- init = init && ts.getRightMostAssignedExpression(init);
- if (init) {
- var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
- return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
+ activeLabelList = activeLabelList.next;
+ addAntecedent(postStatementLabel, currentFlow);
+ currentFlow = finishFlowLabel(postStatementLabel);
+ }
+ function bindDestructuringTargetFlow(node) {
+ if (node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 63 /* EqualsToken */) {
+ bindAssignmentTargetFlow(node.left);
+ }
+ else {
+ bindAssignmentTargetFlow(node);
}
- return false;
}
- function getParentOfBinaryExpression(expr) {
- while (ts.isBinaryExpression(expr.parent)) {
- expr = expr.parent;
+ function bindAssignmentTargetFlow(node) {
+ if (isNarrowableReference(node)) {
+ currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
+ }
+ else if (node.kind === 203 /* ArrayLiteralExpression */) {
+ for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
+ var e = _a[_i];
+ if (e.kind === 224 /* SpreadElement */) {
+ bindAssignmentTargetFlow(e.expression);
+ }
+ else {
+ bindDestructuringTargetFlow(e);
+ }
+ }
+ }
+ else if (node.kind === 204 /* ObjectLiteralExpression */) {
+ for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
+ var p = _c[_b];
+ if (p.kind === 294 /* PropertyAssignment */) {
+ bindDestructuringTargetFlow(p.initializer);
+ }
+ else if (p.kind === 295 /* ShorthandPropertyAssignment */) {
+ bindAssignmentTargetFlow(p.name);
+ }
+ else if (p.kind === 296 /* SpreadAssignment */) {
+ bindAssignmentTargetFlow(p.expression);
+ }
+ }
}
- return expr.parent;
}
- function lookupSymbolForPropertyAccess(node, lookupContainer) {
- if (lookupContainer === void 0) { lookupContainer = container; }
- if (ts.isIdentifier(node)) {
- return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
+ function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
+ var preRightLabel = createBranchLabel();
+ if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 76 /* AmpersandAmpersandEqualsToken */) {
+ bindCondition(node.left, preRightLabel, falseTarget);
}
else {
- var symbol = lookupSymbolForPropertyAccess(node.expression);
- return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
+ bindCondition(node.left, trueTarget, preRightLabel);
}
- }
- function forEachIdentifierInEntityName(e, parent, action) {
- if (isExportsOrModuleExportsOrAlias(file, e)) {
- return file.symbol;
+ currentFlow = finishFlowLabel(preRightLabel);
+ bind(node.operatorToken);
+ if (ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
+ doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
+ bindAssignmentTargetFlow(node.left);
+ addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
+ addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
}
- else if (ts.isIdentifier(e)) {
- return action(e, lookupSymbolForPropertyAccess(e), parent);
+ else {
+ bindCondition(node.right, trueTarget, falseTarget);
+ }
+ }
+ function bindPrefixUnaryExpressionFlow(node) {
+ if (node.operator === 53 /* ExclamationToken */) {
+ var saveTrueTarget = currentTrueTarget;
+ currentTrueTarget = currentFalseTarget;
+ currentFalseTarget = saveTrueTarget;
+ bindEachChild(node);
+ currentFalseTarget = currentTrueTarget;
+ currentTrueTarget = saveTrueTarget;
}
else {
- var s = forEachIdentifierInEntityName(e.expression, parent, action);
- var name = ts.getNameOrArgument(e);
- // unreachable
- if (ts.isPrivateIdentifier(name)) {
- ts.Debug.fail("unexpected PrivateIdentifier");
+ bindEachChild(node);
+ if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
+ bindAssignmentTargetFlow(node.operand);
}
- return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
}
}
- function bindCallExpression(node) {
- // We're only inspecting call expressions to detect CommonJS modules, so we can skip
- // this check if we've already seen the module indicator
- if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
- setCommonJsModuleIndicator(node);
+ function bindPostfixUnaryExpressionFlow(node) {
+ bindEachChild(node);
+ if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
+ bindAssignmentTargetFlow(node.operand);
}
}
- function bindClassLikeDeclaration(node) {
- if (node.kind === 245 /* ClassDeclaration */) {
- bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
+ function bindDestructuringAssignmentFlow(node) {
+ if (inAssignmentPattern) {
+ inAssignmentPattern = false;
+ bind(node.operatorToken);
+ bind(node.right);
+ inAssignmentPattern = true;
+ bind(node.left);
}
else {
- var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
- bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
- // Add name of class expression into the map for semantic classifier
- if (node.name) {
- classifiableNames.set(node.name.escapedText, true);
+ inAssignmentPattern = true;
+ bind(node.left);
+ inAssignmentPattern = false;
+ bind(node.operatorToken);
+ bind(node.right);
+ }
+ bindAssignmentTargetFlow(node.left);
+ }
+ function createBindBinaryExpressionFlow() {
+ return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined);
+ function onEnter(node, state) {
+ if (state) {
+ state.stackIndex++;
+ // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to
+ // `bindBinaryExpressionFlow` will already have done this work.
+ ts.setParent(node, parent);
+ var saveInStrictMode = inStrictMode;
+ bindWorker(node);
+ var saveParent = parent;
+ parent = node;
+ state.skip = false;
+ state.inStrictModeStack[state.stackIndex] = saveInStrictMode;
+ state.parentStack[state.stackIndex] = saveParent;
+ }
+ else {
+ state = {
+ stackIndex: 0,
+ skip: false,
+ inStrictModeStack: [undefined],
+ parentStack: [undefined]
+ };
+ }
+ // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
+ // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
+ // For now, though, since the common cases are chained `+`, leaving it recursive is fine
+ var operator = node.operatorToken.kind;
+ if (operator === 55 /* AmpersandAmpersandToken */ ||
+ operator === 56 /* BarBarToken */ ||
+ operator === 60 /* QuestionQuestionToken */ ||
+ ts.isLogicalOrCoalescingAssignmentOperator(operator)) {
+ if (isTopLevelLogicalExpression(node)) {
+ var postExpressionLabel = createBranchLabel();
+ bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
+ currentFlow = finishFlowLabel(postExpressionLabel);
+ }
+ else {
+ bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
+ }
+ state.skip = true;
}
+ return state;
}
- var symbol = node.symbol;
- // TypeScript 1.0 spec (April 2014): 8.4
- // Every class automatically contains a static property member named 'prototype', the
- // type of which is an instantiation of the class type with type Any supplied as a type
- // argument for each type parameter. It is an error to explicitly declare a static
- // property member with the name 'prototype'.
- //
- // Note: we check for this here because this class may be merging into a module. The
- // module might have an exported variable called 'prototype'. We can't allow that as
- // that would clash with the built-in 'prototype' for the class.
- var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
- var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
- if (symbolExport) {
- if (node.name) {
- node.name.parent = node;
+ function onLeft(left, state, _node) {
+ if (!state.skip) {
+ return maybeBind(left);
}
- file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
}
- symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
- prototypeSymbol.parent = symbol;
- }
- function bindEnumDeclaration(node) {
- return ts.isEnumConst(node)
- ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
- : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
- }
- function bindVariableDeclarationOrBindingElement(node) {
- if (inStrictMode) {
- checkStrictModeEvalOrArguments(node, node.name);
+ function onOperator(operatorToken, state, node) {
+ if (!state.skip) {
+ if (operatorToken.kind === 27 /* CommaToken */) {
+ maybeBindExpressionFlowIfCall(node.left);
+ }
+ bind(operatorToken);
+ }
}
- if (!ts.isBindingPattern(node.name)) {
- if (ts.isBlockOrCatchScoped(node)) {
- bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
+ function onRight(right, state, _node) {
+ if (!state.skip) {
+ return maybeBind(right);
}
- else if (ts.isParameterDeclaration(node)) {
- // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
- // because its parent chain has already been set up, since parents are set before descending into children.
- //
- // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
- // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
- // For example:
- // function foo([a,a]) {} // Duplicate Identifier error
- // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
- // // which correctly set excluded symbols
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
+ }
+ function onExit(node, state) {
+ if (!state.skip) {
+ var operator = node.operatorToken.kind;
+ if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
+ bindAssignmentTargetFlow(node.left);
+ if (operator === 63 /* EqualsToken */ && node.left.kind === 206 /* ElementAccessExpression */) {
+ var elementAccess = node.left;
+ if (isNarrowableOperand(elementAccess.expression)) {
+ currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
+ }
+ }
+ }
}
- else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
+ var savedInStrictMode = state.inStrictModeStack[state.stackIndex];
+ var savedParent = state.parentStack[state.stackIndex];
+ if (savedInStrictMode !== undefined) {
+ inStrictMode = savedInStrictMode;
+ }
+ if (savedParent !== undefined) {
+ parent = savedParent;
+ }
+ state.skip = false;
+ state.stackIndex--;
+ }
+ function maybeBind(node) {
+ if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) {
+ return node;
+ }
+ bind(node);
+ }
+ }
+ function bindDeleteExpressionFlow(node) {
+ bindEachChild(node);
+ if (node.expression.kind === 205 /* PropertyAccessExpression */) {
+ bindAssignmentTargetFlow(node.expression);
+ }
+ }
+ function bindConditionalExpressionFlow(node) {
+ var trueLabel = createBranchLabel();
+ var falseLabel = createBranchLabel();
+ var postExpressionLabel = createBranchLabel();
+ bindCondition(node.condition, trueLabel, falseLabel);
+ currentFlow = finishFlowLabel(trueLabel);
+ bind(node.questionToken);
+ bind(node.whenTrue);
+ addAntecedent(postExpressionLabel, currentFlow);
+ currentFlow = finishFlowLabel(falseLabel);
+ bind(node.colonToken);
+ bind(node.whenFalse);
+ addAntecedent(postExpressionLabel, currentFlow);
+ currentFlow = finishFlowLabel(postExpressionLabel);
+ }
+ function bindInitializedVariableFlow(node) {
+ var name = !ts.isOmittedExpression(node) ? node.name : undefined;
+ if (ts.isBindingPattern(name)) {
+ for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
+ var child = _a[_i];
+ bindInitializedVariableFlow(child);
}
}
- }
- function bindParameter(node) {
- if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
- return;
+ else {
+ currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
}
- if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
- // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
- // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
- checkStrictModeEvalOrArguments(node, node.name);
+ }
+ function bindVariableDeclarationFlow(node) {
+ bindEachChild(node);
+ if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
+ bindInitializedVariableFlow(node);
}
+ }
+ function bindBindingElementFlow(node) {
if (ts.isBindingPattern(node.name)) {
- bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
+ // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per:
+ // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization
+ // - `BindingElement: BindingPattern Initializer?`
+ // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization
+ // - `BindingElement: BindingPattern Initializer?`
+ bindEach(node.decorators);
+ bindEach(node.modifiers);
+ bind(node.dotDotDotToken);
+ bind(node.propertyName);
+ bind(node.initializer);
+ bind(node.name);
}
else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
- }
- // If this is a property-parameter, then also declare the property symbol into the
- // containing class.
- if (ts.isParameterPropertyDeclaration(node, node.parent)) {
- var classDeclaration = node.parent.parent;
- declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
+ bindEachChild(node);
}
}
- function bindFunctionDeclaration(node) {
- if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
- if (ts.isAsyncFunction(node)) {
- emitFlags |= 2048 /* HasAsyncFunctions */;
- }
+ function bindJSDocTypeAlias(node) {
+ bind(node.tagName);
+ if (node.kind !== 337 /* JSDocEnumTag */ && node.fullName) {
+ // don't bind the type name yet; that's delayed until delayedBindJSDocTypedefTag
+ ts.setParent(node.fullName, node);
+ ts.setParentRecursive(node.fullName, /*incremental*/ false);
}
- checkStrictModeFunctionName(node);
- if (inStrictMode) {
- checkStrictModeFunctionDeclaration(node);
- bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
+ if (typeof node.comment !== "string") {
+ bindEach(node.comment);
}
- else {
- declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
+ }
+ function bindJSDocClassTag(node) {
+ bindEachChild(node);
+ var host = ts.getHostSignatureFromJSDoc(node);
+ if (host && host.kind !== 168 /* MethodDeclaration */) {
+ addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
}
}
- function bindFunctionExpression(node) {
- if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
- if (ts.isAsyncFunction(node)) {
- emitFlags |= 2048 /* HasAsyncFunctions */;
- }
+ function bindOptionalExpression(node, trueTarget, falseTarget) {
+ doWithConditionalBranches(bind, node, trueTarget, falseTarget);
+ if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
+ addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
+ addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
}
- if (currentFlow) {
- node.flowNode = currentFlow;
+ }
+ function bindOptionalChainRest(node) {
+ switch (node.kind) {
+ case 205 /* PropertyAccessExpression */:
+ bind(node.questionDotToken);
+ bind(node.name);
+ break;
+ case 206 /* ElementAccessExpression */:
+ bind(node.questionDotToken);
+ bind(node.argumentExpression);
+ break;
+ case 207 /* CallExpression */:
+ bind(node.questionDotToken);
+ bindEach(node.typeArguments);
+ bindEach(node.arguments);
+ break;
}
- checkStrictModeFunctionName(node);
- var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
- return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
}
- function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
- if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
- emitFlags |= 2048 /* HasAsyncFunctions */;
+ function bindOptionalChain(node, trueTarget, falseTarget) {
+ // For an optional chain, we emulate the behavior of a logical expression:
+ //
+ // a?.b -> a && a.b
+ // a?.b.c -> a && a.b.c
+ // a?.b?.c -> a && a.b && a.b.c
+ // a?.[x = 1] -> a && a[x = 1]
+ //
+ // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
+ // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
+ // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
+ // chain node. We then treat the entire node as the right side of the expression.
+ var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
+ bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
+ if (preChainLabel) {
+ currentFlow = finishFlowLabel(preChainLabel);
}
- if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
- node.flowNode = currentFlow;
+ doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
+ if (ts.isOutermostOptionalChain(node)) {
+ addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
+ addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
}
- return ts.hasDynamicName(node)
- ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
- : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
- }
- function getInferTypeContainer(node) {
- var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
- return extendsType && extendsType.parent;
}
- function bindTypeParameter(node) {
- if (ts.isJSDocTemplateTag(node.parent)) {
- var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
- if (container_1) {
- if (!container_1.locals) {
- container_1.locals = ts.createSymbolTable();
- }
- declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
- }
- }
- else if (node.parent.kind === 181 /* InferType */) {
- var container_2 = getInferTypeContainer(node.parent);
- if (container_2) {
- if (!container_2.locals) {
- container_2.locals = ts.createSymbolTable();
- }
- declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
- }
- else {
- bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
- }
+ function bindOptionalChainFlow(node) {
+ if (isTopLevelLogicalExpression(node)) {
+ var postExpressionLabel = createBranchLabel();
+ bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
+ currentFlow = finishFlowLabel(postExpressionLabel);
}
else {
- declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
+ bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
}
}
- // reachability checks
- function shouldReportErrorOnModuleDeclaration(node) {
- var instanceState = getModuleInstanceState(node);
- return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
- }
- function checkUnreachable(node) {
- if (!(currentFlow.flags & 1 /* Unreachable */)) {
- return false;
+ function bindNonNullExpressionFlow(node) {
+ if (ts.isOptionalChain(node)) {
+ bindOptionalChainFlow(node);
}
- if (currentFlow === unreachableFlow) {
- var reportError =
- // report error on all statements except empty ones
- (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
- // report error on class declarations
- node.kind === 245 /* ClassDeclaration */ ||
- // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
- (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
- if (reportError) {
- currentFlow = reportedUnreachableFlow;
- if (!options.allowUnreachableCode) {
- // unreachable code is reported if
- // - user has explicitly asked about it AND
- // - statement is in not ambient context (statements in ambient context is already an error
- // so we should not report extras) AND
- // - node is not variable statement OR
- // - node is block scoped variable statement OR
- // - node is not block scoped variable statement and at least one variable declaration has initializer
- // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
- // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
- var isError_1 = ts.unreachableCodeIsError(options) &&
- !(node.flags & 8388608 /* Ambient */) &&
- (!ts.isVariableStatement(node) ||
- !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
- node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
- eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
- }
- }
+ else {
+ bindEachChild(node);
}
- return true;
- }
- }
- function eachUnreachableRange(node, cb) {
- if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
- var statements = node.parent.statements;
- var slice_1 = ts.sliceAfter(statements, node);
- ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
- }
- else {
- cb(node, node);
}
- }
- // As opposed to a pure declaration like an `interface`
- function isExecutableStatement(s) {
- // Don't remove statements that can validly be used before they appear.
- return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
- // `var x;` may declare a variable used above
- !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
- }
- function isPurelyTypeDeclaration(s) {
- switch (s.kind) {
- case 246 /* InterfaceDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- return true;
- case 249 /* ModuleDeclaration */:
- return getModuleInstanceState(s) !== 1 /* Instantiated */;
- case 248 /* EnumDeclaration */:
- return ts.hasModifier(s, 2048 /* Const */);
- default:
- return false;
+ function bindAccessExpressionFlow(node) {
+ if (ts.isOptionalChain(node)) {
+ bindOptionalChainFlow(node);
+ }
+ else {
+ bindEachChild(node);
+ }
}
- }
- function isExportsOrModuleExportsOrAlias(sourceFile, node) {
- var i = 0;
- var q = [node];
- while (q.length && i < 100) {
- i++;
- node = q.shift();
- if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
- return true;
+ function bindCallExpressionFlow(node) {
+ if (ts.isOptionalChain(node)) {
+ bindOptionalChainFlow(node);
}
- else if (ts.isIdentifier(node)) {
- var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
- if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
- var init = symbol.valueDeclaration.initializer;
- q.push(init);
- if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
- q.push(init.left);
- q.push(init.right);
+ else {
+ // If the target of the call expression is a function expression or arrow function we have
+ // an immediately invoked function expression (IIFE). Initialize the flowNode property to
+ // the current control flow (which includes evaluation of the IIFE arguments).
+ var expr = ts.skipParentheses(node.expression);
+ if (expr.kind === 212 /* FunctionExpression */ || expr.kind === 213 /* ArrowFunction */) {
+ bindEach(node.typeArguments);
+ bindEach(node.arguments);
+ bind(node.expression);
+ }
+ else {
+ bindEachChild(node);
+ if (node.expression.kind === 106 /* SuperKeyword */) {
+ currentFlow = createFlowCall(currentFlow, node);
}
}
}
+ if (node.expression.kind === 205 /* PropertyAccessExpression */) {
+ var propertyAccess = node.expression;
+ if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
+ currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
+ }
+ }
}
- return false;
- }
- ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
- function lookupSymbolForNameWorker(container, name) {
- var local = container.locals && container.locals.get(name);
- if (local) {
- return local.exportSymbol || local;
- }
- if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
- return container.jsGlobalAugmentations.get(name);
- }
- return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
- }
- /**
- * Computes the transform flags for a node, given the transform flags of its subtree
- *
- * @param node The node to analyze
- * @param subtreeFlags Transform flags computed for this node's subtree
- */
- function computeTransformFlagsForNode(node, subtreeFlags) {
- var kind = node.kind;
- switch (kind) {
- case 196 /* CallExpression */:
- return computeCallExpression(node, subtreeFlags);
- case 197 /* NewExpression */:
- return computeNewExpression(node, subtreeFlags);
- case 249 /* ModuleDeclaration */:
- return computeModuleDeclaration(node, subtreeFlags);
- case 200 /* ParenthesizedExpression */:
- return computeParenthesizedExpression(node, subtreeFlags);
- case 209 /* BinaryExpression */:
- return computeBinaryExpression(node, subtreeFlags);
- case 226 /* ExpressionStatement */:
- return computeExpressionStatement(node, subtreeFlags);
- case 156 /* Parameter */:
- return computeParameter(node, subtreeFlags);
- case 202 /* ArrowFunction */:
- return computeArrowFunction(node, subtreeFlags);
- case 201 /* FunctionExpression */:
- return computeFunctionExpression(node, subtreeFlags);
- case 244 /* FunctionDeclaration */:
- return computeFunctionDeclaration(node, subtreeFlags);
- case 242 /* VariableDeclaration */:
- return computeVariableDeclaration(node, subtreeFlags);
- case 243 /* VariableDeclarationList */:
- return computeVariableDeclarationList(node, subtreeFlags);
- case 225 /* VariableStatement */:
- return computeVariableStatement(node, subtreeFlags);
- case 238 /* LabeledStatement */:
- return computeLabeledStatement(node, subtreeFlags);
- case 245 /* ClassDeclaration */:
- return computeClassDeclaration(node, subtreeFlags);
- case 214 /* ClassExpression */:
- return computeClassExpression(node, subtreeFlags);
- case 279 /* HeritageClause */:
- return computeHeritageClause(node, subtreeFlags);
- case 280 /* CatchClause */:
- return computeCatchClause(node, subtreeFlags);
- case 216 /* ExpressionWithTypeArguments */:
- return computeExpressionWithTypeArguments(node, subtreeFlags);
- case 162 /* Constructor */:
- return computeConstructor(node, subtreeFlags);
- case 159 /* PropertyDeclaration */:
- return computePropertyDeclaration(node, subtreeFlags);
- case 161 /* MethodDeclaration */:
- return computeMethod(node, subtreeFlags);
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- return computeAccessor(node, subtreeFlags);
- case 253 /* ImportEqualsDeclaration */:
- return computeImportEquals(node, subtreeFlags);
- case 194 /* PropertyAccessExpression */:
- return computePropertyAccess(node, subtreeFlags);
- case 195 /* ElementAccessExpression */:
- return computeElementAccess(node, subtreeFlags);
- case 267 /* JsxSelfClosingElement */:
- case 268 /* JsxOpeningElement */:
- return computeJsxOpeningLikeElement(node, subtreeFlags);
- default:
- return computeOther(node, kind, subtreeFlags);
+ function getContainerFlags(node) {
+ switch (node.kind) {
+ case 225 /* ClassExpression */:
+ case 256 /* ClassDeclaration */:
+ case 259 /* EnumDeclaration */:
+ case 204 /* ObjectLiteralExpression */:
+ case 181 /* TypeLiteral */:
+ case 320 /* JSDocTypeLiteral */:
+ case 285 /* JsxAttributes */:
+ return 1 /* IsContainer */;
+ case 257 /* InterfaceDeclaration */:
+ return 1 /* IsContainer */ | 64 /* IsInterface */;
+ case 260 /* ModuleDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ case 194 /* MappedType */:
+ return 1 /* IsContainer */ | 32 /* HasLocals */;
+ case 303 /* SourceFile */:
+ return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 168 /* MethodDeclaration */:
+ if (ts.isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
+ return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */;
+ }
+ // falls through
+ case 170 /* Constructor */:
+ case 255 /* FunctionDeclaration */:
+ case 167 /* MethodSignature */:
+ case 173 /* CallSignature */:
+ case 321 /* JSDocSignature */:
+ case 315 /* JSDocFunctionType */:
+ case 178 /* FunctionType */:
+ case 174 /* ConstructSignature */:
+ case 175 /* IndexSignature */:
+ case 179 /* ConstructorType */:
+ case 169 /* ClassStaticBlockDeclaration */:
+ return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
+ case 261 /* ModuleBlock */:
+ return 4 /* IsControlFlowContainer */;
+ case 166 /* PropertyDeclaration */:
+ return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
+ case 291 /* CatchClause */:
+ case 241 /* ForStatement */:
+ case 242 /* ForInStatement */:
+ case 243 /* ForOfStatement */:
+ case 262 /* CaseBlock */:
+ return 2 /* IsBlockScopedContainer */;
+ case 234 /* Block */:
+ // do not treat blocks directly inside a function as a block-scoped-container.
+ // Locals that reside in this block should go to the function locals. Otherwise 'x'
+ // would not appear to be a redeclaration of a block scoped local in the following
+ // example:
+ //
+ // function foo() {
+ // var x;
+ // let x;
+ // }
+ //
+ // If we placed 'var x' into the function locals and 'let x' into the locals of
+ // the block, then there would be no collision.
+ //
+ // By not creating a new block-scoped-container here, we ensure that both 'var x'
+ // and 'let x' go into the Function-container's locals, and we do get a collision
+ // conflict.
+ return ts.isFunctionLike(node.parent) || ts.isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
+ }
+ return 0 /* None */;
}
- }
- ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
- function computeCallExpression(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- var callee = ts.skipOuterExpressions(node.expression);
- var expression = node.expression;
- if (node.flags & 32 /* OptionalChain */) {
- transformFlags |= 8 /* ContainsES2020 */;
+ function addToContainerChain(next) {
+ if (lastContainer) {
+ lastContainer.nextContainer = next;
+ }
+ lastContainer = next;
}
- if (node.typeArguments) {
- transformFlags |= 1 /* AssertTypeScript */;
+ function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
+ switch (container.kind) {
+ // Modules, source files, and classes need specialized handling for how their
+ // members are declared (for example, a member of a class will go into a specific
+ // symbol table depending on if it is static or not). We defer to specialized
+ // handlers to take care of declaring these child members.
+ case 260 /* ModuleDeclaration */:
+ return declareModuleMember(node, symbolFlags, symbolExcludes);
+ case 303 /* SourceFile */:
+ return declareSourceFileMember(node, symbolFlags, symbolExcludes);
+ case 225 /* ClassExpression */:
+ case 256 /* ClassDeclaration */:
+ return declareClassMember(node, symbolFlags, symbolExcludes);
+ case 259 /* EnumDeclaration */:
+ return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
+ case 181 /* TypeLiteral */:
+ case 320 /* JSDocTypeLiteral */:
+ case 204 /* ObjectLiteralExpression */:
+ case 257 /* InterfaceDeclaration */:
+ case 285 /* JsxAttributes */:
+ // Interface/Object-types always have their children added to the 'members' of
+ // their container. They are only accessible through an instance of their
+ // container, and are never in scope otherwise (even inside the body of the
+ // object / type / interface declaring them). An exception is type parameters,
+ // which are in scope without qualification (similar to 'locals').
+ return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
+ case 178 /* FunctionType */:
+ case 179 /* ConstructorType */:
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 321 /* JSDocSignature */:
+ case 175 /* IndexSignature */:
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ case 315 /* JSDocFunctionType */:
+ case 343 /* JSDocTypedefTag */:
+ case 336 /* JSDocCallbackTag */:
+ case 169 /* ClassStaticBlockDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ case 194 /* MappedType */:
+ // All the children of these container types are never visible through another
+ // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
+ // they're only accessed 'lexically' (i.e. from code that exists underneath
+ // their container in the tree). To accomplish this, we simply add their declared
+ // symbol to the 'locals' of the container. These symbols can then be found as
+ // the type checker walks up the containers, checking them for matching names.
+ return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
+ }
}
- if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
- // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
- // node.
- transformFlags |= 256 /* AssertES2015 */;
- if (ts.isSuperProperty(callee)) {
- transformFlags |= 4096 /* ContainsLexicalThis */;
- }
- }
- if (expression.kind === 96 /* ImportKeyword */) {
- transformFlags |= 2097152 /* ContainsDynamicImport */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
- }
- function computeNewExpression(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- if (node.typeArguments) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadElementExpression then it is an ES6
- // node.
- transformFlags |= 256 /* AssertES2015 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
- }
- function computeJsxOpeningLikeElement(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 2 /* AssertJsx */;
- if (node.typeArguments) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeBinaryExpression(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- var operatorTokenKind = node.operatorToken.kind;
- var leftKind = node.left.kind;
- if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
- transformFlags |= 8 /* AssertES2020 */;
- }
- else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
- // Destructuring object assignments with are ES2015 syntax
- // and possibly ES2018 if they contain rest
- transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
- }
- else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
- // Destructuring assignments are ES2015 syntax.
- transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
- }
- else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
- || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
- // Exponentiation is ES2016 syntax.
- transformFlags |= 128 /* AssertES2016 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeParameter(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- var name = node.name;
- var initializer = node.initializer;
- var dotDotDotToken = node.dotDotDotToken;
- // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
- // syntax.
- if (node.questionToken
- || node.type
- || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
- || ts.isThisIdentifier(name)) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // If a parameter has an accessibility modifier, then it is TypeScript syntax.
- if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
- }
- // parameters with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
- // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* ParameterExcludes */;
- }
- function computeParenthesizedExpression(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionKind = expression.kind;
- // If the node is synthesized, it means the emitter put the parentheses there,
- // not the user. If we didn't want them, the emitter would not have put them
- // there.
- if (expressionKind === 217 /* AsExpression */
- || expressionKind === 199 /* TypeAssertionExpression */) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* OuterExpressionExcludes */;
- }
- function computeClassDeclaration(node, subtreeFlags) {
- var transformFlags;
- if (ts.hasModifier(node, 2 /* Ambient */)) {
- // An ambient declaration is TypeScript syntax.
- transformFlags = 1 /* AssertTypeScript */;
+ function declareClassMember(node, symbolFlags, symbolExcludes) {
+ return ts.isStatic(node)
+ ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
+ : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
}
- else {
- // A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 256 /* AssertES2015 */;
- // A class with a parameter property assignment or decorator is TypeScript syntax.
- // An exported declaration may be TypeScript syntax, but is handled by the visitor
- // for a namespace declaration.
- if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
- || node.typeParameters) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536905728 /* ClassExcludes */;
- }
- function computeClassExpression(node, subtreeFlags) {
- // A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
- // A class with a parameter property assignment or decorator is TypeScript syntax.
- if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
- || node.typeParameters) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536905728 /* ClassExcludes */;
- }
- function computeHeritageClause(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- switch (node.token) {
- case 90 /* ExtendsKeyword */:
- // An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 256 /* AssertES2015 */;
- break;
- case 113 /* ImplementsKeyword */:
- // An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 1 /* AssertTypeScript */;
- break;
- default:
- ts.Debug.fail("Unexpected token for heritage clause");
- break;
+ function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
+ return ts.isExternalModule(file)
+ ? declareModuleMember(node, symbolFlags, symbolExcludes)
+ : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeCatchClause(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- if (!node.variableDeclaration) {
- transformFlags |= 16 /* AssertES2019 */;
- }
- else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536887296 /* CatchClauseExcludes */;
- }
- function computeExpressionWithTypeArguments(node, subtreeFlags) {
- // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
- // extends clause of a class.
- var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
- // If an ExpressionWithTypeArguments contains type arguments, then it
- // is TypeScript syntax.
- if (node.typeArguments) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeConstructor(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- // TypeScript-specific modifiers and overloads are TypeScript syntax
- if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
- || !node.body) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // function declarations with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~538923008 /* ConstructorExcludes */;
- }
- function computeMethod(node, subtreeFlags) {
- // A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
- // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
- // overloads are TypeScript syntax.
- if (node.decorators
- || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
- || node.typeParameters
- || node.type
- || !node.body
- || node.questionToken) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // function declarations with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- // An async method declaration is ES2017 syntax.
- if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
- }
- if (node.asteriskToken) {
- transformFlags |= 512 /* AssertGenerator */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
- }
- function computeAccessor(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
- // TypeScript syntax.
- if (node.decorators
- || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
- || node.type
- || !node.body) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // function declarations with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
- }
- function computePropertyDeclaration(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
- // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
- if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // Hoisted variables related to class properties should live within the TypeScript class wrapper.
- if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
- transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
- }
- function computeFunctionDeclaration(node, subtreeFlags) {
- var transformFlags;
- var modifierFlags = ts.getModifierFlags(node);
- var body = node.body;
- if (!body || (modifierFlags & 2 /* Ambient */)) {
- // An ambient declaration is TypeScript syntax.
- // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 1 /* AssertTypeScript */;
+ function hasExportDeclarations(node) {
+ var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
+ return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
}
- else {
- transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
- // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
- // syntax.
- if (modifierFlags & 2270 /* TypeScriptModifier */
- || node.typeParameters
- || node.type) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // An async function declaration is ES2017 syntax.
- if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
- }
- // function declarations with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- // If a FunctionDeclaration is generator function and is the body of a
- // transformed async function, then this node can be transformed to a
- // down-level generator.
- // Currently we do not support transforming any other generator functions
- // down level.
- if (node.asteriskToken) {
- transformFlags |= 512 /* AssertGenerator */;
- }
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~538925056 /* FunctionExcludes */;
- }
- function computeFunctionExpression(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
- // syntax.
- if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
- || node.typeParameters
- || node.type) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // An async function expression is ES2017 syntax.
- if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
- }
- // function expressions with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- // If a FunctionExpression is generator function and is the body of a
- // transformed async function, then this node can be transformed to a
- // down-level generator.
- if (node.asteriskToken) {
- transformFlags |= 512 /* AssertGenerator */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~538925056 /* FunctionExcludes */;
- }
- function computeArrowFunction(node, subtreeFlags) {
- // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
- // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
- // syntax.
- if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
- || node.typeParameters
- || node.type) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- // An async arrow function is ES2017 syntax.
- if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 64 /* AssertES2017 */;
- }
- // arrow functions with object rest destructuring are ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
- }
- function computePropertyAccess(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- if (node.flags & 32 /* OptionalChain */) {
- transformFlags |= 8 /* ContainsES2020 */;
- }
- // If a PropertyAccessExpression starts with a super keyword, then it is
- // ES6 syntax, and requires a lexical `this` binding.
- if (node.expression.kind === 102 /* SuperKeyword */) {
- // super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ES2018.
- transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* PropertyAccessExcludes */;
- }
- function computeElementAccess(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- if (node.flags & 32 /* OptionalChain */) {
- transformFlags |= 8 /* ContainsES2020 */;
- }
- // If an ElementAccessExpression starts with a super keyword, then it is
- // ES6 syntax, and requires a lexical `this` binding.
- if (node.expression.kind === 102 /* SuperKeyword */) {
- // super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ES2018.
- transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* PropertyAccessExcludes */;
- }
- function computeVariableDeclaration(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
- // A VariableDeclaration containing ObjectRest is ES2018 syntax
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- // Type annotations are TypeScript syntax.
- if (node.type || node.exclamationToken) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeVariableStatement(node, subtreeFlags) {
- var transformFlags;
- var declarationListTransformFlags = node.declarationList.transformFlags;
- // An ambient declaration is TypeScript syntax.
- if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 1 /* AssertTypeScript */;
+ function setExportContextFlag(node) {
+ // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
+ // declarations with export modifiers) is an export context in which declarations are implicitly exported.
+ if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
+ node.flags |= 64 /* ExportContext */;
+ }
+ else {
+ node.flags &= ~64 /* ExportContext */;
+ }
}
- else {
- transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeLabeledStatement(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
- && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeImportEquals(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- // An ImportEqualsDeclaration with a namespace reference is TypeScript.
- if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 1 /* AssertTypeScript */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeExpressionStatement(node, subtreeFlags) {
- var transformFlags = subtreeFlags;
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536870912 /* NodeExcludes */;
- }
- function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 1 /* AssertTypeScript */;
- var modifierFlags = ts.getModifierFlags(node);
- if ((modifierFlags & 2 /* Ambient */) === 0) {
- transformFlags |= subtreeFlags;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~537991168 /* ModuleExcludes */;
- }
- function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
- if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
- }
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
- }
- function computeOther(node, kind, subtreeFlags) {
- // Mark transformations needed for each node
- var transformFlags = subtreeFlags;
- var excludeFlags = 536870912 /* NodeExcludes */;
- switch (kind) {
- case 126 /* AsyncKeyword */:
- // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
- transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
- break;
- case 206 /* AwaitExpression */:
- // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
- transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
- break;
- case 199 /* TypeAssertionExpression */:
- case 217 /* AsExpression */:
- case 326 /* PartiallyEmittedExpression */:
- // These nodes are TypeScript syntax.
- transformFlags |= 1 /* AssertTypeScript */;
- excludeFlags = 536870912 /* OuterExpressionExcludes */;
- break;
- case 119 /* PublicKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 122 /* AbstractKeyword */:
- case 130 /* DeclareKeyword */:
- case 81 /* ConstKeyword */:
- case 248 /* EnumDeclaration */:
- case 284 /* EnumMember */:
- case 218 /* NonNullExpression */:
- case 138 /* ReadonlyKeyword */:
- // These nodes are TypeScript syntax.
- transformFlags |= 1 /* AssertTypeScript */;
- break;
- case 266 /* JsxElement */:
- case 11 /* JsxText */:
- case 269 /* JsxClosingElement */:
- case 270 /* JsxFragment */:
- case 271 /* JsxOpeningFragment */:
- case 272 /* JsxClosingFragment */:
- case 273 /* JsxAttribute */:
- case 274 /* JsxAttributes */:
- case 275 /* JsxSpreadAttribute */:
- case 276 /* JsxExpression */:
- // These nodes are Jsx syntax.
- transformFlags |= 2 /* AssertJsx */;
- break;
- case 14 /* NoSubstitutionTemplateLiteral */:
- case 15 /* TemplateHead */:
- case 16 /* TemplateMiddle */:
- case 17 /* TemplateTail */:
- if (node.templateFlags) {
- transformFlags |= 32 /* AssertES2018 */;
- break;
- }
- // falls through
- case 198 /* TaggedTemplateExpression */:
- if (ts.hasInvalidEscape(node.template)) {
- transformFlags |= 32 /* AssertES2018 */;
- break;
- }
- // falls through
- case 211 /* TemplateExpression */:
- case 282 /* ShorthandPropertyAssignment */:
- case 120 /* StaticKeyword */:
- case 219 /* MetaProperty */:
- // These nodes are ES6 syntax.
- transformFlags |= 256 /* AssertES2015 */;
- break;
- case 10 /* StringLiteral */:
- if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- break;
- case 8 /* NumericLiteral */:
- if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 256 /* AssertES2015 */;
- }
- break;
- case 9 /* BigIntLiteral */:
- transformFlags |= 4 /* AssertESNext */;
- break;
- case 232 /* ForOfStatement */:
- // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
- if (node.awaitModifier) {
- transformFlags |= 32 /* AssertES2018 */;
- }
- transformFlags |= 256 /* AssertES2015 */;
- break;
- case 212 /* YieldExpression */:
- // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
- // generator).
- transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
- break;
- case 125 /* AnyKeyword */:
- case 140 /* NumberKeyword */:
- case 151 /* BigIntKeyword */:
- case 137 /* NeverKeyword */:
- case 141 /* ObjectKeyword */:
- case 143 /* StringKeyword */:
- case 128 /* BooleanKeyword */:
- case 144 /* SymbolKeyword */:
- case 110 /* VoidKeyword */:
- case 155 /* TypeParameter */:
- case 158 /* PropertySignature */:
- case 160 /* MethodSignature */:
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- case 168 /* TypePredicate */:
- case 169 /* TypeReference */:
- case 170 /* FunctionType */:
- case 171 /* ConstructorType */:
- case 172 /* TypeQuery */:
- case 173 /* TypeLiteral */:
- case 174 /* ArrayType */:
- case 175 /* TupleType */:
- case 176 /* OptionalType */:
- case 177 /* RestType */:
- case 178 /* UnionType */:
- case 179 /* IntersectionType */:
- case 180 /* ConditionalType */:
- case 181 /* InferType */:
- case 182 /* ParenthesizedType */:
- case 246 /* InterfaceDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- case 183 /* ThisType */:
- case 184 /* TypeOperator */:
- case 185 /* IndexedAccessType */:
- case 186 /* MappedType */:
- case 187 /* LiteralType */:
- case 252 /* NamespaceExportDeclaration */:
- // Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 1 /* AssertTypeScript */;
- excludeFlags = -2 /* TypeExcludes */;
- break;
- case 154 /* ComputedPropertyName */:
- // Even though computed property names are ES6, we don't treat them as such.
- // This is so that they can flow through PropertyName transforms unaffected.
- // Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 32768 /* ContainsComputedPropertyName */;
- break;
- case 213 /* SpreadElement */:
- transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
- break;
- case 283 /* SpreadAssignment */:
- transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
- break;
- case 102 /* SuperKeyword */:
- // This node is ES6 syntax.
- transformFlags |= 256 /* AssertES2015 */;
- excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
- break;
- case 104 /* ThisKeyword */:
- // Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 4096 /* ContainsLexicalThis */;
- break;
- case 189 /* ObjectBindingPattern */:
- transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
- if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
- transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
+ function bindModuleDeclaration(node) {
+ setExportContextFlag(node);
+ if (ts.isAmbientModule(node)) {
+ if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
+ errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
- excludeFlags = 536879104 /* BindingPatternExcludes */;
- break;
- case 190 /* ArrayBindingPattern */:
- transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
- excludeFlags = 536879104 /* BindingPatternExcludes */;
- break;
- case 191 /* BindingElement */:
- transformFlags |= 256 /* AssertES2015 */;
- if (node.dotDotDotToken) {
- transformFlags |= 8192 /* ContainsRestOrSpread */;
+ if (ts.isModuleAugmentationExternal(node)) {
+ declareModuleSymbol(node);
}
- break;
- case 157 /* Decorator */:
- // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
- break;
- case 193 /* ObjectLiteralExpression */:
- excludeFlags = 536922112 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
- // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
- // is an ES6 node.
- transformFlags |= 256 /* AssertES2015 */;
- }
- if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
- // If an ObjectLiteralExpression contains a spread element, then it
- // is an ES2018 node.
- transformFlags |= 32 /* AssertES2018 */;
+ else {
+ var pattern = void 0;
+ if (node.name.kind === 10 /* StringLiteral */) {
+ var text = node.name.text;
+ pattern = ts.tryParsePattern(text);
+ if (pattern === undefined) {
+ errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
+ }
+ }
+ var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
+ file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && !ts.isString(pattern) ? { pattern: pattern, symbol: symbol } : undefined);
}
- break;
- case 192 /* ArrayLiteralExpression */:
- excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
- break;
- case 228 /* DoStatement */:
- case 229 /* WhileStatement */:
- case 230 /* ForStatement */:
- case 231 /* ForInStatement */:
- // A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
- transformFlags |= 256 /* AssertES2015 */;
+ }
+ else {
+ var state = declareModuleSymbol(node);
+ if (state !== 0 /* NonInstantiated */) {
+ var symbol = node.symbol;
+ // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
+ symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
+ // Current must be `const enum` only
+ && state === 2 /* ConstEnumOnly */
+ // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
+ && symbol.constEnumOnlyModule !== false;
}
- break;
- case 290 /* SourceFile */:
- break;
- case 262 /* NamespaceExport */:
- transformFlags |= 4 /* AssertESNext */;
- break;
- case 235 /* ReturnStatement */:
- // Return statements may require an `await` in ES2018.
- transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
- break;
- case 233 /* ContinueStatement */:
- case 234 /* BreakStatement */:
- transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
- break;
- case 76 /* PrivateIdentifier */:
- transformFlags |= 4194304 /* ContainsClassFields */;
- break;
+ }
}
- node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~excludeFlags;
- }
- function propagatePropertyNameFlags(node, transformFlags) {
- return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
- }
- /**
- * Gets the transform flags to exclude when unioning the transform flags of a subtree.
- *
- * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
- * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
- * than calling this function.
- */
- function getTransformFlagsSubtreeExclusions(kind) {
- if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
- return -2 /* TypeExcludes */;
+ function declareModuleSymbol(node) {
+ var state = getModuleInstanceState(node);
+ var instantiated = state !== 0 /* NonInstantiated */;
+ declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
+ return state;
}
- switch (kind) {
- case 196 /* CallExpression */:
- case 197 /* NewExpression */:
- case 192 /* ArrayLiteralExpression */:
- return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
- case 249 /* ModuleDeclaration */:
- return 537991168 /* ModuleExcludes */;
- case 156 /* Parameter */:
- return 536870912 /* ParameterExcludes */;
- case 202 /* ArrowFunction */:
- return 538920960 /* ArrowFunctionExcludes */;
- case 201 /* FunctionExpression */:
- case 244 /* FunctionDeclaration */:
- return 538925056 /* FunctionExcludes */;
- case 243 /* VariableDeclarationList */:
- return 537018368 /* VariableDeclarationListExcludes */;
- case 245 /* ClassDeclaration */:
- case 214 /* ClassExpression */:
- return 536905728 /* ClassExcludes */;
- case 162 /* Constructor */:
- return 538923008 /* ConstructorExcludes */;
- case 161 /* MethodDeclaration */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- return 538923008 /* MethodOrAccessorExcludes */;
- case 125 /* AnyKeyword */:
- case 140 /* NumberKeyword */:
- case 151 /* BigIntKeyword */:
- case 137 /* NeverKeyword */:
- case 143 /* StringKeyword */:
- case 141 /* ObjectKeyword */:
- case 128 /* BooleanKeyword */:
- case 144 /* SymbolKeyword */:
- case 110 /* VoidKeyword */:
- case 155 /* TypeParameter */:
- case 158 /* PropertySignature */:
- case 160 /* MethodSignature */:
- case 165 /* CallSignature */:
- case 166 /* ConstructSignature */:
- case 167 /* IndexSignature */:
- case 246 /* InterfaceDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- return -2 /* TypeExcludes */;
- case 193 /* ObjectLiteralExpression */:
- return 536922112 /* ObjectLiteralExcludes */;
- case 280 /* CatchClause */:
- return 536887296 /* CatchClauseExcludes */;
- case 189 /* ObjectBindingPattern */:
- case 190 /* ArrayBindingPattern */:
- return 536879104 /* BindingPatternExcludes */;
- case 199 /* TypeAssertionExpression */:
- case 217 /* AsExpression */:
- case 326 /* PartiallyEmittedExpression */:
- case 200 /* ParenthesizedExpression */:
- case 102 /* SuperKeyword */:
- return 536870912 /* OuterExpressionExcludes */;
- case 194 /* PropertyAccessExpression */:
- case 195 /* ElementAccessExpression */:
- return 536870912 /* PropertyAccessExcludes */;
- default:
- return 536870912 /* NodeExcludes */;
+ function bindFunctionOrConstructorType(node) {
+ // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
+ // to the one we would get for: { <...>(...): T }
+ //
+ // We do that by making an anonymous type literal symbol, and then setting the function
+ // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
+ // from an actual type literal symbol you would have gotten had you used the long form.
+ var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
+ addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
+ var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
+ addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
+ typeLiteralSymbol.members = ts.createSymbolTable();
+ typeLiteralSymbol.members.set(symbol.escapedName, symbol);
}
- }
- ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
- /**
- * "Binds" JSDoc nodes in TypeScript code.
- * Since we will never create symbols for JSDoc, we just set parent pointers instead.
- */
- function setParentPointers(parent, child) {
- child.parent = parent;
- ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
- }
-})(ts || (ts = {}));
-/** @internal */
-var ts;
-(function (ts) {
- function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
- return getSymbolWalker;
- function getSymbolWalker(accept) {
- if (accept === void 0) { accept = function () { return true; }; }
- var visitedTypes = []; // Sparse array from id to type
- var visitedSymbols = []; // Sparse array from id to symbol
- return {
- walkType: function (type) {
- try {
- visitType(type);
- return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
- }
- finally {
- ts.clear(visitedTypes);
- ts.clear(visitedSymbols);
- }
- },
- walkSymbol: function (symbol) {
- try {
- visitSymbol(symbol);
- return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
- }
- finally {
- ts.clear(visitedTypes);
- ts.clear(visitedSymbols);
+ function bindObjectLiteralExpression(node) {
+ var ElementKind;
+ (function (ElementKind) {
+ ElementKind[ElementKind["Property"] = 1] = "Property";
+ ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
+ })(ElementKind || (ElementKind = {}));
+ if (inStrictMode && !ts.isAssignmentTarget(node)) {
+ var seen = new ts.Map();
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (prop.kind === 296 /* SpreadAssignment */ || prop.name.kind !== 79 /* Identifier */) {
+ continue;
}
- },
- };
- function visitType(type) {
- if (!type) {
- return;
- }
- if (visitedTypes[type.id]) {
- return;
- }
- visitedTypes[type.id] = type;
- // Reuse visitSymbol to visit the type's symbol,
- // but be sure to bail on recuring into the type if accept declines the symbol.
- var shouldBail = visitSymbol(type.symbol);
- if (shouldBail)
- return;
- // Visit the type's related types, if any
- if (type.flags & 524288 /* Object */) {
- var objectType = type;
- var objectFlags = objectType.objectFlags;
- if (objectFlags & 4 /* Reference */) {
- visitTypeReference(type);
+ var identifier = prop.name;
+ // ECMA-262 11.1.5 Object Initializer
+ // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
+ // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
+ // IsDataDescriptor(propId.descriptor) is true.
+ // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
+ // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
+ // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
+ // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
+ var currentKind = prop.kind === 294 /* PropertyAssignment */ || prop.kind === 295 /* ShorthandPropertyAssignment */ || prop.kind === 168 /* MethodDeclaration */
+ ? 1 /* Property */
+ : 2 /* Accessor */;
+ var existingKind = seen.get(identifier.escapedText);
+ if (!existingKind) {
+ seen.set(identifier.escapedText, currentKind);
+ continue;
}
- if (objectFlags & 32 /* Mapped */) {
- visitMappedType(type);
+ if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
+ var span = ts.getErrorSpanForNode(file, identifier);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
}
- if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
- visitInterfaceType(type);
+ }
+ }
+ return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
+ }
+ function bindJsxAttributes(node) {
+ return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
+ }
+ function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
+ return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ }
+ function bindAnonymousDeclaration(node, symbolFlags, name) {
+ var symbol = createSymbol(symbolFlags, name);
+ if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
+ symbol.parent = container.symbol;
+ }
+ addDeclarationToSymbol(symbol, node, symbolFlags);
+ return symbol;
+ }
+ function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
+ switch (blockScopeContainer.kind) {
+ case 260 /* ModuleDeclaration */:
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
+ case 303 /* SourceFile */:
+ if (ts.isExternalOrCommonJsModule(container)) {
+ declareModuleMember(node, symbolFlags, symbolExcludes);
+ break;
}
- if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
- visitObjectType(objectType);
+ // falls through
+ default:
+ if (!blockScopeContainer.locals) {
+ blockScopeContainer.locals = ts.createSymbolTable();
+ addToContainerChain(blockScopeContainer);
+ }
+ declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
+ }
+ }
+ function delayedBindJSDocTypedefTag() {
+ if (!delayedTypeAliases) {
+ return;
+ }
+ var saveContainer = container;
+ var saveLastContainer = lastContainer;
+ var saveBlockScopeContainer = blockScopeContainer;
+ var saveParent = parent;
+ var saveCurrentFlow = currentFlow;
+ for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
+ var typeAlias = delayedTypeAliases_1[_i];
+ var host = typeAlias.parent.parent;
+ container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
+ blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
+ currentFlow = initFlowNode({ flags: 2 /* Start */ });
+ parent = typeAlias;
+ bind(typeAlias.typeExpression);
+ var declName = ts.getNameOfDeclaration(typeAlias);
+ if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
+ // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
+ var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
+ if (isTopLevel) {
+ bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
+ var oldContainer = container;
+ switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
+ case 1 /* ExportsProperty */:
+ case 2 /* ModuleExports */:
+ if (!ts.isExternalOrCommonJsModule(file)) {
+ container = undefined;
+ }
+ else {
+ container = file;
+ }
+ break;
+ case 4 /* ThisProperty */:
+ container = declName.parent.expression;
+ break;
+ case 3 /* PrototypeProperty */:
+ container = declName.parent.expression.name;
+ break;
+ case 5 /* Property */:
+ container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
+ : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
+ : declName.parent.expression;
+ break;
+ case 0 /* None */:
+ return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
+ }
+ if (container) {
+ declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
+ }
+ container = oldContainer;
}
}
- if (type.flags & 262144 /* TypeParameter */) {
- visitTypeParameter(type);
+ else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 79 /* Identifier */) {
+ parent = typeAlias.parent;
+ bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
}
- if (type.flags & 3145728 /* UnionOrIntersection */) {
- visitUnionOrIntersectionType(type);
+ else {
+ bind(typeAlias.fullName);
}
- if (type.flags & 4194304 /* Index */) {
- visitIndexType(type);
+ }
+ container = saveContainer;
+ lastContainer = saveLastContainer;
+ blockScopeContainer = saveBlockScopeContainer;
+ parent = saveParent;
+ currentFlow = saveCurrentFlow;
+ }
+ // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
+ // check for reserved words used as identifiers in strict mode code, as well as `yield` or `await` in
+ // [Yield] or [Await] contexts, respectively.
+ function checkContextualIdentifier(node) {
+ // Report error only if there are no parse errors in file
+ if (!file.parseDiagnostics.length &&
+ !(node.flags & 8388608 /* Ambient */) &&
+ !(node.flags & 4194304 /* JSDoc */) &&
+ !ts.isIdentifierName(node)) {
+ // strict mode identifiers
+ if (inStrictMode &&
+ node.originalKeywordKind >= 117 /* FirstFutureReservedWord */ &&
+ node.originalKeywordKind <= 125 /* LastFutureReservedWord */) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
}
- if (type.flags & 8388608 /* IndexedAccess */) {
- visitIndexedAccessType(type);
+ else if (node.originalKeywordKind === 132 /* AwaitKeyword */) {
+ if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node)));
+ }
+ else if (node.flags & 32768 /* AwaitContext */) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
+ }
+ }
+ else if (node.originalKeywordKind === 125 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
}
}
- function visitTypeReference(type) {
- visitType(type.target);
- ts.forEach(getTypeArguments(type), visitType);
+ }
+ function getStrictModeIdentifierMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
}
- function visitTypeParameter(type) {
- visitType(getConstraintOfTypeParameter(type));
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
}
- function visitUnionOrIntersectionType(type) {
- ts.forEach(type.types, visitType);
+ return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
+ }
+ // The binder visits every node, so this is a good place to check for
+ // the reserved private name (there is only one)
+ function checkPrivateIdentifier(node) {
+ if (node.escapedText === "#constructor") {
+ // Report error only if there are no parse errors in file
+ if (!file.parseDiagnostics.length) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
+ }
}
- function visitIndexType(type) {
- visitType(type.type);
+ }
+ function checkStrictModeBinaryExpression(node) {
+ if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
+ // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
+ // Assignment operator(11.13) or of a PostfixExpression(11.3)
+ checkStrictModeEvalOrArguments(node, node.left);
}
- function visitIndexedAccessType(type) {
- visitType(type.objectType);
- visitType(type.indexType);
- visitType(type.constraint);
+ }
+ function checkStrictModeCatchClause(node) {
+ // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
+ // Catch production is eval or arguments
+ if (inStrictMode && node.variableDeclaration) {
+ checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
}
- function visitMappedType(type) {
- visitType(type.typeParameter);
- visitType(type.constraintType);
- visitType(type.templateType);
- visitType(type.modifiersType);
+ }
+ function checkStrictModeDeleteExpression(node) {
+ // Grammar checking
+ if (inStrictMode && node.expression.kind === 79 /* Identifier */) {
+ // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
+ // UnaryExpression is a direct reference to a variable, function argument, or function name
+ var span = ts.getErrorSpanForNode(file, node.expression);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
}
- function visitSignature(signature) {
- var typePredicate = getTypePredicateOfSignature(signature);
- if (typePredicate) {
- visitType(typePredicate.type);
- }
- ts.forEach(signature.typeParameters, visitType);
- for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
- var parameter = _a[_i];
- visitSymbol(parameter);
+ }
+ function isEvalOrArgumentsIdentifier(node) {
+ return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
+ }
+ function checkStrictModeEvalOrArguments(contextNode, name) {
+ if (name && name.kind === 79 /* Identifier */) {
+ var identifier = name;
+ if (isEvalOrArgumentsIdentifier(identifier)) {
+ // We check first if the name is inside class declaration or class expression; if so give explicit message
+ // otherwise report generic error message.
+ var span = ts.getErrorSpanForNode(file, name);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
}
- visitType(getRestTypeOfSignature(signature));
- visitType(getReturnTypeOfSignature(signature));
}
- function visitInterfaceType(interfaceT) {
- visitObjectType(interfaceT);
- ts.forEach(interfaceT.typeParameters, visitType);
- ts.forEach(getBaseTypes(interfaceT), visitType);
- visitType(interfaceT.thisType);
+ }
+ function getStrictModeEvalOrArgumentsMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode;
}
- function visitObjectType(type) {
- var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
- visitType(stringIndexType);
- var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
- visitType(numberIndexType);
- // The two checks above *should* have already resolved the type (if needed), so this should be cached
- var resolved = resolveStructuredTypeMembers(type);
- for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
- var signature = _a[_i];
- visitSignature(signature);
- }
- for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
- var signature = _c[_b];
- visitSignature(signature);
- }
- for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
- var p = _e[_d];
- visitSymbol(p);
- }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
}
- function visitSymbol(symbol) {
- if (!symbol) {
- return false;
- }
- var symbolId = ts.getSymbolId(symbol);
- if (visitedSymbols[symbolId]) {
- return false;
- }
- visitedSymbols[symbolId] = symbol;
- if (!accept(symbol)) {
- return true;
- }
- var t = getTypeOfSymbol(symbol);
- visitType(t); // Should handle members on classes and such
- if (symbol.exports) {
- symbol.exports.forEach(visitSymbol);
+ return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
+ }
+ function checkStrictModeFunctionName(node) {
+ if (inStrictMode) {
+ // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ }
+ function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
+ // Provide specialized messages to help the user understand why we think they're in
+ // strict mode.
+ if (ts.getContainingClass(node)) {
+ return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;
+ }
+ if (file.externalModuleIndicator) {
+ return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
+ }
+ return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
+ }
+ function checkStrictModeFunctionDeclaration(node) {
+ if (languageVersion < 2 /* ES2015 */) {
+ // Report error if function is not top level function declaration
+ if (blockScopeContainer.kind !== 303 /* SourceFile */ &&
+ blockScopeContainer.kind !== 260 /* ModuleDeclaration */ &&
+ !ts.isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) {
+ // We check first if the name is inside class declaration or class expression; if so give explicit message
+ // otherwise report generic error message.
+ var errorSpan = ts.getErrorSpanForNode(file, node);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
}
- ts.forEach(symbol.declarations, function (d) {
- // Type queries are too far resolved when we just visit the symbol's type
- // (their type resolved directly to the member deeply referenced)
- // So to get the intervening symbols, we need to check if there's a type
- // query node on any of the symbol's declarations and get symbols there
- if (d.type && d.type.kind === 172 /* TypeQuery */) {
- var query = d.type;
- var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
- visitSymbol(entity);
- }
- });
- return false;
}
}
- }
- ts.createGetSymbolWalker = createGetSymbolWalker;
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var ambientModuleSymbolRegex = /^".+"$/;
- var anon = "(anonymous)";
- var nextSymbolId = 1;
- var nextNodeId = 1;
- var nextMergeId = 1;
- var nextFlowId = 1;
- var IterationUse;
- (function (IterationUse) {
- IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
- IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
- IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
- IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
- IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
- IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
- IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
- // Spread, Destructuring, Array element assignment
- IterationUse[IterationUse["Element"] = 1] = "Element";
- IterationUse[IterationUse["Spread"] = 33] = "Spread";
- IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
- IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
- IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
- IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
- IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
- IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
- IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
- })(IterationUse || (IterationUse = {}));
- var IterationTypeKind;
- (function (IterationTypeKind) {
- IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
- IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
- IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
- })(IterationTypeKind || (IterationTypeKind = {}));
- var WideningKind;
- (function (WideningKind) {
- WideningKind[WideningKind["Normal"] = 0] = "Normal";
- WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
- WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
- WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
- })(WideningKind || (WideningKind = {}));
- var TypeFacts;
- (function (TypeFacts) {
- TypeFacts[TypeFacts["None"] = 0] = "None";
- TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
- TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
- TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
- TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
- TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
- TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
- TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
- TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
- TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
- TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
- TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
- TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
- TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
- TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
- TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
- TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
- TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
- TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
- TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
- TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
- TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
- TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
- TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
- TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
- TypeFacts[TypeFacts["All"] = 16777215] = "All";
- // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
- // The presence of a particular fact means that the given test is true for some (and possibly all) values
- // of that kind of type.
- TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
- TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
- TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
- TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
- TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
- TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
- TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
- TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
- TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
- TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
- TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
- TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
- TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
- TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
- TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
- TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
- TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
- TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
- TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
- TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
- TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
- TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
- TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
- TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
- TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
- TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
- TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
- TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
- TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
- TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
- TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
- TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
- TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
- TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
- TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
- TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
- TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
- TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
- TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
- TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
- TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
- TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
- })(TypeFacts || (TypeFacts = {}));
- var typeofEQFacts = ts.createMapFromTemplate({
- string: 1 /* TypeofEQString */,
- number: 2 /* TypeofEQNumber */,
- bigint: 4 /* TypeofEQBigInt */,
- boolean: 8 /* TypeofEQBoolean */,
- symbol: 16 /* TypeofEQSymbol */,
- undefined: 65536 /* EQUndefined */,
- object: 32 /* TypeofEQObject */,
- function: 64 /* TypeofEQFunction */
- });
- var typeofNEFacts = ts.createMapFromTemplate({
- string: 256 /* TypeofNEString */,
- number: 512 /* TypeofNENumber */,
- bigint: 1024 /* TypeofNEBigInt */,
- boolean: 2048 /* TypeofNEBoolean */,
- symbol: 4096 /* TypeofNESymbol */,
- undefined: 524288 /* NEUndefined */,
- object: 8192 /* TypeofNEObject */,
- function: 16384 /* TypeofNEFunction */
- });
- var TypeSystemPropertyName;
- (function (TypeSystemPropertyName) {
- TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
- TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
- TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
- TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
- TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
- TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
- TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
- })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
- var CheckMode;
- (function (CheckMode) {
- CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
- CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
- CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
- CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
- })(CheckMode || (CheckMode = {}));
- var AccessFlags;
- (function (AccessFlags) {
- AccessFlags[AccessFlags["None"] = 0] = "None";
- AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
- AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
- AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
- AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
- })(AccessFlags || (AccessFlags = {}));
- var SignatureCheckMode;
- (function (SignatureCheckMode) {
- SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
- SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
- SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
- SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
- SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
- })(SignatureCheckMode || (SignatureCheckMode = {}));
- var IntersectionState;
- (function (IntersectionState) {
- IntersectionState[IntersectionState["None"] = 0] = "None";
- IntersectionState[IntersectionState["Source"] = 1] = "Source";
- IntersectionState[IntersectionState["Target"] = 2] = "Target";
- IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
- IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
- })(IntersectionState || (IntersectionState = {}));
- var MappedTypeModifiers;
- (function (MappedTypeModifiers) {
- MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
- MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
- MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
- MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
- })(MappedTypeModifiers || (MappedTypeModifiers = {}));
- var ExpandingFlags;
- (function (ExpandingFlags) {
- ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
- ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
- ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
- ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
- })(ExpandingFlags || (ExpandingFlags = {}));
- var MembersOrExportsResolutionKind;
- (function (MembersOrExportsResolutionKind) {
- MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
- MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
- })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
- var UnusedKind;
- (function (UnusedKind) {
- UnusedKind[UnusedKind["Local"] = 0] = "Local";
- UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
- })(UnusedKind || (UnusedKind = {}));
- var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
- var DeclarationMeaning;
- (function (DeclarationMeaning) {
- DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
- DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
- DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
- DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
- DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
- DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
- })(DeclarationMeaning || (DeclarationMeaning = {}));
- var DeclarationSpaces;
- (function (DeclarationSpaces) {
- DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
- DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
- DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
- DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
- })(DeclarationSpaces || (DeclarationSpaces = {}));
- function SymbolLinks() {
- }
- function NodeLinks() {
- this.flags = 0;
- }
- function getNodeId(node) {
- if (!node.id) {
- node.id = nextNodeId;
- nextNodeId++;
+ function checkStrictModeNumericLiteral(node) {
+ if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
+ }
}
- return node.id;
- }
- ts.getNodeId = getNodeId;
- function getSymbolId(symbol) {
- if (!symbol.id) {
- symbol.id = nextSymbolId;
- nextSymbolId++;
+ function checkStrictModePostfixUnaryExpression(node) {
+ // Grammar checking
+ // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
+ // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
+ // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.operand);
+ }
}
- return symbol.id;
- }
- ts.getSymbolId = getSymbolId;
- function isInstantiatedModule(node, preserveConstEnums) {
- var moduleState = ts.getModuleInstanceState(node);
- return moduleState === 1 /* Instantiated */ ||
- (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
- }
- ts.isInstantiatedModule = isInstantiatedModule;
- function createTypeChecker(host, produceDiagnostics) {
- var getPackagesSet = ts.memoize(function () {
- var set = ts.createMap();
- host.getSourceFiles().forEach(function (sf) {
- if (!sf.resolvedModules)
- return;
- ts.forEachEntry(sf.resolvedModules, function (r) {
- if (r && r.packageId)
- set.set(r.packageId.name, true);
- });
- });
- return set;
- });
- // Cancellation that controls whether or not we can cancel in the middle of type checking.
- // In general cancelling is *not* safe for the type checker. We might be in the middle of
- // computing something, and we will leave our internals in an inconsistent state. Callers
- // who set the cancellation token should catch if a cancellation exception occurs, and
- // should throw away and create a new TypeChecker.
- //
- // Currently we only support setting the cancellation token when getting diagnostics. This
- // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
- // they no longer need the information (for example, if the user started editing again).
- var cancellationToken;
- var requestedExternalEmitHelpers;
- var externalHelpersModule;
- var Symbol = ts.objectAllocator.getSymbolConstructor();
- var Type = ts.objectAllocator.getTypeConstructor();
- var Signature = ts.objectAllocator.getSignatureConstructor();
- var typeCount = 0;
- var symbolCount = 0;
- var enumCount = 0;
- var totalInstantiationCount = 0;
- var instantiationCount = 0;
- var instantiationDepth = 0;
- var constraintDepth = 0;
- var currentNode;
- var emptySymbols = ts.createSymbolTable();
- var arrayVariances = [1 /* Covariant */];
- var compilerOptions = host.getCompilerOptions();
- var languageVersion = ts.getEmitScriptTarget(compilerOptions);
- var moduleKind = ts.getEmitModuleKind(compilerOptions);
- var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
- var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
- var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
- var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
- var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
- var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
- var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
- var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
- var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
- var emitResolver = createResolver();
- var nodeBuilder = createNodeBuilder();
- var globals = ts.createSymbolTable();
- var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
- undefinedSymbol.declarations = [];
- var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
- globalThisSymbol.exports = globals;
- globalThisSymbol.declarations = [];
- globals.set(globalThisSymbol.escapedName, globalThisSymbol);
- var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
- var requireSymbol = createSymbol(4 /* Property */, "require");
- /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
- var apparentArgumentCount;
- // for public members that accept a Node or one of its subtypes, we must guard against
- // synthetic nodes created during transformations by calling `getParseTreeNode`.
- // for most of these, we perform the guard only on `checker` to avoid any possible
- // extra cost of calling `getParseTreeNode` when calling these functions from inside the
- // checker.
- var checker = {
- getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
- getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
- getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
- getTypeCount: function () { return typeCount; },
- getInstantiationCount: function () { return totalInstantiationCount; },
- getRelationCacheSizes: function () { return ({
- assignable: assignableRelation.size,
- identity: identityRelation.size,
- subtype: subtypeRelation.size,
- strictSubtype: strictSubtypeRelation.size,
- }); },
- isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
- isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
- isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
- getMergedSymbol: getMergedSymbol,
- getDiagnostics: getDiagnostics,
- getGlobalDiagnostics: getGlobalDiagnostics,
- getTypeOfSymbolAtLocation: function (symbol, location) {
- location = ts.getParseTreeNode(location);
- return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
- },
- getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
- var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
- if (parameter === undefined)
- return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
- return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
- },
- getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
- getPropertiesOfType: getPropertiesOfType,
- getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
- getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
- var node = ts.getParseTreeNode(location);
- if (!node) {
- return undefined;
+ function checkStrictModePrefixUnaryExpression(node) {
+ // Grammar checking
+ if (inStrictMode) {
+ if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
+ checkStrictModeEvalOrArguments(node, node.operand);
}
- var propName = ts.escapeLeadingUnderscores(name);
- var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
- return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
- },
- getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
- getIndexInfoOfType: getIndexInfoOfType,
- getSignaturesOfType: getSignaturesOfType,
- getIndexTypeOfType: getIndexTypeOfType,
- getBaseTypes: getBaseTypes,
- getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
- getWidenedType: getWidenedType,
- getTypeFromTypeNode: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
- return node ? getTypeFromTypeNode(node) : errorType;
- },
- getParameterType: getTypeAtPosition,
- getPromisedTypeOfPromise: getPromisedTypeOfPromise,
- getReturnTypeOfSignature: getReturnTypeOfSignature,
- isNullableType: isNullableType,
- getNullableType: getNullableType,
- getNonNullableType: getNonNullableType,
- getNonOptionalType: removeOptionalTypeMarker,
- getTypeArguments: getTypeArguments,
- typeToTypeNode: nodeBuilder.typeToTypeNode,
- indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
- signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
- symbolToEntityName: nodeBuilder.symbolToEntityName,
- symbolToExpression: nodeBuilder.symbolToExpression,
- symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
- symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
- typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
- getSymbolsInScope: function (location, meaning) {
- location = ts.getParseTreeNode(location);
- return location ? getSymbolsInScope(location, meaning) : [];
- },
- getSymbolAtLocation: function (node) {
- node = ts.getParseTreeNode(node);
- // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
- return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
- },
- getShorthandAssignmentValueSymbol: function (node) {
- node = ts.getParseTreeNode(node);
- return node ? getShorthandAssignmentValueSymbol(node) : undefined;
- },
- getExportSpecifierLocalTargetSymbol: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
- return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
- },
- getExportSymbolOfSymbol: function (symbol) {
- return getMergedSymbol(symbol.exportSymbol || symbol);
- },
- getTypeAtLocation: function (node) {
- node = ts.getParseTreeNode(node);
- return node ? getTypeOfNode(node) : errorType;
- },
- getTypeOfAssignmentPattern: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
- return node && getTypeOfAssignmentPattern(node) || errorType;
- },
- getPropertySymbolOfDestructuringAssignment: function (locationIn) {
- var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
- return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
- },
- signatureToString: function (signature, enclosingDeclaration, flags, kind) {
- return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
- },
- typeToString: function (type, enclosingDeclaration, flags) {
- return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
- },
- symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
- return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
- },
- typePredicateToString: function (predicate, enclosingDeclaration, flags) {
- return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
- },
- writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
- return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
- },
- writeType: function (type, enclosingDeclaration, flags, writer) {
- return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
- },
- writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
- return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
- },
- writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
- return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
- },
- getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
- getRootSymbols: getRootSymbols,
- getContextualType: function (nodeIn, contextFlags) {
- var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
- if (!node) {
- return undefined;
+ }
+ }
+ function checkStrictModeWithStatement(node) {
+ // Grammar checking for withStatement
+ if (inStrictMode) {
+ errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
+ }
+ }
+ function checkStrictModeLabeledStatement(node) {
+ // Grammar checking for labeledStatement
+ if (inStrictMode && ts.getEmitScriptTarget(options) >= 2 /* ES2015 */) {
+ if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
+ errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
}
- var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
- var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
- if (contextFlags & 4 /* Completions */ && containingCall) {
- var toMarkSkip = node;
- do {
- getNodeLinks(toMarkSkip).skipDirectInference = true;
- toMarkSkip = toMarkSkip.parent;
- } while (toMarkSkip && toMarkSkip !== containingCall);
- getNodeLinks(containingCall).resolvedSignature = undefined;
+ }
+ }
+ function errorOnFirstToken(node, message, arg0, arg1, arg2) {
+ var span = ts.getSpanOfTokenAtPosition(file, node.pos);
+ file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
+ }
+ function errorOrSuggestionOnNode(isError, node, message) {
+ errorOrSuggestionOnRange(isError, node, node, message);
+ }
+ function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
+ addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
+ }
+ function addErrorOrSuggestionDiagnostic(isError, range, message) {
+ var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
+ if (isError) {
+ file.bindDiagnostics.push(diag);
+ }
+ else {
+ file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
+ }
+ }
+ function bind(node) {
+ if (!node) {
+ return;
+ }
+ ts.setParent(node, parent);
+ var saveInStrictMode = inStrictMode;
+ // Even though in the AST the jsdoc @typedef node belongs to the current node,
+ // its symbol might be in the same scope with the current node's symbol. Consider:
+ //
+ // /** @typedef {string | number} MyType */
+ // function foo();
+ //
+ // Here the current node is "foo", which is a container, but the scope of "MyType" should
+ // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
+ // and skip binding this tag later when binding all the other jsdoc tags.
+ // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
+ // and then potentially add the symbol to an appropriate symbol table. Possible
+ // destination symbol tables are:
+ //
+ // 1) The 'exports' table of the current container's symbol.
+ // 2) The 'members' table of the current container's symbol.
+ // 3) The 'locals' table of the current container.
+ //
+ // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
+ // (like TypeLiterals for example) will not be put in any table.
+ bindWorker(node);
+ // Then we recurse into the children of the node to bind them as well. For certain
+ // symbols we do specialized work when we recurse. For example, we'll keep track of
+ // the current 'container' node when it changes. This helps us know which symbol table
+ // a local should go into for example. Since terminal nodes are known not to have
+ // children, as an optimization we don't process those.
+ if (node.kind > 159 /* LastToken */) {
+ var saveParent = parent;
+ parent = node;
+ var containerFlags = getContainerFlags(node);
+ if (containerFlags === 0 /* None */) {
+ bindChildren(node);
}
- var result = getContextualType(node, contextFlags);
- if (contextFlags & 4 /* Completions */ && containingCall) {
- var toMarkSkip = node;
- do {
- getNodeLinks(toMarkSkip).skipDirectInference = undefined;
- toMarkSkip = toMarkSkip.parent;
- } while (toMarkSkip && toMarkSkip !== containingCall);
- getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
+ else {
+ bindContainer(node, containerFlags);
}
- return result;
- },
- getContextualTypeForObjectLiteralElement: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
- return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
- },
- getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
- var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
- return node && getContextualTypeForArgumentAtIndex(node, argIndex);
- },
- getContextualTypeForJsxAttribute: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
- return node && getContextualTypeForJsxAttribute(node);
- },
- isContextSensitive: isContextSensitive,
- getFullyQualifiedName: getFullyQualifiedName,
- getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
- },
- getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
- },
- getExpandedParameters: getExpandedParameters,
- hasEffectiveRestParameter: hasEffectiveRestParameter,
- getConstantValue: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
- return node ? getConstantValue(node) : undefined;
- },
- isValidPropertyAccess: function (nodeIn, propertyName) {
- var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
- return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
- },
- isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
- var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
- return !!node && isValidPropertyAccessForCompletions(node, type, property);
- },
- getSignatureFromDeclaration: function (declarationIn) {
- var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
- return declaration ? getSignatureFromDeclaration(declaration) : undefined;
- },
- isImplementationOfOverload: function (node) {
- var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
- return parsed ? isImplementationOfOverload(parsed) : undefined;
- },
- getImmediateAliasedSymbol: getImmediateAliasedSymbol,
- getAliasedSymbol: resolveAlias,
- getEmitResolver: getEmitResolver,
- getExportsOfModule: getExportsOfModuleAsArray,
- getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
- getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
- getAmbientModules: getAmbientModules,
- getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
- isOptionalParameter: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
- return node ? isOptionalParameter(node) : false;
- },
- tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
- tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
- tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
- // we deliberately exclude augmentations
- // since we are only interested in declarations of the module itself
- return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
- },
- getApparentType: getApparentType,
- getUnionType: getUnionType,
- isTypeAssignableTo: isTypeAssignableTo,
- createAnonymousType: createAnonymousType,
- createSignature: createSignature,
- createSymbol: createSymbol,
- createIndexInfo: createIndexInfo,
- getAnyType: function () { return anyType; },
- getStringType: function () { return stringType; },
- getNumberType: function () { return numberType; },
- createPromiseType: createPromiseType,
- createArrayType: createArrayType,
- getElementTypeOfArrayType: getElementTypeOfArrayType,
- getBooleanType: function () { return booleanType; },
- getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
- getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
- getVoidType: function () { return voidType; },
- getUndefinedType: function () { return undefinedType; },
- getNullType: function () { return nullType; },
- getESSymbolType: function () { return esSymbolType; },
- getNeverType: function () { return neverType; },
- getOptionalType: function () { return optionalType; },
- isSymbolAccessible: isSymbolAccessible,
- isArrayType: isArrayType,
- isTupleType: isTupleType,
- isArrayLikeType: isArrayLikeType,
- isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
- getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
- getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
- getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
- getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
- getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
- getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
- getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
- getBaseConstraintOfType: getBaseConstraintOfType,
- getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
- resolveName: function (name, location, meaning, excludeGlobals) {
- return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
- },
- getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
- getAccessibleSymbolChain: getAccessibleSymbolChain,
- getTypePredicateOfSignature: getTypePredicateOfSignature,
- resolveExternalModuleName: function (moduleSpecifier) {
- return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
- },
- resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node, includeGlobalThis) {
- node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node, includeGlobalThis);
- },
- getTypeArgumentConstraint: function (nodeIn) {
- var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
- return node && getTypeArgumentConstraint(node);
- },
- getSuggestionDiagnostics: function (file, ct) {
- if (ts.skipTypeChecking(file, compilerOptions, host)) {
- return ts.emptyArray;
+ parent = saveParent;
+ }
+ else {
+ var saveParent = parent;
+ if (node.kind === 1 /* EndOfFileToken */)
+ parent = node;
+ bindJSDoc(node);
+ parent = saveParent;
+ }
+ inStrictMode = saveInStrictMode;
+ }
+ function bindJSDoc(node) {
+ if (ts.hasJSDocNodes(node)) {
+ if (ts.isInJSFile(node)) {
+ for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
+ var j = _a[_i];
+ bind(j);
+ }
}
- var diagnostics;
- try {
- // Record the cancellation token so it can be checked later on during checkSourceElement.
- // Do this in a finally block so we can ensure that it gets reset back to nothing after
- // this call is done.
- cancellationToken = ct;
- // Ensure file is type checked
- checkSourceFile(file);
- ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
- diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
- checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
- if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
- (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
- }
- });
- return diagnostics || ts.emptyArray;
+ else {
+ for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
+ var j = _c[_b];
+ ts.setParent(j, node);
+ ts.setParentRecursive(j, /*incremental*/ false);
+ }
}
- finally {
- cancellationToken = undefined;
+ }
+ }
+ function updateStrictModeStatementList(statements) {
+ if (!inStrictMode) {
+ for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
+ var statement = statements_3[_i];
+ if (!ts.isPrologueDirective(statement)) {
+ return;
+ }
+ if (isUseStrictPrologueDirective(statement)) {
+ inStrictMode = true;
+ return;
+ }
+ }
+ }
+ }
+ /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
+ function isUseStrictPrologueDirective(node) {
+ var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
+ // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
+ // string to contain unicode escapes (as per ES5).
+ return nodeText === '"use strict"' || nodeText === "'use strict'";
+ }
+ function bindWorker(node) {
+ switch (node.kind) {
+ /* Strict mode checks */
+ case 79 /* Identifier */:
+ // for typedef type names with namespaces, bind the new jsdoc type symbol here
+ // because it requires all containing namespaces to be in effect, namely the
+ // current "blockScopeContainer" needs to be set to its immediate namespace parent.
+ if (node.isInJSDocNamespace) {
+ var parentNode = node.parent;
+ while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
+ parentNode = parentNode.parent;
+ }
+ bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
+ break;
+ }
+ // falls through
+ case 108 /* ThisKeyword */:
+ if (currentFlow && (ts.isExpression(node) || parent.kind === 295 /* ShorthandPropertyAssignment */)) {
+ node.flowNode = currentFlow;
+ }
+ return checkContextualIdentifier(node);
+ case 160 /* QualifiedName */:
+ if (currentFlow && ts.isPartOfTypeQuery(node)) {
+ node.flowNode = currentFlow;
+ }
+ break;
+ case 230 /* MetaProperty */:
+ case 106 /* SuperKeyword */:
+ node.flowNode = currentFlow;
+ break;
+ case 80 /* PrivateIdentifier */:
+ return checkPrivateIdentifier(node);
+ case 205 /* PropertyAccessExpression */:
+ case 206 /* ElementAccessExpression */:
+ var expr = node;
+ if (currentFlow && isNarrowableReference(expr)) {
+ expr.flowNode = currentFlow;
+ }
+ if (ts.isSpecialPropertyDeclaration(expr)) {
+ bindSpecialPropertyDeclaration(expr);
+ }
+ if (ts.isInJSFile(expr) &&
+ file.commonJsModuleIndicator &&
+ ts.isModuleExportsAccessExpression(expr) &&
+ !lookupSymbolForName(blockScopeContainer, "module")) {
+ declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
+ }
+ break;
+ case 220 /* BinaryExpression */:
+ var specialKind = ts.getAssignmentDeclarationKind(node);
+ switch (specialKind) {
+ case 1 /* ExportsProperty */:
+ bindExportsPropertyAssignment(node);
+ break;
+ case 2 /* ModuleExports */:
+ bindModuleExportsAssignment(node);
+ break;
+ case 3 /* PrototypeProperty */:
+ bindPrototypePropertyAssignment(node.left, node);
+ break;
+ case 6 /* Prototype */:
+ bindPrototypeAssignment(node);
+ break;
+ case 4 /* ThisProperty */:
+ bindThisPropertyAssignment(node);
+ break;
+ case 5 /* Property */:
+ var expression = node.left.expression;
+ if (ts.isInJSFile(node) && ts.isIdentifier(expression)) {
+ var symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
+ if (ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration)) {
+ bindThisPropertyAssignment(node);
+ break;
+ }
+ }
+ bindSpecialPropertyAssignment(node);
+ break;
+ case 0 /* None */:
+ // Nothing to do
+ break;
+ default:
+ ts.Debug.fail("Unknown binary expression special property assignment kind");
+ }
+ return checkStrictModeBinaryExpression(node);
+ case 291 /* CatchClause */:
+ return checkStrictModeCatchClause(node);
+ case 214 /* DeleteExpression */:
+ return checkStrictModeDeleteExpression(node);
+ case 8 /* NumericLiteral */:
+ return checkStrictModeNumericLiteral(node);
+ case 219 /* PostfixUnaryExpression */:
+ return checkStrictModePostfixUnaryExpression(node);
+ case 218 /* PrefixUnaryExpression */:
+ return checkStrictModePrefixUnaryExpression(node);
+ case 247 /* WithStatement */:
+ return checkStrictModeWithStatement(node);
+ case 249 /* LabeledStatement */:
+ return checkStrictModeLabeledStatement(node);
+ case 191 /* ThisType */:
+ seenThisKeyword = true;
+ return;
+ case 176 /* TypePredicate */:
+ break; // Binding the children will handle everything
+ case 162 /* TypeParameter */:
+ return bindTypeParameter(node);
+ case 163 /* Parameter */:
+ return bindParameter(node);
+ case 253 /* VariableDeclaration */:
+ return bindVariableDeclarationOrBindingElement(node);
+ case 202 /* BindingElement */:
+ node.flowNode = currentFlow;
+ return bindVariableDeclarationOrBindingElement(node);
+ case 166 /* PropertyDeclaration */:
+ case 165 /* PropertySignature */:
+ return bindPropertyWorker(node);
+ case 294 /* PropertyAssignment */:
+ case 295 /* ShorthandPropertyAssignment */:
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
+ case 297 /* EnumMember */:
+ return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
+ case 173 /* CallSignature */:
+ case 174 /* ConstructSignature */:
+ case 175 /* IndexSignature */:
+ return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
+ case 168 /* MethodDeclaration */:
+ case 167 /* MethodSignature */:
+ // If this is an ObjectLiteralExpression method, then it sits in the same space
+ // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
+ // so that it will conflict with any other object literal members with the same
+ // name.
+ return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
+ case 255 /* FunctionDeclaration */:
+ return bindFunctionDeclaration(node);
+ case 170 /* Constructor */:
+ return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
+ case 171 /* GetAccessor */:
+ return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
+ case 172 /* SetAccessor */:
+ return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
+ case 178 /* FunctionType */:
+ case 315 /* JSDocFunctionType */:
+ case 321 /* JSDocSignature */:
+ case 179 /* ConstructorType */:
+ return bindFunctionOrConstructorType(node);
+ case 181 /* TypeLiteral */:
+ case 320 /* JSDocTypeLiteral */:
+ case 194 /* MappedType */:
+ return bindAnonymousTypeWorker(node);
+ case 330 /* JSDocClassTag */:
+ return bindJSDocClassTag(node);
+ case 204 /* ObjectLiteralExpression */:
+ return bindObjectLiteralExpression(node);
+ case 212 /* FunctionExpression */:
+ case 213 /* ArrowFunction */:
+ return bindFunctionExpression(node);
+ case 207 /* CallExpression */:
+ var assignmentKind = ts.getAssignmentDeclarationKind(node);
+ switch (assignmentKind) {
+ case 7 /* ObjectDefinePropertyValue */:
+ return bindObjectDefinePropertyAssignment(node);
+ case 8 /* ObjectDefinePropertyExports */:
+ return bindObjectDefinePropertyExport(node);
+ case 9 /* ObjectDefinePrototypeProperty */:
+ return bindObjectDefinePrototypeProperty(node);
+ case 0 /* None */:
+ break; // Nothing to do
+ default:
+ return ts.Debug.fail("Unknown call expression assignment declaration kind");
+ }
+ if (ts.isInJSFile(node)) {
+ bindCallExpression(node);
+ }
+ break;
+ // Members of classes, interfaces, and modules
+ case 225 /* ClassExpression */:
+ case 256 /* ClassDeclaration */:
+ // All classes are automatically in strict mode in ES6.
+ inStrictMode = true;
+ return bindClassLikeDeclaration(node);
+ case 257 /* InterfaceDeclaration */:
+ return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
+ case 258 /* TypeAliasDeclaration */:
+ return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
+ case 259 /* EnumDeclaration */:
+ return bindEnumDeclaration(node);
+ case 260 /* ModuleDeclaration */:
+ return bindModuleDeclaration(node);
+ // Jsx-attributes
+ case 285 /* JsxAttributes */:
+ return bindJsxAttributes(node);
+ case 284 /* JsxAttribute */:
+ return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
+ // Imports and exports
+ case 264 /* ImportEqualsDeclaration */:
+ case 267 /* NamespaceImport */:
+ case 269 /* ImportSpecifier */:
+ case 274 /* ExportSpecifier */:
+ return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ case 263 /* NamespaceExportDeclaration */:
+ return bindNamespaceExportDeclaration(node);
+ case 266 /* ImportClause */:
+ return bindImportClause(node);
+ case 271 /* ExportDeclaration */:
+ return bindExportDeclaration(node);
+ case 270 /* ExportAssignment */:
+ return bindExportAssignment(node);
+ case 303 /* SourceFile */:
+ updateStrictModeStatementList(node.statements);
+ return bindSourceFileIfExternalModule();
+ case 234 /* Block */:
+ if (!ts.isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) {
+ return;
+ }
+ // falls through
+ case 261 /* ModuleBlock */:
+ return updateStrictModeStatementList(node.statements);
+ case 338 /* JSDocParameterTag */:
+ if (node.parent.kind === 321 /* JSDocSignature */) {
+ return bindParameter(node);
+ }
+ if (node.parent.kind !== 320 /* JSDocTypeLiteral */) {
+ break;
+ }
+ // falls through
+ case 345 /* JSDocPropertyTag */:
+ var propTag = node;
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 314 /* JSDocOptionalType */ ?
+ 4 /* Property */ | 16777216 /* Optional */ :
+ 4 /* Property */;
+ return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
+ case 343 /* JSDocTypedefTag */:
+ case 336 /* JSDocCallbackTag */:
+ case 337 /* JSDocEnumTag */:
+ return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
+ }
+ }
+ function bindPropertyWorker(node) {
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
+ }
+ function bindAnonymousTypeWorker(node) {
+ return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
+ }
+ function bindSourceFileIfExternalModule() {
+ setExportContextFlag(file);
+ if (ts.isExternalModule(file)) {
+ bindSourceFileAsExternalModule();
+ }
+ else if (ts.isJsonSourceFile(file)) {
+ bindSourceFileAsExternalModule();
+ // Create symbol equivalent for the module.exports = {}
+ var originalSymbol = file.symbol;
+ declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
+ file.symbol = originalSymbol;
+ }
+ }
+ function bindSourceFileAsExternalModule() {
+ bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"".concat(ts.removeFileExtension(file.fileName), "\""));
+ }
+ function bindExportAssignment(node) {
+ if (!container.symbol || !container.symbol.exports) {
+ // Incorrect export assignment in some sort of block construct
+ bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node));
+ }
+ else {
+ var flags = ts.exportAssignmentIsAlias(node)
+ // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
+ ? 2097152 /* Alias */
+ // An export default clause with any other expression exports a value
+ : 4 /* Property */;
+ // If there is an `export default x;` alias declaration, can't `export default` anything else.
+ // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
+ var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
+ if (node.isExportEquals) {
+ // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
+ ts.setValueDeclaration(symbol, node);
}
- },
- runWithCancellationToken: function (token, callback) {
- try {
- cancellationToken = token;
- return callback(checker);
+ }
+ }
+ function bindNamespaceExportDeclaration(node) {
+ if (node.modifiers && node.modifiers.length) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
+ }
+ var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
+ : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
+ : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
+ : undefined;
+ if (diag) {
+ file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
+ }
+ else {
+ file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
+ declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ }
+ }
+ function bindExportDeclaration(node) {
+ if (!container.symbol || !container.symbol.exports) {
+ // Export * in some sort of block construct
+ bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
+ }
+ else if (!node.exportClause) {
+ // All export * declarations are collected in an __export symbol
+ declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
+ }
+ else if (ts.isNamespaceExport(node.exportClause)) {
+ // declareSymbol walks up parents to find name text, parent _must_ be set
+ // but won't be set by the normal binder walk until `bindChildren` later on.
+ ts.setParent(node.exportClause, node);
+ declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ }
+ }
+ function bindImportClause(node) {
+ if (node.name) {
+ declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
+ }
+ }
+ function setCommonJsModuleIndicator(node) {
+ if (file.externalModuleIndicator) {
+ return false;
+ }
+ if (!file.commonJsModuleIndicator) {
+ file.commonJsModuleIndicator = node;
+ bindSourceFileAsExternalModule();
+ }
+ return true;
+ }
+ function bindObjectDefinePropertyExport(node) {
+ if (!setCommonJsModuleIndicator(node)) {
+ return;
+ }
+ var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
+ if (symbol) {
+ addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
}
- finally {
- cancellationToken = undefined;
+ return symbol;
+ });
+ if (symbol) {
+ var flags = 4 /* Property */ | 1048576 /* ExportValue */;
+ declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
+ }
+ }
+ function bindExportsPropertyAssignment(node) {
+ // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
+ // expression is the declaration
+ if (!setCommonJsModuleIndicator(node)) {
+ return;
+ }
+ var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
+ if (symbol) {
+ addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
}
- },
- getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
- isDeclarationVisible: isDeclarationVisible,
- };
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
- var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
- apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
- apparentArgumentCount = undefined;
- return res;
+ return symbol;
+ });
+ if (symbol) {
+ var isAlias = ts.isAliasableExpression(node.right) && (ts.isExportsIdentifier(node.left.expression) || ts.isModuleExportsAccessExpression(node.left.expression));
+ var flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
+ ts.setParent(node.left, node);
+ declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
+ }
}
- var tupleTypes = ts.createMap();
- var unionTypes = ts.createMap();
- var intersectionTypes = ts.createMap();
- var literalTypes = ts.createMap();
- var indexedAccessTypes = ts.createMap();
- var substitutionTypes = ts.createMap();
- var evolvingArrayTypes = [];
- var undefinedProperties = ts.createMap();
- var unknownSymbol = createSymbol(4 /* Property */, "unknown");
- var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
- var anyType = createIntrinsicType(1 /* Any */, "any");
- var autoType = createIntrinsicType(1 /* Any */, "any");
- var wildcardType = createIntrinsicType(1 /* Any */, "any");
- var errorType = createIntrinsicType(1 /* Any */, "error");
- var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
- var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
- var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
- var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
- var stringType = createIntrinsicType(4 /* String */, "string");
- var numberType = createIntrinsicType(8 /* Number */, "number");
- var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
- var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
- var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
- var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
- var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
- trueType.regularType = regularTrueType;
- trueType.freshType = trueType;
- regularTrueType.regularType = regularTrueType;
- regularTrueType.freshType = trueType;
- falseType.regularType = regularFalseType;
- falseType.freshType = falseType;
- regularFalseType.regularType = regularFalseType;
- regularFalseType.freshType = falseType;
- var booleanType = createBooleanType([regularFalseType, regularTrueType]);
- // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
- // (The union is cached, so simply doing the marking here is sufficient)
- createBooleanType([regularFalseType, trueType]);
- createBooleanType([falseType, regularTrueType]);
- createBooleanType([falseType, trueType]);
- var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
- var voidType = createIntrinsicType(16384 /* Void */, "void");
- var neverType = createIntrinsicType(131072 /* Never */, "never");
- var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
- var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
- var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
- var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
- var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
- var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
- var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
- var numberOrBigIntType = getUnionType([numberType, bigintType]);
- var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
- var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
- var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
- var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
- emptyTypeLiteralSymbol.members = ts.createSymbolTable();
- var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- emptyGenericType.instantiations = ts.createMap();
- var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
- // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
- var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- var markerSuperType = createTypeParameter();
- var markerSubType = createTypeParameter();
- markerSubType.constraint = markerSuperType;
- var markerOtherType = createTypeParameter();
- var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType);
- var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
- var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
- var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
- var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
- var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
- var noIterationTypes = {
- get yieldType() { return ts.Debug.fail("Not supported"); },
- get returnType() { return ts.Debug.fail("Not supported"); },
- get nextType() { return ts.Debug.fail("Not supported"); },
- };
- var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
- var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
- var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
- var asyncIterationTypesResolver = {
- iterableCacheKey: "iterationTypesOfAsyncIterable",
- iteratorCacheKey: "iterationTypesOfAsyncIterator",
- iteratorSymbolName: "asyncIterator",
- getGlobalIteratorType: getGlobalAsyncIteratorType,
- getGlobalIterableType: getGlobalAsyncIterableType,
- getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
- getGlobalGeneratorType: getGlobalAsyncGeneratorType,
- resolveIterationType: getAwaitedType,
- mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
- mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
- mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property,
- };
- var syncIterationTypesResolver = {
- iterableCacheKey: "iterationTypesOfIterable",
- iteratorCacheKey: "iterationTypesOfIterator",
- iteratorSymbolName: "iterator",
- getGlobalIteratorType: getGlobalIteratorType,
- getGlobalIterableType: getGlobalIterableType,
- getGlobalIterableIteratorType: getGlobalIterableIteratorType,
- getGlobalGeneratorType: getGlobalGeneratorType,
- resolveIterationType: function (type, _errorNode) { return type; },
- mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
- mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
- mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
- };
- /** Key is "/path/to/a.ts|/path/to/b.ts". */
- var amalgamatedDuplicates;
- var reverseMappedCache = ts.createMap();
- var ambientModulesCache;
- /**
- * List of every ambient module with a "*" wildcard.
- * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
- * This is only used if there is no exact match.
- */
- var patternAmbientModules;
- var patternAmbientModuleAugmentations;
- var globalObjectType;
- var globalFunctionType;
- var globalCallableFunctionType;
- var globalNewableFunctionType;
- var globalArrayType;
- var globalReadonlyArrayType;
- var globalStringType;
- var globalNumberType;
- var globalBooleanType;
- var globalRegExpType;
- var globalThisType;
- var anyArrayType;
- var autoArrayType;
- var anyReadonlyArrayType;
- var deferredGlobalNonNullableTypeAlias;
- // The library files are only loaded when the feature is used.
- // This allows users to just specify library files they want to used through --lib
- // and they will not get an error from not having unrelated library files
- var deferredGlobalESSymbolConstructorSymbol;
- var deferredGlobalESSymbolType;
- var deferredGlobalTypedPropertyDescriptorType;
- var deferredGlobalPromiseType;
- var deferredGlobalPromiseLikeType;
- var deferredGlobalPromiseConstructorSymbol;
- var deferredGlobalPromiseConstructorLikeType;
- var deferredGlobalIterableType;
- var deferredGlobalIteratorType;
- var deferredGlobalIterableIteratorType;
- var deferredGlobalGeneratorType;
- var deferredGlobalIteratorYieldResultType;
- var deferredGlobalIteratorReturnResultType;
- var deferredGlobalAsyncIterableType;
- var deferredGlobalAsyncIteratorType;
- var deferredGlobalAsyncIterableIteratorType;
- var deferredGlobalAsyncGeneratorType;
- var deferredGlobalTemplateStringsArrayType;
- var deferredGlobalImportMetaType;
- var deferredGlobalExtractSymbol;
- var deferredGlobalOmitSymbol;
- var deferredGlobalBigIntType;
- var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
- var flowLoopStart = 0;
- var flowLoopCount = 0;
- var sharedFlowCount = 0;
- var flowAnalysisDisabled = false;
- var flowInvocationCount = 0;
- var lastFlowNode;
- var lastFlowNodeReachable;
- var flowTypeCache;
- var emptyStringType = getLiteralType("");
- var zeroType = getLiteralType(0);
- var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
- var resolutionTargets = [];
- var resolutionResults = [];
- var resolutionPropertyNames = [];
- var suggestionCount = 0;
- var maximumSuggestionCount = 10;
- var mergedSymbols = [];
- var symbolLinks = [];
- var nodeLinks = [];
- var flowLoopCaches = [];
- var flowLoopNodes = [];
- var flowLoopKeys = [];
- var flowLoopTypes = [];
- var sharedFlowNodes = [];
- var sharedFlowTypes = [];
- var flowNodeReachable = [];
- var potentialThisCollisions = [];
- var potentialNewTargetCollisions = [];
- var potentialWeakMapCollisions = [];
- var awaitedTypeStack = [];
- var diagnostics = ts.createDiagnosticCollection();
- var suggestionDiagnostics = ts.createDiagnosticCollection();
- var typeofTypesByName = ts.createMapFromTemplate({
- string: stringType,
- number: numberType,
- bigint: bigintType,
- boolean: booleanType,
- symbol: esSymbolType,
- undefined: undefinedType
- });
- var typeofType = createTypeofType();
- var _jsxNamespace;
- var _jsxFactoryEntity;
- var outofbandVarianceMarkerHandler;
- var subtypeRelation = ts.createMap();
- var strictSubtypeRelation = ts.createMap();
- var assignableRelation = ts.createMap();
- var comparableRelation = ts.createMap();
- var identityRelation = ts.createMap();
- var enumRelation = ts.createMap();
- var builtinGlobals = ts.createSymbolTable();
- builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
- initializeTypeChecker();
- return checker;
- function getJsxNamespace(location) {
- if (location) {
- var file = ts.getSourceFileOfNode(location);
- if (file) {
- if (file.localJsxNamespace) {
- return file.localJsxNamespace;
+ function bindModuleExportsAssignment(node) {
+ // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
+ // is still pointing to 'module.exports'.
+ // We do not want to consider this as 'export=' since a module can have only one of these.
+ // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
+ if (!setCommonJsModuleIndicator(node)) {
+ return;
+ }
+ var assignedExpression = ts.getRightMostAssignedExpression(node.right);
+ if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
+ return;
+ }
+ if (ts.isObjectLiteralExpression(assignedExpression) && ts.every(assignedExpression.properties, ts.isShorthandPropertyAssignment)) {
+ ts.forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
+ return;
+ }
+ // 'module.exports = expr' assignment
+ var flags = ts.exportAssignmentIsAlias(node)
+ ? 2097152 /* Alias */
+ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
+ var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
+ ts.setValueDeclaration(symbol, node);
+ }
+ function bindExportAssignedObjectMemberAlias(node) {
+ declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
+ }
+ function bindThisPropertyAssignment(node) {
+ ts.Debug.assert(ts.isInJSFile(node));
+ // private identifiers *must* be declared (even in JS files)
+ var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
+ || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
+ if (hasPrivateIdentifier) {
+ return;
+ }
+ var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
+ switch (thisContainer.kind) {
+ case 255 /* FunctionDeclaration */:
+ case 212 /* FunctionExpression */:
+ var constructorSymbol = thisContainer.symbol;
+ // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
+ if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 63 /* EqualsToken */) {
+ var l = thisContainer.parent.left;
+ if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
+ constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
+ }
}
- var jsxPragma = file.pragmas.get("jsx");
- if (jsxPragma) {
- var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
- file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
- ts.visitNode(file.localJsxFactory, markAsSynthetic);
- if (file.localJsxFactory) {
- return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
+ if (constructorSymbol && constructorSymbol.valueDeclaration) {
+ // Declare a 'member' if the container is an ES5 class or ES6 constructor
+ constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
+ // It's acceptable for multiple 'this' assignments of the same identifier to occur
+ if (ts.hasDynamicName(node)) {
+ bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol, constructorSymbol.members);
+ }
+ else {
+ declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
}
+ addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
}
- }
- }
- if (!_jsxNamespace) {
- _jsxNamespace = "React";
- if (compilerOptions.jsxFactory) {
- _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
- ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
- if (_jsxFactoryEntity) {
- _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
+ break;
+ case 170 /* Constructor */:
+ case 166 /* PropertyDeclaration */:
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 169 /* ClassStaticBlockDeclaration */:
+ // this.foo assignment in a JavaScript class
+ // Bind this property to the containing class
+ var containingClass = thisContainer.parent;
+ var symbolTable = ts.isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members;
+ if (ts.hasDynamicName(node)) {
+ bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable);
}
+ else {
+ declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
+ }
+ break;
+ case 303 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (ts.hasDynamicName(node)) {
+ break;
+ }
+ else if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
+ }
+ break;
+ default:
+ ts.Debug.failBadSyntaxKind(thisContainer);
+ }
+ }
+ function bindDynamicallyNamedThisPropertyAssignment(node, symbol, symbolTable) {
+ declareSymbol(symbolTable, symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true, /*isComputedName*/ true);
+ addLateBoundAssignmentDeclarationToSymbol(node, symbol);
+ }
+ function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
+ if (symbol) {
+ (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = new ts.Map())).set(ts.getNodeId(node), node);
+ }
+ }
+ function bindSpecialPropertyDeclaration(node) {
+ if (node.expression.kind === 108 /* ThisKeyword */) {
+ bindThisPropertyAssignment(node);
+ }
+ else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 303 /* SourceFile */) {
+ if (ts.isPrototypeAccess(node.expression)) {
+ bindPrototypePropertyAssignment(node, node.parent);
+ }
+ else {
+ bindStaticPropertyAssignment(node);
}
- else if (compilerOptions.reactNamespace) {
- _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
- }
- }
- if (!_jsxFactoryEntity) {
- _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
}
- return _jsxNamespace;
- function markAsSynthetic(node) {
- node.pos = -1;
- node.end = -1;
- return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
+ }
+ /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
+ function bindPrototypeAssignment(node) {
+ ts.setParent(node.left, node);
+ ts.setParent(node.right, node);
+ bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
+ }
+ function bindObjectDefinePrototypeProperty(node) {
+ var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
+ if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
+ // Ensure the namespace symbol becomes class-like
+ addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
}
+ bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
}
- function getEmitResolver(sourceFile, cancellationToken) {
- // Ensure we have all the type information in place for this file so that all the
- // emitter questions of this resolver will return the right information.
- getDiagnostics(sourceFile, cancellationToken);
- return emitResolver;
+ /**
+ * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
+ * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
+ */
+ function bindPrototypePropertyAssignment(lhs, parent) {
+ // Look up the function in the local scope, since prototype assignments should
+ // follow the function declaration
+ var classPrototype = lhs.expression;
+ var constructorFunction = classPrototype.expression;
+ // Fix up parent pointers since we're going to use these nodes before we bind into them
+ ts.setParent(constructorFunction, classPrototype);
+ ts.setParent(classPrototype, lhs);
+ ts.setParent(lhs, parent);
+ bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
}
- function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
- var diagnostic = location
- ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
- : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
- var existing = diagnostics.lookup(diagnostic);
- if (existing) {
- return existing;
+ function bindObjectDefinePropertyAssignment(node) {
+ var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
+ var isToplevel = node.parent.parent.kind === 303 /* SourceFile */;
+ namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
+ bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
+ }
+ function bindSpecialPropertyAssignment(node) {
+ var _a;
+ // Class declarations in Typescript do not allow property declarations
+ var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer);
+ if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
+ return;
+ }
+ var rootExpr = ts.getLeftmostAccessExpression(node.left);
+ if (ts.isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) === null || _a === void 0 ? void 0 : _a.flags) & 2097152 /* Alias */) {
+ return;
+ }
+ // Fix up parent pointers since we're going to use these nodes before we bind into them
+ ts.setParent(node.left, node);
+ ts.setParent(node.right, node);
+ if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
+ // This can be an alias for the 'exports' or 'module.exports' names, e.g.
+ // var util = module.exports;
+ // util.property = function ...
+ bindExportsPropertyAssignment(node);
+ }
+ else if (ts.hasDynamicName(node)) {
+ bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
+ var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
+ addLateBoundAssignmentDeclarationToSymbol(node, sym);
}
else {
- diagnostics.add(diagnostic);
- return diagnostic;
+ bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
}
}
- function error(location, message, arg0, arg1, arg2, arg3) {
- var diagnostic = location
- ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
- : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
- diagnostics.add(diagnostic);
- return diagnostic;
+ /**
+ * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared.
+ * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
+ */
+ function bindStaticPropertyAssignment(node) {
+ ts.Debug.assert(!ts.isIdentifier(node));
+ ts.setParent(node.expression, node);
+ bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
}
- function addErrorOrSuggestion(isError, diagnostic) {
- if (isError) {
- diagnostics.add(diagnostic);
+ function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
+ if ((namespaceSymbol === null || namespaceSymbol === void 0 ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
+ return namespaceSymbol;
}
- else {
- suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
+ if (isToplevel && !isPrototypeProperty) {
+ // make symbols or add declarations for intermediate containers
+ var flags_2 = 1536 /* Module */ | 67108864 /* Assignment */;
+ var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
+ namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
+ if (symbol) {
+ addDeclarationToSymbol(symbol, id, flags_2);
+ return symbol;
+ }
+ else {
+ var table = parent ? parent.exports :
+ file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
+ return declareSymbol(table, parent, id, flags_2, excludeFlags_1);
+ }
+ });
}
+ if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
+ addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
+ }
+ return namespaceSymbol;
}
- function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
- addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
- }
- function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
- var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
- if (maybeMissingAwait) {
- var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
- ts.addRelatedInfo(diagnostic, related);
+ function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
+ if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
+ return;
}
- return diagnostic;
+ // Set up the members collection if it doesn't exist already
+ var symbolTable = isPrototypeProperty ?
+ (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
+ (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
+ var includes = 0 /* None */;
+ var excludes = 0 /* None */;
+ // Method-like
+ if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
+ includes = 8192 /* Method */;
+ excludes = 103359 /* MethodExcludes */;
+ }
+ // Maybe accessor-like
+ else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
+ if (ts.some(declaration.arguments[2].properties, function (p) {
+ var id = ts.getNameOfDeclaration(p);
+ return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
+ })) {
+ // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
+ // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
+ includes |= 65536 /* SetAccessor */ | 4 /* Property */;
+ excludes |= 78783 /* SetAccessorExcludes */;
+ }
+ if (ts.some(declaration.arguments[2].properties, function (p) {
+ var id = ts.getNameOfDeclaration(p);
+ return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
+ })) {
+ includes |= 32768 /* GetAccessor */ | 4 /* Property */;
+ excludes |= 46015 /* GetAccessorExcludes */;
+ }
+ }
+ if (includes === 0 /* None */) {
+ includes = 4 /* Property */;
+ excludes = 0 /* PropertyExcludes */;
+ }
+ declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
}
- function createSymbol(flags, name, checkFlags) {
- symbolCount++;
- var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
- symbol.checkFlags = checkFlags || 0;
- return symbol;
+ function isTopLevelNamespaceAssignment(propertyAccess) {
+ return ts.isBinaryExpression(propertyAccess.parent)
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 303 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 303 /* SourceFile */;
}
- function getExcludedSymbolFlags(flags) {
- var result = 0;
- if (flags & 2 /* BlockScopedVariable */)
- result |= 111551 /* BlockScopedVariableExcludes */;
- if (flags & 1 /* FunctionScopedVariable */)
- result |= 111550 /* FunctionScopedVariableExcludes */;
- if (flags & 4 /* Property */)
- result |= 0 /* PropertyExcludes */;
- if (flags & 8 /* EnumMember */)
- result |= 900095 /* EnumMemberExcludes */;
- if (flags & 16 /* Function */)
- result |= 110991 /* FunctionExcludes */;
- if (flags & 32 /* Class */)
- result |= 899503 /* ClassExcludes */;
- if (flags & 64 /* Interface */)
- result |= 788872 /* InterfaceExcludes */;
- if (flags & 256 /* RegularEnum */)
- result |= 899327 /* RegularEnumExcludes */;
- if (flags & 128 /* ConstEnum */)
- result |= 899967 /* ConstEnumExcludes */;
- if (flags & 512 /* ValueModule */)
- result |= 110735 /* ValueModuleExcludes */;
- if (flags & 8192 /* Method */)
- result |= 103359 /* MethodExcludes */;
- if (flags & 32768 /* GetAccessor */)
- result |= 46015 /* GetAccessorExcludes */;
- if (flags & 65536 /* SetAccessor */)
- result |= 78783 /* SetAccessorExcludes */;
- if (flags & 262144 /* TypeParameter */)
- result |= 526824 /* TypeParameterExcludes */;
- if (flags & 524288 /* TypeAlias */)
- result |= 788968 /* TypeAliasExcludes */;
- if (flags & 2097152 /* Alias */)
- result |= 2097152 /* AliasExcludes */;
- return result;
+ function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
+ var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer);
+ var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
+ namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
+ bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
- function recordMergedSymbol(target, source) {
- if (!source.mergeId) {
- source.mergeId = nextMergeId;
- nextMergeId++;
+ /**
+ * Javascript expando values are:
+ * - Functions
+ * - classes
+ * - namespaces
+ * - variables initialized with function expressions
+ * - with class expressions
+ * - with empty object literals
+ * - with non-empty object literals if assigned to the prototype property
+ */
+ function isExpandoSymbol(symbol) {
+ if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
+ return true;
}
- mergedSymbols[source.mergeId] = target;
+ var node = symbol.valueDeclaration;
+ if (node && ts.isCallExpression(node)) {
+ return !!ts.getAssignedExpandoInitializer(node);
+ }
+ var init = !node ? undefined :
+ ts.isVariableDeclaration(node) ? node.initializer :
+ ts.isBinaryExpression(node) ? node.right :
+ ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
+ undefined;
+ init = init && ts.getRightMostAssignedExpression(init);
+ if (init) {
+ var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
+ return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
+ }
+ return false;
}
- function cloneSymbol(symbol) {
- var result = createSymbol(symbol.flags, symbol.escapedName);
- result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
- result.parent = symbol.parent;
- if (symbol.valueDeclaration)
- result.valueDeclaration = symbol.valueDeclaration;
- if (symbol.constEnumOnlyModule)
- result.constEnumOnlyModule = true;
- if (symbol.members)
- result.members = ts.cloneMap(symbol.members);
- if (symbol.exports)
- result.exports = ts.cloneMap(symbol.exports);
- recordMergedSymbol(result, symbol);
- return result;
+ function getParentOfBinaryExpression(expr) {
+ while (ts.isBinaryExpression(expr.parent)) {
+ expr = expr.parent;
+ }
+ return expr.parent;
}
- /**
- * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
- * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
- */
- function mergeSymbol(target, source, unidirectional) {
- if (unidirectional === void 0) { unidirectional = false; }
- if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
- (source.flags | target.flags) & 67108864 /* Assignment */) {
- if (source === target) {
- // This can happen when an export assigned namespace exports something also erroneously exported at the top level
- // See `declarationFileNoCrashOnExtraExportModifier` for an example
- return target;
+ function lookupSymbolForPropertyAccess(node, lookupContainer) {
+ if (lookupContainer === void 0) { lookupContainer = container; }
+ if (ts.isIdentifier(node)) {
+ return lookupSymbolForName(lookupContainer, node.escapedText);
+ }
+ else {
+ var symbol = lookupSymbolForPropertyAccess(node.expression);
+ return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
+ }
+ }
+ function forEachIdentifierInEntityName(e, parent, action) {
+ if (isExportsOrModuleExportsOrAlias(file, e)) {
+ return file.symbol;
+ }
+ else if (ts.isIdentifier(e)) {
+ return action(e, lookupSymbolForPropertyAccess(e), parent);
+ }
+ else {
+ var s = forEachIdentifierInEntityName(e.expression, parent, action);
+ var name = ts.getNameOrArgument(e);
+ // unreachable
+ if (ts.isPrivateIdentifier(name)) {
+ ts.Debug.fail("unexpected PrivateIdentifier");
}
- if (!(target.flags & 33554432 /* Transient */)) {
- var resolvedTarget = resolveSymbol(target);
- if (resolvedTarget === unknownSymbol) {
- return source;
- }
- target = cloneSymbol(resolvedTarget);
+ return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
+ }
+ }
+ function bindCallExpression(node) {
+ // We're only inspecting call expressions to detect CommonJS modules, so we can skip
+ // this check if we've already seen the module indicator
+ if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
+ setCommonJsModuleIndicator(node);
+ }
+ }
+ function bindClassLikeDeclaration(node) {
+ if (node.kind === 256 /* ClassDeclaration */) {
+ bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
+ }
+ else {
+ var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
+ bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
+ // Add name of class expression into the map for semantic classifier
+ if (node.name) {
+ classifiableNames.add(node.name.escapedText);
}
- // Javascript static-property-assignment declarations always merge, even though they are also values
- if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
- // reset flag when merging instantiated module into value module that has only const enums
- target.constEnumOnlyModule = false;
+ }
+ var symbol = node.symbol;
+ // TypeScript 1.0 spec (April 2014): 8.4
+ // Every class automatically contains a static property member named 'prototype', the
+ // type of which is an instantiation of the class type with type Any supplied as a type
+ // argument for each type parameter. It is an error to explicitly declare a static
+ // property member with the name 'prototype'.
+ //
+ // Note: we check for this here because this class may be merging into a module. The
+ // module might have an exported variable called 'prototype'. We can't allow that as
+ // that would clash with the built-in 'prototype' for the class.
+ var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
+ var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
+ if (symbolExport) {
+ if (node.name) {
+ ts.setParent(node.name, node);
}
- target.flags |= source.flags;
- if (source.valueDeclaration) {
- ts.setValueDeclaration(target, source.valueDeclaration);
+ file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
+ }
+ symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
+ prototypeSymbol.parent = symbol;
+ }
+ function bindEnumDeclaration(node) {
+ return ts.isEnumConst(node)
+ ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
+ : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
+ }
+ function bindVariableDeclarationOrBindingElement(node) {
+ if (inStrictMode) {
+ checkStrictModeEvalOrArguments(node, node.name);
+ }
+ if (!ts.isBindingPattern(node.name)) {
+ if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) {
+ declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
}
- ts.addRange(target.declarations, source.declarations);
- if (source.members) {
- if (!target.members)
- target.members = ts.createSymbolTable();
- mergeSymbolTable(target.members, source.members, unidirectional);
+ else if (ts.isBlockOrCatchScoped(node)) {
+ bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
}
- if (source.exports) {
- if (!target.exports)
- target.exports = ts.createSymbolTable();
- mergeSymbolTable(target.exports, source.exports, unidirectional);
+ else if (ts.isParameterDeclaration(node)) {
+ // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
+ // because its parent chain has already been set up, since parents are set before descending into children.
+ //
+ // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
+ // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
+ // For example:
+ // function foo([a,a]) {} // Duplicate Identifier error
+ // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
+ // // which correctly set excluded symbols
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
}
- if (!unidirectional) {
- recordMergedSymbol(target, source);
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
}
}
- else if (target.flags & 1024 /* NamespaceModule */) {
- // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
- // as we will already report a "Declaration name conflicts..." error, and this error
- // won't make much sense.
- if (target !== globalThisSymbol) {
- error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
- }
+ }
+ function bindParameter(node) {
+ if (node.kind === 338 /* JSDocParameterTag */ && container.kind !== 321 /* JSDocSignature */) {
+ return;
}
- else { // error
- var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
- var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
- var message = isEitherEnum
- ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
- : isEitherBlockScoped_1
- ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
- : ts.Diagnostics.Duplicate_identifier_0;
- var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
- var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
- var symbolName_1 = symbolToString(source);
- // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
- if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
- var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
- var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
- var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
- return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
- });
- var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
- return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
- });
- addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
- addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
- }
- else {
- addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
- addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
- }
+ if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
+ // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
+ // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
+ checkStrictModeEvalOrArguments(node, node.name);
}
- return target;
- function addDuplicateLocations(locs, symbol) {
- for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
- var decl = _a[_i];
- ts.pushIfUnique(locs, decl);
- }
+ if (ts.isBindingPattern(node.name)) {
+ bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
}
- }
- function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
- ts.forEach(target.declarations, function (node) {
- addDuplicateDeclarationError(node, message, symbolName, source.declarations);
- });
- }
- function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
- var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
- var err = lookupOrIssueError(errorNode, message, symbolName);
- var _loop_6 = function (relatedNode) {
- var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
- if (adjustedNode === errorNode)
- return "continue";
- err.relatedInformation = err.relatedInformation || [];
- var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
- var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
- if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; }))
- return "continue";
- ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
- };
- for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
- var relatedNode = _a[_i];
- _loop_6(relatedNode);
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
+ }
+ // If this is a property-parameter, then also declare the property symbol into the
+ // containing class.
+ if (ts.isParameterPropertyDeclaration(node, node.parent)) {
+ var classDeclaration = node.parent.parent;
+ declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
}
}
- function combineSymbolTables(first, second) {
- if (!ts.hasEntries(first))
- return second;
- if (!ts.hasEntries(second))
- return first;
- var combined = ts.createSymbolTable();
- mergeSymbolTable(combined, first);
- mergeSymbolTable(combined, second);
- return combined;
- }
- function mergeSymbolTable(target, source, unidirectional) {
- if (unidirectional === void 0) { unidirectional = false; }
- source.forEach(function (sourceSymbol, id) {
- var targetSymbol = target.get(id);
- target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
- });
- }
- function mergeModuleAugmentation(moduleName) {
- var _a, _b;
- var moduleAugmentation = moduleName.parent;
- if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
- // this is a combined symbol for multiple augmentations within the same file.
- // its symbol already has accumulated information for all declarations
- // so we need to add it just once - do the work only for first declaration
- ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
- return;
+ function bindFunctionDeclaration(node) {
+ if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
+ if (ts.isAsyncFunction(node)) {
+ emitFlags |= 2048 /* HasAsyncFunctions */;
+ }
}
- if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
- mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
+ checkStrictModeFunctionName(node);
+ if (inStrictMode) {
+ checkStrictModeFunctionDeclaration(node);
+ bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
}
else {
- // find a module that about to be augmented
- // do not validate names of augmentations that are defined in ambient context
- var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
- ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
- : undefined;
- var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
- if (!mainModule_1) {
- return;
+ declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
+ }
+ }
+ function bindFunctionExpression(node) {
+ if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
+ if (ts.isAsyncFunction(node)) {
+ emitFlags |= 2048 /* HasAsyncFunctions */;
}
- // obtain item referenced by 'export='
- mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
- if (mainModule_1.flags & 1920 /* Namespace */) {
- // If we're merging an augmentation to a pattern ambient module, we want to
- // perform the merge unidirectionally from the augmentation ('a.foo') to
- // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
- // all the exports both from the pattern and from the augmentation, but
- // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
- if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
- var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
- if (!patternAmbientModuleAugmentations) {
- patternAmbientModuleAugmentations = ts.createMap();
- }
- // moduleName will be a StringLiteral since this is not `declare global`.
- patternAmbientModuleAugmentations.set(moduleName.text, merged);
- }
- else {
- if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) {
- // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
- var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
- for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
- var _d = _c[_i], key = _d[0], value = _d[1];
- if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
- mergeSymbol(resolvedExports.get(key), value);
- }
- }
- }
- mergeSymbol(mainModule_1, moduleAugmentation.symbol);
+ }
+ if (currentFlow) {
+ node.flowNode = currentFlow;
+ }
+ checkStrictModeFunctionName(node);
+ var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
+ return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
+ }
+ function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
+ if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
+ emitFlags |= 2048 /* HasAsyncFunctions */;
+ }
+ if (currentFlow && ts.isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
+ node.flowNode = currentFlow;
+ }
+ return ts.hasDynamicName(node)
+ ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
+ : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ }
+ function getInferTypeContainer(node) {
+ var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
+ return extendsType && extendsType.parent;
+ }
+ function bindTypeParameter(node) {
+ if (ts.isJSDocTemplateTag(node.parent)) {
+ var container_1 = ts.getEffectiveContainerForJSDocTemplateTag(node.parent);
+ if (container_1) {
+ if (!container_1.locals) {
+ container_1.locals = ts.createSymbolTable();
}
+ declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
}
else {
- // moduleName will be a StringLiteral since this is not `declare global`.
- error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
+ declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
}
}
- }
- function addToSymbolTable(target, source, message) {
- source.forEach(function (sourceSymbol, id) {
- var targetSymbol = target.get(id);
- if (targetSymbol) {
- // Error on redeclarations
- ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
+ else if (node.parent.kind === 189 /* InferType */) {
+ var container_2 = getInferTypeContainer(node.parent);
+ if (container_2) {
+ if (!container_2.locals) {
+ container_2.locals = ts.createSymbolTable();
+ }
+ declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
}
else {
- target.set(id, sourceSymbol);
+ bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
}
- });
- function addDeclarationDiagnostic(id, message) {
- return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
}
}
- function getSymbolLinks(symbol) {
- if (symbol.flags & 33554432 /* Transient */)
- return symbol;
- var id = getSymbolId(symbol);
- return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
+ // reachability checks
+ function shouldReportErrorOnModuleDeclaration(node) {
+ var instanceState = getModuleInstanceState(node);
+ return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options));
}
- function getNodeLinks(node) {
- var nodeId = getNodeId(node);
- return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
+ function checkUnreachable(node) {
+ if (!(currentFlow.flags & 1 /* Unreachable */)) {
+ return false;
+ }
+ if (currentFlow === unreachableFlow) {
+ var reportError =
+ // report error on all statements except empty ones
+ (ts.isStatementButNotDeclaration(node) && node.kind !== 235 /* EmptyStatement */) ||
+ // report error on class declarations
+ node.kind === 256 /* ClassDeclaration */ ||
+ // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
+ (node.kind === 260 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
+ if (reportError) {
+ currentFlow = reportedUnreachableFlow;
+ if (!options.allowUnreachableCode) {
+ // unreachable code is reported if
+ // - user has explicitly asked about it AND
+ // - statement is in not ambient context (statements in ambient context is already an error
+ // so we should not report extras) AND
+ // - node is not variable statement OR
+ // - node is block scoped variable statement OR
+ // - node is not block scoped variable statement and at least one variable declaration has initializer
+ // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
+ // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
+ var isError_1 = ts.unreachableCodeIsError(options) &&
+ !(node.flags & 8388608 /* Ambient */) &&
+ (!ts.isVariableStatement(node) ||
+ !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
+ node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
+ eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
+ }
+ }
+ }
+ return true;
}
- function isGlobalSourceFile(node) {
- return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ }
+ function eachUnreachableRange(node, cb) {
+ if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
+ var statements = node.parent.statements;
+ var slice_1 = ts.sliceAfter(statements, node);
+ ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
}
- function getSymbol(symbols, name, meaning) {
- if (meaning) {
- var symbol = getMergedSymbol(symbols.get(name));
- if (symbol) {
- ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
- if (symbol.flags & meaning) {
- return symbol;
- }
- if (symbol.flags & 2097152 /* Alias */) {
- var target = resolveAlias(symbol);
- // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
- if (target === unknownSymbol || target.flags & meaning) {
- return symbol;
- }
+ else {
+ cb(node, node);
+ }
+ }
+ // As opposed to a pure declaration like an `interface`
+ function isExecutableStatement(s) {
+ // Don't remove statements that can validly be used before they appear.
+ return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
+ // `var x;` may declare a variable used above
+ !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
+ }
+ function isPurelyTypeDeclaration(s) {
+ switch (s.kind) {
+ case 257 /* InterfaceDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ return true;
+ case 260 /* ModuleDeclaration */:
+ return getModuleInstanceState(s) !== 1 /* Instantiated */;
+ case 259 /* EnumDeclaration */:
+ return ts.hasSyntacticModifier(s, 2048 /* Const */);
+ default:
+ return false;
+ }
+ }
+ function isExportsOrModuleExportsOrAlias(sourceFile, node) {
+ var i = 0;
+ var q = [node];
+ while (q.length && i < 100) {
+ i++;
+ node = q.shift();
+ if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
+ return true;
+ }
+ else if (ts.isIdentifier(node)) {
+ var symbol = lookupSymbolForName(sourceFile, node.escapedText);
+ if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
+ var init = symbol.valueDeclaration.initializer;
+ q.push(init);
+ if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
+ q.push(init.left);
+ q.push(init.right);
}
}
}
- // return undefined if we can't find a symbol.
}
- /**
- * Get symbols that represent parameter-property-declaration as parameter and as property declaration
- * @param parameter a parameterDeclaration node
- * @param parameterName a name of the parameter to get the symbols for.
- * @return a tuple of two symbols
- */
- function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
- var constructorDeclaration = parameter.parent;
- var classDeclaration = parameter.parent.parent;
- var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
- var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
- if (parameterSymbol && propertySymbol) {
- return [parameterSymbol, propertySymbol];
- }
- return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
+ return false;
+ }
+ ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
+ function lookupSymbolForName(container, name) {
+ var local = container.locals && container.locals.get(name);
+ if (local) {
+ return local.exportSymbol || local;
}
- function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
- var declarationFile = ts.getSourceFileOfNode(declaration);
- var useFile = ts.getSourceFileOfNode(usage);
- var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
- if (declarationFile !== useFile) {
- if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
- (!compilerOptions.outFile && !compilerOptions.out) ||
- isInTypeQuery(usage) ||
- declaration.flags & 8388608 /* Ambient */) {
- // nodes are in different files and order cannot be determined
- return true;
+ if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
+ return container.jsGlobalAugmentations.get(name);
+ }
+ return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
+ }
+})(ts || (ts = {}));
+/** @internal */
+var ts;
+(function (ts) {
+ function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
+ return getSymbolWalker;
+ function getSymbolWalker(accept) {
+ if (accept === void 0) { accept = function () { return true; }; }
+ var visitedTypes = []; // Sparse array from id to type
+ var visitedSymbols = []; // Sparse array from id to symbol
+ return {
+ walkType: function (type) {
+ try {
+ visitType(type);
+ return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
+ }
+ finally {
+ ts.clear(visitedTypes);
+ ts.clear(visitedSymbols);
+ }
+ },
+ walkSymbol: function (symbol) {
+ try {
+ visitSymbol(symbol);
+ return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
+ }
+ finally {
+ ts.clear(visitedTypes);
+ ts.clear(visitedSymbols);
+ }
+ },
+ };
+ function visitType(type) {
+ if (!type) {
+ return;
}
- // declaration is after usage
- // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
- if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
- return true;
+ if (visitedTypes[type.id]) {
+ return;
}
- var sourceFiles = host.getSourceFiles();
- return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
- }
- if (declaration.pos <= usage.pos) {
- // declaration is before usage
- if (declaration.kind === 191 /* BindingElement */) {
- // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
- var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
- if (errorBindingElement) {
- return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
- declaration.pos < errorBindingElement.pos;
+ visitedTypes[type.id] = type;
+ // Reuse visitSymbol to visit the type's symbol,
+ // but be sure to bail on recuring into the type if accept declines the symbol.
+ var shouldBail = visitSymbol(type.symbol);
+ if (shouldBail)
+ return;
+ // Visit the type's related types, if any
+ if (type.flags & 524288 /* Object */) {
+ var objectType = type;
+ var objectFlags = objectType.objectFlags;
+ if (objectFlags & 4 /* Reference */) {
+ visitTypeReference(type);
+ }
+ if (objectFlags & 32 /* Mapped */) {
+ visitMappedType(type);
+ }
+ if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
+ visitInterfaceType(type);
+ }
+ if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
+ visitObjectType(objectType);
}
- // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
- return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
}
- else if (declaration.kind === 242 /* VariableDeclaration */) {
- // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
- return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
+ if (type.flags & 262144 /* TypeParameter */) {
+ visitTypeParameter(type);
}
- else if (ts.isClassDeclaration(declaration)) {
- // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
- return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
+ if (type.flags & 3145728 /* UnionOrIntersection */) {
+ visitUnionOrIntersectionType(type);
}
- else if (ts.isPropertyDeclaration(declaration)) {
- // still might be illegal if a self-referencing property initializer (eg private x = this.x)
- return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
+ if (type.flags & 4194304 /* Index */) {
+ visitIndexType(type);
}
- else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
- // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
- return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
- && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
- && isUsedInFunctionOrInstanceProperty(usage, declaration));
+ if (type.flags & 8388608 /* IndexedAccess */) {
+ visitIndexedAccessType(type);
}
- return true;
}
- // declaration is after usage, but it can still be legal if usage is deferred:
- // 1. inside an export specifier
- // 2. inside a function
- // 3. inside an instance property initializer, a reference to a non-instance property
- // (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
- // 4. inside a static property initializer, a reference to a static method in the same class
- // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
- // or if usage is in a type context:
- // 1. inside a type query (typeof in type position)
- // 2. inside a jsdoc comment
- if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
- // export specifiers do not use the variable, they only make it available for use
- return true;
+ function visitTypeReference(type) {
+ visitType(type.target);
+ ts.forEach(getTypeArguments(type), visitType);
}
- // When resolving symbols for exports, the `usage` location passed in can be the export site directly
- if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
- return true;
+ function visitTypeParameter(type) {
+ visitType(getConstraintOfTypeParameter(type));
}
- if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
- return true;
+ function visitUnionOrIntersectionType(type) {
+ ts.forEach(type.types, visitType);
}
- if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
- if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
- && ts.getContainingClass(declaration)
- && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
- return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
+ function visitIndexType(type) {
+ visitType(type.type);
+ }
+ function visitIndexedAccessType(type) {
+ visitType(type.objectType);
+ visitType(type.indexType);
+ visitType(type.constraint);
+ }
+ function visitMappedType(type) {
+ visitType(type.typeParameter);
+ visitType(type.constraintType);
+ visitType(type.templateType);
+ visitType(type.modifiersType);
+ }
+ function visitSignature(signature) {
+ var typePredicate = getTypePredicateOfSignature(signature);
+ if (typePredicate) {
+ visitType(typePredicate.type);
}
- else {
- return true;
+ ts.forEach(signature.typeParameters, visitType);
+ for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
+ var parameter = _a[_i];
+ visitSymbol(parameter);
}
+ visitType(getRestTypeOfSignature(signature));
+ visitType(getReturnTypeOfSignature(signature));
}
- return false;
- function usageInTypeDeclaration() {
- return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
+ function visitInterfaceType(interfaceT) {
+ visitObjectType(interfaceT);
+ ts.forEach(interfaceT.typeParameters, visitType);
+ ts.forEach(getBaseTypes(interfaceT), visitType);
+ visitType(interfaceT.thisType);
}
- function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
- switch (declaration.parent.parent.kind) {
- case 225 /* VariableStatement */:
- case 230 /* ForStatement */:
- case 232 /* ForOfStatement */:
- // variable statement/for/for-of statement case,
- // use site should not be inside variable declaration (initializer of declaration or binding element)
- if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
- return true;
- }
- break;
+ function visitObjectType(type) {
+ var resolved = resolveStructuredTypeMembers(type);
+ for (var _i = 0, _a = resolved.indexInfos; _i < _a.length; _i++) {
+ var info = _a[_i];
+ visitType(info.keyType);
+ visitType(info.type);
+ }
+ for (var _b = 0, _c = resolved.callSignatures; _b < _c.length; _b++) {
+ var signature = _c[_b];
+ visitSignature(signature);
+ }
+ for (var _d = 0, _e = resolved.constructSignatures; _d < _e.length; _d++) {
+ var signature = _e[_d];
+ visitSignature(signature);
+ }
+ for (var _f = 0, _g = resolved.properties; _f < _g.length; _f++) {
+ var p = _g[_f];
+ visitSymbol(p);
}
- // ForIn/ForOf case - use site should not be used in expression part
- var grandparent = declaration.parent.parent;
- return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
}
- function isUsedInFunctionOrInstanceProperty(usage, declaration) {
- return !!ts.findAncestor(usage, function (current) {
- if (current === declContainer) {
- return "quit";
- }
- if (ts.isFunctionLike(current)) {
- return true;
- }
- var initializerOfProperty = current.parent &&
- current.parent.kind === 159 /* PropertyDeclaration */ &&
- current.parent.initializer === current;
- if (initializerOfProperty) {
- if (ts.hasModifier(current.parent, 32 /* Static */)) {
- if (declaration.kind === 161 /* MethodDeclaration */) {
- return true;
- }
- }
- else {
- var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
- if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
- return true;
- }
- }
- }
+ function visitSymbol(symbol) {
+ if (!symbol) {
return false;
- });
- }
- /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
- function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
- // always legal if usage is after declaration
- if (usage.end > declaration.end) {
+ }
+ var symbolId = ts.getSymbolId(symbol);
+ if (visitedSymbols[symbolId]) {
return false;
}
- // still might be legal if usage is deferred (e.g. x: any = () => this.x)
- // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
- var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
- if (node === declaration) {
- return "quit";
- }
- switch (node.kind) {
- case 202 /* ArrowFunction */:
- return true;
- case 159 /* PropertyDeclaration */:
- // even when stopping at any property declaration, they need to come from the same class
- return stopAtAnyPropertyDeclaration &&
- (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
- || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
- ? "quit" : true;
- case 223 /* Block */:
- switch (node.parent.kind) {
- case 163 /* GetAccessor */:
- case 161 /* MethodDeclaration */:
- case 164 /* SetAccessor */:
- return true;
- default:
- return false;
- }
- default:
- return false;
+ visitedSymbols[symbolId] = symbol;
+ if (!accept(symbol)) {
+ return true;
+ }
+ var t = getTypeOfSymbol(symbol);
+ visitType(t); // Should handle members on classes and such
+ if (symbol.exports) {
+ symbol.exports.forEach(visitSymbol);
+ }
+ ts.forEach(symbol.declarations, function (d) {
+ // Type queries are too far resolved when we just visit the symbol's type
+ // (their type resolved directly to the member deeply referenced)
+ // So to get the intervening symbols, we need to check if there's a type
+ // query node on any of the symbol's declarations and get symbols there
+ if (d.type && d.type.kind === 180 /* TypeQuery */) {
+ var query = d.type;
+ var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
+ visitSymbol(entity);
}
});
- return ancestorChangingReferenceScope === undefined;
+ return false;
}
}
- function useOuterVariableScopeInParameter(result, location, lastLocation) {
- var target = ts.getEmitScriptTarget(compilerOptions);
- var functionLocation = location;
- if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
- // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
- // - static field in a class expression
- // - optional chaining pre-es2020
- // - nullish coalesce pre-es2020
- // - spread assignment in binding pattern pre-es2017
- if (target >= 2 /* ES2015 */) {
- var links = getNodeLinks(functionLocation);
- if (links.declarationRequiresScopeChange === undefined) {
- links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
- }
- return !links.declarationRequiresScopeChange;
- }
- }
- return false;
- function requiresScopeChange(node) {
- return requiresScopeChangeWorker(node.name)
- || !!node.initializer && requiresScopeChangeWorker(node.initializer);
- }
- function requiresScopeChangeWorker(node) {
- switch (node.kind) {
- case 202 /* ArrowFunction */:
- case 201 /* FunctionExpression */:
- case 244 /* FunctionDeclaration */:
- case 162 /* Constructor */:
- // do not descend into these
- return false;
- case 161 /* MethodDeclaration */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 281 /* PropertyAssignment */:
- return requiresScopeChangeWorker(node.name);
- case 159 /* PropertyDeclaration */:
- // static properties in classes introduce temporary variables
- if (ts.hasStaticModifier(node)) {
- return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
- }
- return requiresScopeChangeWorker(node.name);
- default:
- // null coalesce and optional chain pre-es2020 produce temporary variables
- if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
- return target < 7 /* ES2020 */;
- }
- if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
- return target < 4 /* ES2017 */;
- }
- if (ts.isTypeNode(node))
- return false;
- return ts.forEachChild(node, requiresScopeChangeWorker) || false;
- }
- }
+ }
+ ts.createGetSymbolWalker = createGetSymbolWalker;
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var ambientModuleSymbolRegex = /^".+"$/;
+ var anon = "(anonymous)";
+ var nextSymbolId = 1;
+ var nextNodeId = 1;
+ var nextMergeId = 1;
+ var nextFlowId = 1;
+ var IterationUse;
+ (function (IterationUse) {
+ IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
+ IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
+ IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
+ IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
+ IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
+ IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
+ IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
+ IterationUse[IterationUse["PossiblyOutOfBounds"] = 128] = "PossiblyOutOfBounds";
+ // Spread, Destructuring, Array element assignment
+ IterationUse[IterationUse["Element"] = 1] = "Element";
+ IterationUse[IterationUse["Spread"] = 33] = "Spread";
+ IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
+ IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
+ IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
+ IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
+ IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
+ IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
+ IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
+ })(IterationUse || (IterationUse = {}));
+ var IterationTypeKind;
+ (function (IterationTypeKind) {
+ IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
+ IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
+ IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
+ })(IterationTypeKind || (IterationTypeKind = {}));
+ var WideningKind;
+ (function (WideningKind) {
+ WideningKind[WideningKind["Normal"] = 0] = "Normal";
+ WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
+ WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
+ WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
+ })(WideningKind || (WideningKind = {}));
+ var TypeFacts;
+ (function (TypeFacts) {
+ TypeFacts[TypeFacts["None"] = 0] = "None";
+ TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
+ TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
+ TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
+ TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
+ TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
+ TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
+ TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
+ TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
+ TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
+ TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
+ TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
+ TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
+ TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
+ TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
+ TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
+ TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
+ TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
+ TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
+ TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
+ TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
+ TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
+ TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
+ TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
+ TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
+ TypeFacts[TypeFacts["All"] = 16777215] = "All";
+ // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
+ // The presence of a particular fact means that the given test is true for some (and possibly all) values
+ // of that kind of type.
+ TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
+ TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
+ TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
+ TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
+ TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
+ TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
+ TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
+ TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
+ TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
+ TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
+ TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
+ TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
+ TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
+ TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
+ TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
+ TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
+ TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
+ TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
+ TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
+ TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
+ TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
+ TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
+ TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
+ TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
+ TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
+ TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
+ TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
+ TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
+ TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
+ TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
+ TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
+ TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
+ TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
+ TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
+ TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
+ TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
+ TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
+ TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
+ TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
+ TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
+ TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
+ TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE";
+ TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
+ })(TypeFacts || (TypeFacts = {}));
+ var typeofEQFacts = new ts.Map(ts.getEntries({
+ string: 1 /* TypeofEQString */,
+ number: 2 /* TypeofEQNumber */,
+ bigint: 4 /* TypeofEQBigInt */,
+ boolean: 8 /* TypeofEQBoolean */,
+ symbol: 16 /* TypeofEQSymbol */,
+ undefined: 65536 /* EQUndefined */,
+ object: 32 /* TypeofEQObject */,
+ function: 64 /* TypeofEQFunction */
+ }));
+ var typeofNEFacts = new ts.Map(ts.getEntries({
+ string: 256 /* TypeofNEString */,
+ number: 512 /* TypeofNENumber */,
+ bigint: 1024 /* TypeofNEBigInt */,
+ boolean: 2048 /* TypeofNEBoolean */,
+ symbol: 4096 /* TypeofNESymbol */,
+ undefined: 524288 /* NEUndefined */,
+ object: 8192 /* TypeofNEObject */,
+ function: 16384 /* TypeofNEFunction */
+ }));
+ var TypeSystemPropertyName;
+ (function (TypeSystemPropertyName) {
+ TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
+ TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
+ TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
+ TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
+ TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
+ TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
+ TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
+ TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseTypes"] = 7] = "ResolvedBaseTypes";
+ })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
+ var CheckMode;
+ (function (CheckMode) {
+ CheckMode[CheckMode["Normal"] = 0] = "Normal";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
+ CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
+ })(CheckMode || (CheckMode = {}));
+ var SignatureCheckMode;
+ (function (SignatureCheckMode) {
+ SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
+ SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
+ SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
+ SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
+ SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
+ })(SignatureCheckMode || (SignatureCheckMode = {}));
+ var IntersectionState;
+ (function (IntersectionState) {
+ IntersectionState[IntersectionState["None"] = 0] = "None";
+ IntersectionState[IntersectionState["Source"] = 1] = "Source";
+ IntersectionState[IntersectionState["Target"] = 2] = "Target";
+ IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
+ IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck";
+ IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck";
+ })(IntersectionState || (IntersectionState = {}));
+ var RecursionFlags;
+ (function (RecursionFlags) {
+ RecursionFlags[RecursionFlags["None"] = 0] = "None";
+ RecursionFlags[RecursionFlags["Source"] = 1] = "Source";
+ RecursionFlags[RecursionFlags["Target"] = 2] = "Target";
+ RecursionFlags[RecursionFlags["Both"] = 3] = "Both";
+ })(RecursionFlags || (RecursionFlags = {}));
+ var MappedTypeModifiers;
+ (function (MappedTypeModifiers) {
+ MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
+ MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
+ MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
+ MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
+ })(MappedTypeModifiers || (MappedTypeModifiers = {}));
+ var ExpandingFlags;
+ (function (ExpandingFlags) {
+ ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
+ ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
+ ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
+ ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
+ })(ExpandingFlags || (ExpandingFlags = {}));
+ var MembersOrExportsResolutionKind;
+ (function (MembersOrExportsResolutionKind) {
+ MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
+ MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
+ })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
+ var UnusedKind;
+ (function (UnusedKind) {
+ UnusedKind[UnusedKind["Local"] = 0] = "Local";
+ UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
+ })(UnusedKind || (UnusedKind = {}));
+ var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
+ var DeclarationMeaning;
+ (function (DeclarationMeaning) {
+ DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
+ DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
+ DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
+ DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
+ DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic";
+ DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
+ DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
+ })(DeclarationMeaning || (DeclarationMeaning = {}));
+ var DeclarationSpaces;
+ (function (DeclarationSpaces) {
+ DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
+ DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
+ DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
+ DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
+ })(DeclarationSpaces || (DeclarationSpaces = {}));
+ var MinArgumentCountFlags;
+ (function (MinArgumentCountFlags) {
+ MinArgumentCountFlags[MinArgumentCountFlags["None"] = 0] = "None";
+ MinArgumentCountFlags[MinArgumentCountFlags["StrongArityForUntypedJS"] = 1] = "StrongArityForUntypedJS";
+ MinArgumentCountFlags[MinArgumentCountFlags["VoidIsNonOptional"] = 2] = "VoidIsNonOptional";
+ })(MinArgumentCountFlags || (MinArgumentCountFlags = {}));
+ var IntrinsicTypeKind;
+ (function (IntrinsicTypeKind) {
+ IntrinsicTypeKind[IntrinsicTypeKind["Uppercase"] = 0] = "Uppercase";
+ IntrinsicTypeKind[IntrinsicTypeKind["Lowercase"] = 1] = "Lowercase";
+ IntrinsicTypeKind[IntrinsicTypeKind["Capitalize"] = 2] = "Capitalize";
+ IntrinsicTypeKind[IntrinsicTypeKind["Uncapitalize"] = 3] = "Uncapitalize";
+ })(IntrinsicTypeKind || (IntrinsicTypeKind = {}));
+ var intrinsicTypeKinds = new ts.Map(ts.getEntries({
+ Uppercase: 0 /* Uppercase */,
+ Lowercase: 1 /* Lowercase */,
+ Capitalize: 2 /* Capitalize */,
+ Uncapitalize: 3 /* Uncapitalize */
+ }));
+ function SymbolLinks() {
+ }
+ function NodeLinks() {
+ this.flags = 0;
+ }
+ function getNodeId(node) {
+ if (!node.id) {
+ node.id = nextNodeId;
+ nextNodeId++;
}
- /**
- * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
- * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
- * the given name can be found.
- *
- * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
- */
- function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
- if (excludeGlobals === void 0) { excludeGlobals = false; }
- return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
+ return node.id;
+ }
+ ts.getNodeId = getNodeId;
+ function getSymbolId(symbol) {
+ if (!symbol.id) {
+ symbol.id = nextSymbolId;
+ nextSymbolId++;
}
- function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
- var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
- var result;
- var lastLocation;
- var lastSelfReferenceLocation;
- var propertyWithInvalidInitializer;
- var associatedDeclarationForContainingInitializerOrBindingName;
- var withinDeferredContext = false;
- var errorLocation = location;
- var grandparent;
- var isInExternalModule = false;
- loop: while (location) {
- // Locals of a source file are not in scope (because they get merged into the global symbol table)
- if (location.locals && !isGlobalSourceFile(location)) {
- if (result = lookup(location.locals, name, meaning)) {
- var useResult = true;
- if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
- // symbol lookup restrictions for function-like declarations
- // - Type parameters of a function are in scope in the entire function declaration, including the parameter
- // list and return type. However, local types are only in scope in the function body.
- // - parameters are only in the scope of function body
- // This restriction does not apply to JSDoc comment types because they are parented
- // at a higher level than type parameters would normally be
- if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
- useResult = result.flags & 262144 /* TypeParameter */
- // type parameters are visible in parameter list, return type and type parameter list
- ? lastLocation === location.type ||
- lastLocation.kind === 156 /* Parameter */ ||
- lastLocation.kind === 155 /* TypeParameter */
- // local types not visible outside the function body
- : false;
- }
- if (meaning & result.flags & 3 /* Variable */) {
- // expression inside parameter will lookup as normal variable scope when targeting es2015+
- if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
- useResult = false;
- }
- else if (result.flags & 1 /* FunctionScopedVariable */) {
- // parameters are visible only inside function body, parameter list and return type
- // technically for parameter list case here we might mix parameters and variables declared in function,
- // however it is detected separately when checking initializers of parameters
- // to make sure that they reference no variables declared after them.
- useResult =
- lastLocation.kind === 156 /* Parameter */ ||
- (lastLocation === location.type &&
- !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
- }
- }
- }
- else if (location.kind === 180 /* ConditionalType */) {
- // A type parameter declared using 'infer T' in a conditional type is visible only in
- // the true branch of the conditional type.
- useResult = lastLocation === location.trueType;
- }
- if (useResult) {
- break loop;
- }
- else {
- result = undefined;
- }
- }
- }
- withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
- switch (location.kind) {
- case 290 /* SourceFile */:
- if (!ts.isExternalOrCommonJsModule(location))
- break;
- isInExternalModule = true;
- // falls through
- case 249 /* ModuleDeclaration */:
- var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
- if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
- // It's an external module. First see if the module has an export default and if the local
- // name of that export default matches.
- if (result = moduleExports.get("default" /* Default */)) {
- var localSymbol = ts.getLocalSymbolForExportDefault(result);
- if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
- break loop;
- }
- result = undefined;
- }
- // Because of module/namespace merging, a module's exports are in scope,
- // yet we never want to treat an export specifier as putting a member in scope.
- // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
- // Two things to note about this:
- // 1. We have to check this without calling getSymbol. The problem with calling getSymbol
- // on an export specifier is that it might find the export specifier itself, and try to
- // resolve it as an alias. This will cause the checker to consider the export specifier
- // a circular alias reference when it might not be.
- // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
- // an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
- // which is not the desired behavior.
- var moduleExport = moduleExports.get(name);
- if (moduleExport &&
- moduleExport.flags === 2097152 /* Alias */ &&
- (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
- break;
- }
- }
- // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
- if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
- if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
- result = undefined;
- }
- else {
- break loop;
- }
- }
- break;
- case 248 /* EnumDeclaration */:
- if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
- break loop;
- }
- break;
- case 159 /* PropertyDeclaration */:
- // TypeScript 1.0 spec (April 2014): 8.4.1
- // Initializer expressions for instance member variables are evaluated in the scope
- // of the class constructor body but are not permitted to reference parameters or
- // local variables of the constructor. This effectively means that entities from outer scopes
- // by the same name as a constructor parameter or local variable are inaccessible
- // in initializer expressions for instance member variables.
- if (!ts.hasModifier(location, 32 /* Static */)) {
- var ctor = findConstructorDeclaration(location.parent);
- if (ctor && ctor.locals) {
- if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
- // Remember the property node, it will be used later to report appropriate error
- propertyWithInvalidInitializer = location;
- }
- }
- }
- break;
- case 245 /* ClassDeclaration */:
- case 214 /* ClassExpression */:
- case 246 /* InterfaceDeclaration */:
- // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
- // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
- // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
- if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
- if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
- // ignore type parameters not declared in this container
- result = undefined;
- break;
- }
- if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
- // TypeScript 1.0 spec (April 2014): 3.4.1
- // The scope of a type parameter extends over the entire declaration with which the type
- // parameter list is associated, with the exception of static member declarations in classes.
- error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
- return undefined;
- }
- break loop;
- }
- if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
- var className = location.name;
- if (className && name === className.escapedText) {
- result = location.symbol;
- break loop;
- }
- }
- break;
- case 216 /* ExpressionWithTypeArguments */:
- // The type parameters of a class are not in scope in the base class expression.
- if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
- var container = location.parent.parent;
- if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
- if (nameNotFoundMessage) {
- error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
- }
- return undefined;
- }
- }
- break;
- // It is not legal to reference a class's own type parameters from a computed property name that
- // belongs to the class. For example:
- //
- // function foo() { return '' }
- // class C { // <-- Class's own type parameter T
- // [foo()]() { } // <-- Reference to T from class's own computed property
- // }
- //
- case 154 /* ComputedPropertyName */:
- grandparent = location.parent.parent;
- if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
- // A reference to this grandparent's type parameters would be an error
- if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
- error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
- return undefined;
- }
- }
- break;
- case 202 /* ArrowFunction */:
- // when targeting ES6 or higher there is no 'arguments' in an arrow function
- // for lower compile targets the resolved symbol is used to emit an error
- if (compilerOptions.target >= 2 /* ES2015 */) {
- break;
- }
- // falls through
- case 161 /* MethodDeclaration */:
- case 162 /* Constructor */:
- case 163 /* GetAccessor */:
- case 164 /* SetAccessor */:
- case 244 /* FunctionDeclaration */:
- if (meaning & 3 /* Variable */ && name === "arguments") {
- result = argumentsSymbol;
- break loop;
- }
- break;
- case 201 /* FunctionExpression */:
- if (meaning & 3 /* Variable */ && name === "arguments") {
- result = argumentsSymbol;
- break loop;
- }
- if (meaning & 16 /* Function */) {
- var functionName = location.name;
- if (functionName && name === functionName.escapedText) {
- result = location.symbol;
- break loop;
- }
- }
- break;
- case 157 /* Decorator */:
- // Decorators are resolved at the class declaration. Resolving at the parameter
- // or member would result in looking up locals in the method.
- //
- // function y() {}
- // class C {
- // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
- // }
- //
- if (location.parent && location.parent.kind === 156 /* Parameter */) {
- location = location.parent;
- }
- //
- // function y() {}
- // class C {
- // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
- // }
- //
- // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
- //
- // type T = number;
- // declare function y(x: T): any;
- // @param(1 as T) // <-- T should resolve to the type alias outside of class C
- // class C {}
- if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
- location = location.parent;
- }
- break;
- case 322 /* JSDocTypedefTag */:
- case 315 /* JSDocCallbackTag */:
- case 316 /* JSDocEnumTag */:
- // js type aliases do not resolve names from their host, so skip past it
- location = ts.getJSDocHost(location);
- break;
- case 156 /* Parameter */:
- if (lastLocation && (lastLocation === location.initializer ||
- lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
- if (!associatedDeclarationForContainingInitializerOrBindingName) {
- associatedDeclarationForContainingInitializerOrBindingName = location;
- }
- }
- break;
- case 191 /* BindingElement */:
- if (lastLocation && (lastLocation === location.initializer ||
- lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
- var root = ts.getRootDeclaration(location);
- if (root.kind === 156 /* Parameter */) {
- if (!associatedDeclarationForContainingInitializerOrBindingName) {
- associatedDeclarationForContainingInitializerOrBindingName = location;
- }
- }
- }
- break;
+ return symbol.id;
+ }
+ ts.getSymbolId = getSymbolId;
+ function isInstantiatedModule(node, preserveConstEnums) {
+ var moduleState = ts.getModuleInstanceState(node);
+ return moduleState === 1 /* Instantiated */ ||
+ (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
+ }
+ ts.isInstantiatedModule = isInstantiatedModule;
+ function createTypeChecker(host, produceDiagnostics) {
+ var getPackagesMap = ts.memoize(function () {
+ // A package name maps to true when we detect it has .d.ts files.
+ // This is useful as an approximation of whether a package bundles its own types.
+ // Note: we only look at files already found by module resolution,
+ // so there may be files we did not consider.
+ var map = new ts.Map();
+ host.getSourceFiles().forEach(function (sf) {
+ if (!sf.resolvedModules)
+ return;
+ sf.resolvedModules.forEach(function (r) {
+ if (r && r.packageId)
+ map.set(r.packageId.name, r.extension === ".d.ts" /* Dts */ || !!map.get(r.packageId.name));
+ });
+ });
+ return map;
+ });
+ // Cancellation that controls whether or not we can cancel in the middle of type checking.
+ // In general cancelling is *not* safe for the type checker. We might be in the middle of
+ // computing something, and we will leave our internals in an inconsistent state. Callers
+ // who set the cancellation token should catch if a cancellation exception occurs, and
+ // should throw away and create a new TypeChecker.
+ //
+ // Currently we only support setting the cancellation token when getting diagnostics. This
+ // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
+ // they no longer need the information (for example, if the user started editing again).
+ var cancellationToken;
+ var requestedExternalEmitHelpers;
+ var externalHelpersModule;
+ var Symbol = ts.objectAllocator.getSymbolConstructor();
+ var Type = ts.objectAllocator.getTypeConstructor();
+ var Signature = ts.objectAllocator.getSignatureConstructor();
+ var typeCount = 0;
+ var symbolCount = 0;
+ var enumCount = 0;
+ var totalInstantiationCount = 0;
+ var instantiationCount = 0;
+ var instantiationDepth = 0;
+ var inlineLevel = 0;
+ var currentNode;
+ var emptySymbols = ts.createSymbolTable();
+ var arrayVariances = [1 /* Covariant */];
+ var compilerOptions = host.getCompilerOptions();
+ var languageVersion = ts.getEmitScriptTarget(compilerOptions);
+ var moduleKind = ts.getEmitModuleKind(compilerOptions);
+ var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions);
+ var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
+ var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
+ var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
+ var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
+ var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
+ var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
+ var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
+ var useUnknownInCatchVariables = ts.getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables");
+ var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
+ var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */;
+ var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes;
+ var checkBinaryExpression = createCheckBinaryExpression();
+ var emitResolver = createResolver();
+ var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
+ var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
+ undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.declarations = [];
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
+ var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
+ var requireSymbol = createSymbol(4 /* Property */, "require");
+ /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
+ var apparentArgumentCount;
+ // for public members that accept a Node or one of its subtypes, we must guard against
+ // synthetic nodes created during transformations by calling `getParseTreeNode`.
+ // for most of these, we perform the guard only on `checker` to avoid any possible
+ // extra cost of calling `getParseTreeNode` when calling these functions from inside the
+ // checker.
+ var checker = {
+ getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
+ getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
+ getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
+ getTypeCount: function () { return typeCount; },
+ getInstantiationCount: function () { return totalInstantiationCount; },
+ getRelationCacheSizes: function () { return ({
+ assignable: assignableRelation.size,
+ identity: identityRelation.size,
+ subtype: subtypeRelation.size,
+ strictSubtype: strictSubtypeRelation.size,
+ }); },
+ isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
+ isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
+ isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
+ getMergedSymbol: getMergedSymbol,
+ getDiagnostics: getDiagnostics,
+ getGlobalDiagnostics: getGlobalDiagnostics,
+ getRecursionIdentity: getRecursionIdentity,
+ getUnmatchedProperties: getUnmatchedProperties,
+ getTypeOfSymbolAtLocation: function (symbol, locationIn) {
+ var location = ts.getParseTreeNode(locationIn);
+ return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
+ },
+ getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
+ var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
+ if (parameter === undefined)
+ return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
+ return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
+ },
+ getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
+ getPropertiesOfType: getPropertiesOfType,
+ getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
+ getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
+ var node = ts.getParseTreeNode(location);
+ if (!node) {
+ return undefined;
}
- if (isSelfReferenceLocation(location)) {
- lastSelfReferenceLocation = location;
+ var propName = ts.escapeLeadingUnderscores(name);
+ var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
+ return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
+ },
+ getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
+ getIndexInfoOfType: function (type, kind) { return getIndexInfoOfType(type, kind === 0 /* String */ ? stringType : numberType); },
+ getIndexInfosOfType: getIndexInfosOfType,
+ getSignaturesOfType: getSignaturesOfType,
+ getIndexTypeOfType: function (type, kind) { return getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType); },
+ getBaseTypes: getBaseTypes,
+ getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
+ getWidenedType: getWidenedType,
+ getTypeFromTypeNode: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
+ return node ? getTypeFromTypeNode(node) : errorType;
+ },
+ getParameterType: getTypeAtPosition,
+ getParameterIdentifierNameAtPosition: getParameterIdentifierNameAtPosition,
+ getPromisedTypeOfPromise: getPromisedTypeOfPromise,
+ getAwaitedType: function (type) { return getAwaitedType(type); },
+ getReturnTypeOfSignature: getReturnTypeOfSignature,
+ isNullableType: isNullableType,
+ getNullableType: getNullableType,
+ getNonNullableType: getNonNullableType,
+ getNonOptionalType: removeOptionalTypeMarker,
+ getTypeArguments: getTypeArguments,
+ typeToTypeNode: nodeBuilder.typeToTypeNode,
+ indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
+ signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
+ symbolToEntityName: nodeBuilder.symbolToEntityName,
+ symbolToExpression: nodeBuilder.symbolToExpression,
+ symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
+ symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
+ typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
+ getSymbolsInScope: function (locationIn, meaning) {
+ var location = ts.getParseTreeNode(locationIn);
+ return location ? getSymbolsInScope(location, meaning) : [];
+ },
+ getSymbolAtLocation: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn);
+ // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
+ return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
+ },
+ getIndexInfosAtLocation: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn);
+ return node ? getIndexInfosAtLocation(node) : undefined;
+ },
+ getShorthandAssignmentValueSymbol: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn);
+ return node ? getShorthandAssignmentValueSymbol(node) : undefined;
+ },
+ getExportSpecifierLocalTargetSymbol: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
+ return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
+ },
+ getExportSymbolOfSymbol: function (symbol) {
+ return getMergedSymbol(symbol.exportSymbol || symbol);
+ },
+ getTypeAtLocation: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn);
+ return node ? getTypeOfNode(node) : errorType;
+ },
+ getTypeOfAssignmentPattern: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
+ return node && getTypeOfAssignmentPattern(node) || errorType;
+ },
+ getPropertySymbolOfDestructuringAssignment: function (locationIn) {
+ var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
+ return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
+ },
+ signatureToString: function (signature, enclosingDeclaration, flags, kind) {
+ return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
+ },
+ typeToString: function (type, enclosingDeclaration, flags) {
+ return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
+ },
+ symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
+ return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
+ },
+ typePredicateToString: function (predicate, enclosingDeclaration, flags) {
+ return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
+ },
+ writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
+ return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
+ },
+ writeType: function (type, enclosingDeclaration, flags, writer) {
+ return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
+ },
+ writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
+ return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
+ },
+ writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
+ return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
+ },
+ getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
+ getRootSymbols: getRootSymbols,
+ getSymbolOfExpando: getSymbolOfExpando,
+ getContextualType: function (nodeIn, contextFlags) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
+ if (!node) {
+ return undefined;
}
- lastLocation = location;
- location = location.parent;
- }
- // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
- // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
- // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
- if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
- result.isReferenced |= meaning;
- }
- if (!result) {
- if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
- if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
- return lastLocation.symbol;
- }
+ var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
+ var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
+ if (contextFlags & 4 /* Completions */ && containingCall) {
+ var toMarkSkip = node;
+ do {
+ getNodeLinks(toMarkSkip).skipDirectInference = true;
+ toMarkSkip = toMarkSkip.parent;
+ } while (toMarkSkip && toMarkSkip !== containingCall);
+ getNodeLinks(containingCall).resolvedSignature = undefined;
}
- if (!excludeGlobals) {
- result = lookup(globals, name, meaning);
+ var result = getContextualType(node, contextFlags);
+ if (contextFlags & 4 /* Completions */ && containingCall) {
+ var toMarkSkip = node;
+ do {
+ getNodeLinks(toMarkSkip).skipDirectInference = undefined;
+ toMarkSkip = toMarkSkip.parent;
+ } while (toMarkSkip && toMarkSkip !== containingCall);
+ getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
}
- }
- if (!result) {
- if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
- if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
- return requireSymbol;
- }
+ return result;
+ },
+ getContextualTypeForObjectLiteralElement: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
+ return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
+ },
+ getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
+ return node && getContextualTypeForArgumentAtIndex(node, argIndex);
+ },
+ getContextualTypeForJsxAttribute: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
+ return node && getContextualTypeForJsxAttribute(node);
+ },
+ isContextSensitive: isContextSensitive,
+ getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType,
+ getFullyQualifiedName: getFullyQualifiedName,
+ getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
+ return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
+ },
+ getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
+ return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
+ },
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
+ containsArgumentsReference: containsArgumentsReference,
+ getConstantValue: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
+ return node ? getConstantValue(node) : undefined;
+ },
+ isValidPropertyAccess: function (nodeIn, propertyName) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
+ return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
+ },
+ isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
+ return !!node && isValidPropertyAccessForCompletions(node, type, property);
+ },
+ getSignatureFromDeclaration: function (declarationIn) {
+ var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
+ return declaration ? getSignatureFromDeclaration(declaration) : undefined;
+ },
+ isImplementationOfOverload: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isFunctionLike);
+ return node ? isImplementationOfOverload(node) : undefined;
+ },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
+ getAliasedSymbol: resolveAlias,
+ getEmitResolver: getEmitResolver,
+ getExportsOfModule: getExportsOfModuleAsArray,
+ getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
+ forEachExportAndPropertyOfModule: forEachExportAndPropertyOfModule,
+ getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
+ getAmbientModules: getAmbientModules,
+ getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
+ isOptionalParameter: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
+ return node ? isOptionalParameter(node) : false;
+ },
+ tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
+ tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
+ tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); },
+ tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
+ // we deliberately exclude augmentations
+ // since we are only interested in declarations of the module itself
+ return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
+ },
+ getApparentType: getApparentType,
+ getUnionType: getUnionType,
+ isTypeAssignableTo: isTypeAssignableTo,
+ createAnonymousType: createAnonymousType,
+ createSignature: createSignature,
+ createSymbol: createSymbol,
+ createIndexInfo: createIndexInfo,
+ getAnyType: function () { return anyType; },
+ getStringType: function () { return stringType; },
+ getNumberType: function () { return numberType; },
+ createPromiseType: createPromiseType,
+ createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
+ getBooleanType: function () { return booleanType; },
+ getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
+ getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
+ getVoidType: function () { return voidType; },
+ getUndefinedType: function () { return undefinedType; },
+ getNullType: function () { return nullType; },
+ getESSymbolType: function () { return esSymbolType; },
+ getNeverType: function () { return neverType; },
+ getOptionalType: function () { return optionalType; },
+ getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); },
+ getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); },
+ isSymbolAccessible: isSymbolAccessible,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
+ isArrayLikeType: isArrayLikeType,
+ isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
+ getExactOptionalProperties: getExactOptionalProperties,
+ getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
+ getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
+ getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
+ getSuggestedSymbolForNonexistentJSXAttribute: getSuggestedSymbolForNonexistentJSXAttribute,
+ getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
+ getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
+ getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
+ getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
+ getSuggestedSymbolForNonexistentClassMember: getSuggestedSymbolForNonexistentClassMember,
+ getBaseConstraintOfType: getBaseConstraintOfType,
+ getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
+ resolveName: function (name, location, meaning, excludeGlobals) {
+ return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
+ },
+ getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
+ getJsxFragmentFactory: function (n) {
+ var jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
+ return jsxFragmentFactory && ts.unescapeLeadingUnderscores(ts.getFirstIdentifier(jsxFragmentFactory).escapedText);
+ },
+ getAccessibleSymbolChain: getAccessibleSymbolChain,
+ getTypePredicateOfSignature: getTypePredicateOfSignature,
+ resolveExternalModuleName: function (moduleSpecifierIn) {
+ var moduleSpecifier = ts.getParseTreeNode(moduleSpecifierIn, ts.isExpression);
+ return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
+ },
+ resolveExternalModuleSymbol: resolveExternalModuleSymbol,
+ tryGetThisTypeAt: function (nodeIn, includeGlobalThis) {
+ var node = ts.getParseTreeNode(nodeIn);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
+ },
+ getTypeArgumentConstraint: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
+ return node && getTypeArgumentConstraint(node);
+ },
+ getSuggestionDiagnostics: function (fileIn, ct) {
+ var file = ts.getParseTreeNode(fileIn, ts.isSourceFile) || ts.Debug.fail("Could not determine parsed source file.");
+ if (ts.skipTypeChecking(file, compilerOptions, host)) {
+ return ts.emptyArray;
}
- }
- if (!result) {
- if (nameNotFoundMessage) {
- if (!errorLocation ||
- !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
- !checkAndReportErrorForExtendingInterface(errorLocation) &&
- !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
- !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
- !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
- var suggestion = void 0;
- if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
- suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
- if (suggestion) {
- var suggestionName = symbolToString(suggestion);
- var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
- if (suggestion.valueDeclaration) {
- ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
- }
- }
- }
- if (!suggestion) {
- error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
+ var diagnostics;
+ try {
+ // Record the cancellation token so it can be checked later on during checkSourceElement.
+ // Do this in a finally block so we can ensure that it gets reset back to nothing after
+ // this call is done.
+ cancellationToken = ct;
+ // Ensure file is type checked
+ checkSourceFile(file);
+ ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
+ diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
+ checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
+ if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
+ (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
}
- suggestionCount++;
- }
+ });
+ return diagnostics || ts.emptyArray;
}
- return undefined;
- }
- // Perform extra checks only if error reporting was requested
- if (nameNotFoundMessage) {
- if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
- // We have a match, but the reference occurred within a property initializer and the identifier also binds
- // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
- // with ESNext+useDefineForClassFields because the scope semantics are different.
- var propertyName = propertyWithInvalidInitializer.name;
- error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
- return undefined;
+ finally {
+ cancellationToken = undefined;
}
- // Only check for block-scoped variable if we have an error location and are looking for the
- // name with variable meaning
- // For example,
- // declare module foo {
- // interface bar {}
- // }
- // const foo/*1*/: foo/*2*/.bar;
- // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
- // block-scoped variable and namespace module. However, only when we
- // try to resolve name in /*1*/ which is used in variable position,
- // we want to check for block-scoped
- if (errorLocation &&
- (meaning & 2 /* BlockScopedVariable */ ||
- ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
- var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
- if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
- checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
+ },
+ runWithCancellationToken: function (token, callback) {
+ try {
+ cancellationToken = token;
+ return callback(checker);
+ }
+ finally {
+ cancellationToken = undefined;
+ }
+ },
+ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
+ isDeclarationVisible: isDeclarationVisible,
+ isPropertyAccessible: isPropertyAccessible,
+ getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration,
+ getMemberOverrideModifierStatus: getMemberOverrideModifierStatus,
+ };
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
+ var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
+ apparentArgumentCount = argumentCount;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
+ apparentArgumentCount = undefined;
+ return res;
+ }
+ var tupleTypes = new ts.Map();
+ var unionTypes = new ts.Map();
+ var intersectionTypes = new ts.Map();
+ var stringLiteralTypes = new ts.Map();
+ var numberLiteralTypes = new ts.Map();
+ var bigIntLiteralTypes = new ts.Map();
+ var enumLiteralTypes = new ts.Map();
+ var indexedAccessTypes = new ts.Map();
+ var templateLiteralTypes = new ts.Map();
+ var stringMappingTypes = new ts.Map();
+ var substitutionTypes = new ts.Map();
+ var subtypeReductionCache = new ts.Map();
+ var evolvingArrayTypes = [];
+ var undefinedProperties = new ts.Map();
+ var unknownSymbol = createSymbol(4 /* Property */, "unknown");
+ var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
+ var unresolvedSymbols = new ts.Map();
+ var errorTypes = new ts.Map();
+ var anyType = createIntrinsicType(1 /* Any */, "any");
+ var autoType = createIntrinsicType(1 /* Any */, "any");
+ var wildcardType = createIntrinsicType(1 /* Any */, "any");
+ var errorType = createIntrinsicType(1 /* Any */, "error");
+ var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved");
+ var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */);
+ var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
+ var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
+ var nonNullUnknownType = createIntrinsicType(2 /* Unknown */, "unknown");
+ var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
+ var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
+ var missingType = exactOptionalPropertyTypes ? createIntrinsicType(32768 /* Undefined */, "undefined") : undefinedType;
+ var nullType = createIntrinsicType(65536 /* Null */, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
+ var stringType = createIntrinsicType(4 /* String */, "string");
+ var numberType = createIntrinsicType(8 /* Number */, "number");
+ var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
+ var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
+ var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
+ var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
+ var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
+ trueType.regularType = regularTrueType;
+ trueType.freshType = trueType;
+ regularTrueType.regularType = regularTrueType;
+ regularTrueType.freshType = trueType;
+ falseType.regularType = regularFalseType;
+ falseType.freshType = falseType;
+ regularFalseType.regularType = regularFalseType;
+ regularFalseType.freshType = falseType;
+ var booleanType = getUnionType([regularFalseType, regularTrueType]);
+ var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
+ var voidType = createIntrinsicType(16384 /* Void */, "void");
+ var neverType = createIntrinsicType(131072 /* Never */, "never");
+ var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
+ var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
+ var stringOrNumberType = getUnionType([stringType, numberType]);
+ var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
+ var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
+ var numberOrBigIntType = getUnionType([numberType, bigintType]);
+ var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
+ var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
+ var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
+ var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */;
+ var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
+ emptyTypeLiteralSymbol.members = ts.createSymbolTable();
+ var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ emptyGenericType.instantiations = new ts.Map();
+ var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
+ // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
+ anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
+ var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
+ var markerSuperType = createTypeParameter();
+ var markerSubType = createTypeParameter();
+ markerSubType.constraint = markerSuperType;
+ var markerOtherType = createTypeParameter();
+ var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType);
+ var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
+ var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
+ var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
+ var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
+ var enumNumberIndexInfo = createIndexInfo(numberType, stringType, /*isReadonly*/ true);
+ var iterationTypesCache = new ts.Map(); // cache for common IterationTypes instances
+ var noIterationTypes = {
+ get yieldType() { return ts.Debug.fail("Not supported"); },
+ get returnType() { return ts.Debug.fail("Not supported"); },
+ get nextType() { return ts.Debug.fail("Not supported"); },
+ };
+ var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
+ var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
+ var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
+ var asyncIterationTypesResolver = {
+ iterableCacheKey: "iterationTypesOfAsyncIterable",
+ iteratorCacheKey: "iterationTypesOfAsyncIterator",
+ iteratorSymbolName: "asyncIterator",
+ getGlobalIteratorType: getGlobalAsyncIteratorType,
+ getGlobalIterableType: getGlobalAsyncIterableType,
+ getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
+ getGlobalGeneratorType: getGlobalAsyncGeneratorType,
+ resolveIterationType: getAwaitedType,
+ mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
+ mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
+ mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property,
+ };
+ var syncIterationTypesResolver = {
+ iterableCacheKey: "iterationTypesOfIterable",
+ iteratorCacheKey: "iterationTypesOfIterator",
+ iteratorSymbolName: "iterator",
+ getGlobalIteratorType: getGlobalIteratorType,
+ getGlobalIterableType: getGlobalIterableType,
+ getGlobalIterableIteratorType: getGlobalIterableIteratorType,
+ getGlobalGeneratorType: getGlobalGeneratorType,
+ resolveIterationType: function (type, _errorNode) { return type; },
+ mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
+ mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
+ mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
+ };
+ /** Key is "/path/to/a.ts|/path/to/b.ts". */
+ var amalgamatedDuplicates;
+ var reverseMappedCache = new ts.Map();
+ var inInferTypeForHomomorphicMappedType = false;
+ var ambientModulesCache;
+ /**
+ * List of every ambient module with a "*" wildcard.
+ * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
+ * This is only used if there is no exact match.
+ */
+ var patternAmbientModules;
+ var patternAmbientModuleAugmentations;
+ var globalObjectType;
+ var globalFunctionType;
+ var globalCallableFunctionType;
+ var globalNewableFunctionType;
+ var globalArrayType;
+ var globalReadonlyArrayType;
+ var globalStringType;
+ var globalNumberType;
+ var globalBooleanType;
+ var globalRegExpType;
+ var globalThisType;
+ var anyArrayType;
+ var autoArrayType;
+ var anyReadonlyArrayType;
+ var deferredGlobalNonNullableTypeAlias;
+ // The library files are only loaded when the feature is used.
+ // This allows users to just specify library files they want to used through --lib
+ // and they will not get an error from not having unrelated library files
+ var deferredGlobalESSymbolConstructorSymbol;
+ var deferredGlobalESSymbolConstructorTypeSymbol;
+ var deferredGlobalESSymbolType;
+ var deferredGlobalTypedPropertyDescriptorType;
+ var deferredGlobalPromiseType;
+ var deferredGlobalPromiseLikeType;
+ var deferredGlobalPromiseConstructorSymbol;
+ var deferredGlobalPromiseConstructorLikeType;
+ var deferredGlobalIterableType;
+ var deferredGlobalIteratorType;
+ var deferredGlobalIterableIteratorType;
+ var deferredGlobalGeneratorType;
+ var deferredGlobalIteratorYieldResultType;
+ var deferredGlobalIteratorReturnResultType;
+ var deferredGlobalAsyncIterableType;
+ var deferredGlobalAsyncIteratorType;
+ var deferredGlobalAsyncIterableIteratorType;
+ var deferredGlobalAsyncGeneratorType;
+ var deferredGlobalTemplateStringsArrayType;
+ var deferredGlobalImportMetaType;
+ var deferredGlobalImportMetaExpressionType;
+ var deferredGlobalImportCallOptionsType;
+ var deferredGlobalExtractSymbol;
+ var deferredGlobalOmitSymbol;
+ var deferredGlobalAwaitedSymbol;
+ var deferredGlobalBigIntType;
+ var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name
+ var flowLoopStart = 0;
+ var flowLoopCount = 0;
+ var sharedFlowCount = 0;
+ var flowAnalysisDisabled = false;
+ var flowInvocationCount = 0;
+ var lastFlowNode;
+ var lastFlowNodeReachable;
+ var flowTypeCache;
+ var emptyStringType = getStringLiteralType("");
+ var zeroType = getNumberLiteralType(0);
+ var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" });
+ var resolutionTargets = [];
+ var resolutionResults = [];
+ var resolutionPropertyNames = [];
+ var suggestionCount = 0;
+ var maximumSuggestionCount = 10;
+ var mergedSymbols = [];
+ var symbolLinks = [];
+ var nodeLinks = [];
+ var flowLoopCaches = [];
+ var flowLoopNodes = [];
+ var flowLoopKeys = [];
+ var flowLoopTypes = [];
+ var sharedFlowNodes = [];
+ var sharedFlowTypes = [];
+ var flowNodeReachable = [];
+ var flowNodePostSuper = [];
+ var potentialThisCollisions = [];
+ var potentialNewTargetCollisions = [];
+ var potentialWeakMapSetCollisions = [];
+ var potentialReflectCollisions = [];
+ var awaitedTypeStack = [];
+ var diagnostics = ts.createDiagnosticCollection();
+ var suggestionDiagnostics = ts.createDiagnosticCollection();
+ var typeofTypesByName = new ts.Map(ts.getEntries({
+ string: stringType,
+ number: numberType,
+ bigint: bigintType,
+ boolean: booleanType,
+ symbol: esSymbolType,
+ undefined: undefinedType
+ }));
+ var typeofType = createTypeofType();
+ var _jsxNamespace;
+ var _jsxFactoryEntity;
+ var outofbandVarianceMarkerHandler;
+ var subtypeRelation = new ts.Map();
+ var strictSubtypeRelation = new ts.Map();
+ var assignableRelation = new ts.Map();
+ var comparableRelation = new ts.Map();
+ var identityRelation = new ts.Map();
+ var enumRelation = new ts.Map();
+ var builtinGlobals = ts.createSymbolTable();
+ builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
+ // Extensions suggested for path imports when module resolution is node12 or higher.
+ // The first element of each tuple is the extension a file has.
+ // The second element of each tuple is the extension that should be used in a path import.
+ // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs".
+ var suggestedExtensions = [
+ [".mts", ".mjs"],
+ [".ts", ".js"],
+ [".cts", ".cjs"],
+ [".mjs", ".mjs"],
+ [".js", ".js"],
+ [".cjs", ".cjs"],
+ [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"],
+ [".jsx", ".jsx"],
+ [".json", ".json"],
+ ];
+ initializeTypeChecker();
+ return checker;
+ function getJsxNamespace(location) {
+ if (location) {
+ var file = ts.getSourceFileOfNode(location);
+ if (file) {
+ if (ts.isJsxOpeningFragment(location)) {
+ if (file.localJsxFragmentNamespace) {
+ return file.localJsxFragmentNamespace;
+ }
+ var jsxFragmentPragma = file.pragmas.get("jsxfrag");
+ if (jsxFragmentPragma) {
+ var chosenPragma = ts.isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
+ file.localJsxFragmentFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
+ ts.visitNode(file.localJsxFragmentFactory, markAsSynthetic);
+ if (file.localJsxFragmentFactory) {
+ return file.localJsxFragmentNamespace = ts.getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
+ }
+ }
+ var entity = getJsxFragmentFactoryEntity(location);
+ if (entity) {
+ file.localJsxFragmentFactory = entity;
+ return file.localJsxFragmentNamespace = ts.getFirstIdentifier(entity).escapedText;
+ }
}
- }
- // If we're in an external module, we can't reference value symbols created from UMD export declarations
- if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
- var merged = getMergedSymbol(result);
- if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
- errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name));
+ else {
+ var localJsxNamespace = getLocalJsxNamespace(file);
+ if (localJsxNamespace) {
+ return file.localJsxNamespace = localJsxNamespace;
+ }
}
}
- // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right
- if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
- var candidate = getMergedSymbol(getLateBoundSymbol(result));
- var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
- // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
- if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
- error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
- }
- // And it cannot refer to any declarations which come after it
- else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
- error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
+ }
+ if (!_jsxNamespace) {
+ _jsxNamespace = "React";
+ if (compilerOptions.jsxFactory) {
+ _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
+ ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
+ if (_jsxFactoryEntity) {
+ _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
}
}
- if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
- checkSymbolUsageInExpressionContext(result, name, errorLocation);
- }
- }
- return result;
- }
- function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
- if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
- var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
- if (typeOnlyDeclaration) {
- var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
- var message = isExport
- ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
- : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
- var relatedMessage = isExport
- ? ts.Diagnostics._0_was_exported_here
- : ts.Diagnostics._0_was_imported_here;
- var unescapedName = ts.unescapeLeadingUnderscores(name);
- ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
+ else if (compilerOptions.reactNamespace) {
+ _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
}
}
- }
- function getIsDeferredContext(location, lastLocation) {
- if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
- // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
- return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
- (location.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
- }
- if (lastLocation && lastLocation === location.name) {
- return false;
- }
- // generator functions and async functions are not inlined in control flow when immediately invoked
- if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
- return true;
+ if (!_jsxFactoryEntity) {
+ _jsxFactoryEntity = ts.factory.createQualifiedName(ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
}
- return !ts.getImmediatelyInvokedFunctionExpression(location);
+ return _jsxNamespace;
}
- function isSelfReferenceLocation(node) {
- switch (node.kind) {
- case 244 /* FunctionDeclaration */:
- case 245 /* ClassDeclaration */:
- case 246 /* InterfaceDeclaration */:
- case 248 /* EnumDeclaration */:
- case 247 /* TypeAliasDeclaration */:
- case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
- return true;
- default:
- return false;
+ function getLocalJsxNamespace(file) {
+ if (file.localJsxNamespace) {
+ return file.localJsxNamespace;
}
- }
- function diagnosticName(nameArg) {
- return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
- }
- function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
- for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
- var decl = _a[_i];
- if (decl.kind === 155 /* TypeParameter */) {
- var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
- if (parent === container) {
- return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
- }
+ var jsxPragma = file.pragmas.get("jsx");
+ if (jsxPragma) {
+ var chosenPragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
+ file.localJsxFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
+ ts.visitNode(file.localJsxFactory, markAsSynthetic);
+ if (file.localJsxFactory) {
+ return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
}
}
- return false;
}
- function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
- if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
- return false;
- }
- var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
- var location = container;
- while (location) {
- if (ts.isClassLike(location.parent)) {
- var classSymbol = getSymbolOfNode(location.parent);
- if (!classSymbol) {
- break;
- }
- // Check to see if a static member exists.
- var constructorType = getTypeOfSymbol(classSymbol);
- if (getPropertyOfType(constructorType, name)) {
- error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
- return true;
- }
- // No static member is present.
- // Check if we're in an instance method and look for a relevant instance member.
- if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
- var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
- if (getPropertyOfType(instanceType, name)) {
- error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
- return true;
- }
- }
- }
- location = location.parent;
- }
- return false;
+ function markAsSynthetic(node) {
+ ts.setTextRangePosEnd(node, -1, -1);
+ return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
}
- function checkAndReportErrorForExtendingInterface(errorLocation) {
- var expression = getEntityNameForExtendingInterface(errorLocation);
- if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
- error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
- return true;
- }
- return false;
+ function getEmitResolver(sourceFile, cancellationToken) {
+ // Ensure we have all the type information in place for this file so that all the
+ // emitter questions of this resolver will return the right information.
+ getDiagnostics(sourceFile, cancellationToken);
+ return emitResolver;
}
- /**
- * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
- * but returns undefined if that expression is not an EntityNameExpression.
- */
- function getEntityNameForExtendingInterface(node) {
- switch (node.kind) {
- case 75 /* Identifier */:
- case 194 /* PropertyAccessExpression */:
- return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
- case 216 /* ExpressionWithTypeArguments */:
- if (ts.isEntityNameExpression(node.expression)) {
- return node.expression;
- }
- // falls through
- default:
- return undefined;
+ function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
+ var diagnostic = location
+ ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
+ : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
+ var existing = diagnostics.lookup(diagnostic);
+ if (existing) {
+ return existing;
}
- }
- function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
- var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
- if (meaning === namespaceMeaning) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
- var parent = errorLocation.parent;
- if (symbol) {
- if (ts.isQualifiedName(parent)) {
- ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
- var propName = parent.right.escapedText;
- var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
- if (propType) {
- error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName));
- return true;
- }
- }
- error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
- return true;
- }
+ else {
+ diagnostics.add(diagnostic);
+ return diagnostic;
}
- return false;
}
- function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
- if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
- if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
- error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.unescapeLeadingUnderscores(name));
- return true;
- }
- }
- return false;
+ function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) {
+ var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
+ diagnostic.skippedOn = key;
+ return diagnostic;
}
- function isPrimitiveTypeName(name) {
- return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
+ function createError(location, message, arg0, arg1, arg2, arg3) {
+ return location
+ ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
+ : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
}
- function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
- if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
- error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
- return true;
- }
- return false;
+ function error(location, message, arg0, arg1, arg2, arg3) {
+ var diagnostic = createError(location, message, arg0, arg1, arg2, arg3);
+ diagnostics.add(diagnostic);
+ return diagnostic;
}
- function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
- if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
- if (isPrimitiveTypeName(name)) {
- error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
- return true;
- }
- var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
- if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = isES2015OrLaterConstructorName(name)
- ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
- : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
- error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
- return true;
- }
+ function addErrorOrSuggestion(isError, diagnostic) {
+ if (isError) {
+ diagnostics.add(diagnostic);
}
- return false;
- }
- function isES2015OrLaterConstructorName(n) {
- switch (n) {
- case "Promise":
- case "Symbol":
- case "Map":
- case "WeakMap":
- case "Set":
- case "WeakSet":
- return true;
+ else {
+ suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
}
- return false;
}
- function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
- if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
- if (symbol) {
- error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
- return true;
- }
- }
- else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
- if (symbol) {
- error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
- return true;
+ function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
+ // Pseudo-synthesized input node
+ if (location.pos < 0 || location.end < 0) {
+ if (!isError) {
+ return; // Drop suggestions (we have no span to suggest on)
}
- }
- return false;
- }
- function checkResolvedBlockScopedVariable(result, errorLocation) {
- ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
- if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
- // constructor functions aren't block scoped
+ // Issue errors globally
+ var file = ts.getSourceFileOfNode(location);
+ addErrorOrSuggestion(isError, "message" in message ? ts.createFileDiagnostic(file, 0, 0, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForFileFromMessageChain(file, message)); // eslint-disable-line no-in-operator
return;
}
- // Block-scoped variables cannot be used before their definition
- var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
- if (declaration === undefined)
- return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
- if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
- var diagnosticMessage = void 0;
- var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
- if (result.flags & 2 /* BlockScopedVariable */) {
- diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
- }
- else if (result.flags & 32 /* Class */) {
- diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
- }
- else if (result.flags & 256 /* RegularEnum */) {
- diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
- }
- else {
- ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
- if (compilerOptions.preserveConstEnums) {
- diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
- }
- }
- if (diagnosticMessage) {
- ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
- }
- }
- }
- /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
- * If at any point current node is equal to 'parent' node - return true.
- * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
- */
- function isSameScopeDescendentOf(initial, parent, stopAt) {
- return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
+ addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
}
- function getAnyImportSyntax(node) {
- switch (node.kind) {
- case 253 /* ImportEqualsDeclaration */:
- return node;
- case 255 /* ImportClause */:
- return node.parent;
- case 256 /* NamespaceImport */:
- return node.parent.parent;
- case 258 /* ImportSpecifier */:
- return node.parent.parent.parent;
- default:
- return undefined;
+ function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
+ var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
+ if (maybeMissingAwait) {
+ var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
+ ts.addRelatedInfo(diagnostic, related);
}
+ return diagnostic;
}
- function getDeclarationOfAliasSymbol(symbol) {
- return ts.find(symbol.declarations, isAliasSymbolDeclaration);
+ function addDeprecatedSuggestionWorker(declarations, diagnostic) {
+ var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations);
+ if (deprecatedTag) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here));
+ }
+ // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates.
+ suggestionDiagnostics.add(diagnostic);
+ return diagnostic;
}
- /**
- * 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 * as ns from ...
- * export =
- * export default
- * module.exports =
- * {}
- * {name: }
- */
- function isAliasSymbolDeclaration(node) {
- return node.kind === 253 /* ImportEqualsDeclaration */ ||
- node.kind === 252 /* NamespaceExportDeclaration */ ||
- node.kind === 255 /* ImportClause */ && !!node.name ||
- node.kind === 256 /* NamespaceImport */ ||
- node.kind === 262 /* NamespaceExport */ ||
- node.kind === 258 /* ImportSpecifier */ ||
- node.kind === 263 /* ExportSpecifier */ ||
- node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
- ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
- ts.isPropertyAccessExpression(node)
- && ts.isBinaryExpression(node.parent)
- && node.parent.left === node
- && node.parent.operatorToken.kind === 62 /* EqualsToken */
- && isAliasableOrJsExpression(node.parent.right) ||
- node.kind === 282 /* ShorthandPropertyAssignment */ ||
- node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
+ function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
+ var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity);
+ return addDeprecatedSuggestionWorker(declarations, diagnostic);
}
- function isAliasableOrJsExpression(e) {
- return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
+ function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
+ var diagnostic = deprecatedEntity
+ ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity)
+ : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString);
+ return addDeprecatedSuggestionWorker(declaration, diagnostic);
}
- function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
- if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
- var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
- var resolved_4 = resolveExternalModuleSymbol(immediate);
- markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
- return resolved_4;
- }
- var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
- checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
- return resolved;
+ function createSymbol(flags, name, checkFlags) {
+ symbolCount++;
+ var symbol = new Symbol(flags | 33554432 /* Transient */, name);
+ symbol.checkFlags = checkFlags || 0;
+ return symbol;
}
- function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
- if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
- var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
- var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
- var message = isExport
- ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
- : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
- var relatedMessage = isExport
- ? ts.Diagnostics._0_was_exported_here
- : ts.Diagnostics._0_was_imported_here;
- // Non-null assertion is safe because the optionality comes from ImportClause,
- // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
- var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
- ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
- }
+ function getExcludedSymbolFlags(flags) {
+ var result = 0;
+ if (flags & 2 /* BlockScopedVariable */)
+ result |= 111551 /* BlockScopedVariableExcludes */;
+ if (flags & 1 /* FunctionScopedVariable */)
+ result |= 111550 /* FunctionScopedVariableExcludes */;
+ if (flags & 4 /* Property */)
+ result |= 0 /* PropertyExcludes */;
+ if (flags & 8 /* EnumMember */)
+ result |= 900095 /* EnumMemberExcludes */;
+ if (flags & 16 /* Function */)
+ result |= 110991 /* FunctionExcludes */;
+ if (flags & 32 /* Class */)
+ result |= 899503 /* ClassExcludes */;
+ if (flags & 64 /* Interface */)
+ result |= 788872 /* InterfaceExcludes */;
+ if (flags & 256 /* RegularEnum */)
+ result |= 899327 /* RegularEnumExcludes */;
+ if (flags & 128 /* ConstEnum */)
+ result |= 899967 /* ConstEnumExcludes */;
+ if (flags & 512 /* ValueModule */)
+ result |= 110735 /* ValueModuleExcludes */;
+ if (flags & 8192 /* Method */)
+ result |= 103359 /* MethodExcludes */;
+ if (flags & 32768 /* GetAccessor */)
+ result |= 46015 /* GetAccessorExcludes */;
+ if (flags & 65536 /* SetAccessor */)
+ result |= 78783 /* SetAccessorExcludes */;
+ if (flags & 262144 /* TypeParameter */)
+ result |= 526824 /* TypeParameterExcludes */;
+ if (flags & 524288 /* TypeAlias */)
+ result |= 788968 /* TypeAliasExcludes */;
+ if (flags & 2097152 /* Alias */)
+ result |= 2097152 /* AliasExcludes */;
+ return result;
}
- function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
- var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
- if (exportValue) {
- return getPropertyOfType(getTypeOfSymbol(exportValue), name);
+ function recordMergedSymbol(target, source) {
+ if (!source.mergeId) {
+ source.mergeId = nextMergeId;
+ nextMergeId++;
}
- var exportSymbol = moduleSymbol.exports.get(name);
- var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
- return resolved;
+ mergedSymbols[source.mergeId] = target;
}
- function isSyntacticDefault(node) {
- return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
+ function cloneSymbol(symbol) {
+ var result = createSymbol(symbol.flags, symbol.escapedName);
+ result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
+ result.parent = symbol.parent;
+ if (symbol.valueDeclaration)
+ result.valueDeclaration = symbol.valueDeclaration;
+ if (symbol.constEnumOnlyModule)
+ result.constEnumOnlyModule = true;
+ if (symbol.members)
+ result.members = new ts.Map(symbol.members);
+ if (symbol.exports)
+ result.exports = new ts.Map(symbol.exports);
+ recordMergedSymbol(result, symbol);
+ return result;
}
- function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
- if (!allowSyntheticDefaultImports) {
- return false;
- }
- // Declaration files (and ambient modules)
- if (!file || file.isDeclarationFile) {
- // Definitely cannot have a synthetic default if they have a syntactic default member specified
- var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
- if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
- return false;
+ /**
+ * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
+ * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
+ */
+ function mergeSymbol(target, source, unidirectional) {
+ if (unidirectional === void 0) { unidirectional = false; }
+ if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
+ (source.flags | target.flags) & 67108864 /* Assignment */) {
+ if (source === target) {
+ // This can happen when an export assigned namespace exports something also erroneously exported at the top level
+ // See `declarationFileNoCrashOnExtraExportModifier` for an example
+ return target;
}
- // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
- // So we check a bit more,
- if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
- // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
- // it definitely is a module and does not have a synthetic default
- return false;
+ if (!(target.flags & 33554432 /* Transient */)) {
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
- // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
- // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
- // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
- return true;
- }
- // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
- if (!ts.isSourceFileJS(file)) {
- return hasExportAssignmentSymbol(moduleSymbol);
- }
- // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker
- return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
- }
- function getTargetOfImportClause(node, dontResolveAlias) {
- var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
- if (moduleSymbol) {
- var exportDefaultSymbol = void 0;
- if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
- exportDefaultSymbol = moduleSymbol;
+ // Javascript static-property-assignment declarations always merge, even though they are also values
+ if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
+ // reset flag when merging instantiated module into value module that has only const enums
+ target.constEnumOnlyModule = false;
}
- else {
- exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
+ target.flags |= source.flags;
+ if (source.valueDeclaration) {
+ ts.setValueDeclaration(target, source.valueDeclaration);
}
- var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
- if (!exportDefaultSymbol && !hasSyntheticDefault) {
- if (hasExportAssignmentSymbol(moduleSymbol)) {
- var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
- var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
- var exportAssignment = exportEqualsSymbol.valueDeclaration;
- var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
- ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName));
- }
- else {
- reportNonDefaultExport(moduleSymbol, node);
- }
+ ts.addRange(target.declarations, source.declarations);
+ if (source.members) {
+ if (!target.members)
+ target.members = ts.createSymbolTable();
+ mergeSymbolTable(target.members, source.members, unidirectional);
}
- else if (hasSyntheticDefault) {
- // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
- var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
- return resolved;
+ if (source.exports) {
+ if (!target.exports)
+ target.exports = ts.createSymbolTable();
+ mergeSymbolTable(target.exports, source.exports, unidirectional);
+ }
+ if (!unidirectional) {
+ recordMergedSymbol(target, source);
}
- markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
- return exportDefaultSymbol;
}
- }
- function reportNonDefaultExport(moduleSymbol, node) {
- var _a, _b;
- if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
- error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol));
+ else if (target.flags & 1024 /* NamespaceModule */) {
+ // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
+ // as we will already report a "Declaration name conflicts..." error, and this error
+ // won't make much sense.
+ if (target !== globalThisSymbol) {
+ error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
+ }
}
- else {
- var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
- var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
- if (exportStar) {
- var defaultExport = ts.find(exportStar.declarations, function (decl) {
- var _a, _b;
- return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)));
+ else { // error
+ var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
+ var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
+ var message = isEitherEnum
+ ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
+ : isEitherBlockScoped_1
+ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
+ : ts.Diagnostics.Duplicate_identifier_0;
+ var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
+ var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
+ var symbolName_1 = symbolToString(source);
+ // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
+ if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
+ var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
+ var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
+ var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, "".concat(firstFile_1.path, "|").concat(secondFile_1.path), function () {
+ return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() });
});
- if (defaultExport) {
- ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
+ var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
+ return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
+ });
+ addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
+ addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
+ }
+ else {
+ addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
+ addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
+ }
+ }
+ return target;
+ function addDuplicateLocations(locs, symbol) {
+ if (symbol.declarations) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ ts.pushIfUnique(locs, decl);
}
}
}
}
- function getTargetOfNamespaceImport(node, dontResolveAlias) {
- var moduleSpecifier = node.parent.parent.moduleSpecifier;
- var immediate = resolveExternalModuleName(node, moduleSpecifier);
- var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
- markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
- return resolved;
- }
- function getTargetOfNamespaceExport(node, dontResolveAlias) {
- var moduleSpecifier = node.parent.moduleSpecifier;
- var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
- var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
- markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
- return resolved;
+ function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
+ ts.forEach(target.declarations, function (node) {
+ addDuplicateDeclarationError(node, message, symbolName, source.declarations);
+ });
}
- // This function creates a synthetic symbol that combines the value side of one symbol with the
- // type/namespace side of another symbol. Consider this example:
- //
- // declare module graphics {
- // interface Point {
- // x: number;
- // y: number;
- // }
- // }
- // declare var graphics: {
- // Point: new (x: number, y: number) => graphics.Point;
- // }
- // declare module "graphics" {
- // export = graphics;
- // }
- //
- // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
- // property with the type/namespace side interface 'Point'.
- function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
- if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
- return unknownSymbol;
- }
- if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
- return valueSymbol;
+ function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
+ var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
+ var err = lookupOrIssueError(errorNode, message, symbolName);
+ var _loop_7 = function (relatedNode) {
+ var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
+ if (adjustedNode === errorNode)
+ return "continue";
+ err.relatedInformation = err.relatedInformation || [];
+ var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
+ var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
+ if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; }))
+ return "continue";
+ ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
+ };
+ for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
+ var relatedNode = _a[_i];
+ _loop_7(relatedNode);
}
- var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
- result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
- result.parent = valueSymbol.parent || typeSymbol.parent;
- if (valueSymbol.valueDeclaration)
- result.valueDeclaration = valueSymbol.valueDeclaration;
- if (typeSymbol.members)
- result.members = ts.cloneMap(typeSymbol.members);
- if (valueSymbol.exports)
- result.exports = ts.cloneMap(valueSymbol.exports);
- return result;
}
- function getExportOfModule(symbol, specifier, dontResolveAlias) {
- var _a;
- if (symbol.flags & 1536 /* Module */) {
- var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
- var exportSymbol = getExportsOfSymbol(symbol).get(name);
- var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
- return resolved;
- }
+ function combineSymbolTables(first, second) {
+ if (!(first === null || first === void 0 ? void 0 : first.size))
+ return second;
+ if (!(second === null || second === void 0 ? void 0 : second.size))
+ return first;
+ var combined = ts.createSymbolTable();
+ mergeSymbolTable(combined, first);
+ mergeSymbolTable(combined, second);
+ return combined;
}
- function getPropertyOfVariable(symbol, name) {
- if (symbol.flags & 3 /* Variable */) {
- var typeAnnotation = symbol.valueDeclaration.type;
- if (typeAnnotation) {
- return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
- }
- }
+ function mergeSymbolTable(target, source, unidirectional) {
+ if (unidirectional === void 0) { unidirectional = false; }
+ source.forEach(function (sourceSymbol, id) {
+ var targetSymbol = target.get(id);
+ target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
+ });
}
- function getExternalModuleMember(node, specifier, dontResolveAlias) {
- var _a;
- if (dontResolveAlias === void 0) { dontResolveAlias = false; }
- var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
- var name = specifier.propertyName || specifier.name;
- var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
- var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
- if (targetSymbol) {
- if (name.escapedText) {
- if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
- return moduleSymbol;
- }
- var symbolFromVariable = void 0;
- // First check if module was specified with "export=". If so, get the member from the resolved type
- if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
- symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
- }
- else {
- symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
- }
- // if symbolFromVariable is export - get its final target
- symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
- var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
- if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
- var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
- if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
- symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
+ function mergeModuleAugmentation(moduleName) {
+ var _a, _b, _c;
+ var moduleAugmentation = moduleName.parent;
+ if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) {
+ // this is a combined symbol for multiple augmentations within the same file.
+ // its symbol already has accumulated information for all declarations
+ // so we need to add it just once - do the work only for first declaration
+ ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
+ return;
+ }
+ if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
+ mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
+ }
+ else {
+ // find a module that about to be augmented
+ // do not validate names of augmentations that are defined in ambient context
+ var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
+ ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
+ : undefined;
+ var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
+ if (!mainModule_1) {
+ return;
+ }
+ // obtain item referenced by 'export='
+ mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
+ if (mainModule_1.flags & 1920 /* Namespace */) {
+ // If we're merging an augmentation to a pattern ambient module, we want to
+ // perform the merge unidirectionally from the augmentation ('a.foo') to
+ // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
+ // all the exports both from the pattern and from the augmentation, but
+ // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
+ if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
+ var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
+ if (!patternAmbientModuleAugmentations) {
+ patternAmbientModuleAugmentations = new ts.Map();
}
+ // moduleName will be a StringLiteral since this is not `declare global`.
+ patternAmbientModuleAugmentations.set(moduleName.text, merged);
}
- var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
- combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
- symbolFromModule || symbolFromVariable;
- if (!symbol) {
- var moduleName = getFullyQualifiedName(moduleSymbol, node);
- var declarationName = ts.declarationNameToString(name);
- var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
- if (suggestion !== undefined) {
- var suggestionName = symbolToString(suggestion);
- var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
- if (suggestion.valueDeclaration) {
- ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
- }
- }
- else {
- if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
- }
- else {
- reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
+ else {
+ if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) {
+ // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
+ var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
+ for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) {
+ var _e = _d[_i], key = _e[0], value = _e[1];
+ if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
+ mergeSymbol(resolvedExports.get(key), value);
+ }
}
}
+ mergeSymbol(mainModule_1, moduleAugmentation.symbol);
}
- return symbol;
- }
- }
- }
- function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
- var _a;
- var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
- var exports = moduleSymbol.exports;
- if (localSymbol) {
- var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
- if (exportedEqualsSymbol) {
- getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
}
else {
- var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
- var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
- error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
- ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
- return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
- })));
+ // moduleName will be a StringLiteral since this is not `declare global`.
+ error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
}
}
- else {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
- }
}
- function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
- if (moduleKind >= ts.ModuleKind.ES2015) {
- var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
- ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
- error(name, message, declarationName);
- }
- else {
- if (ts.isInJSFile(node)) {
- var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
- ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
- error(name, message, declarationName);
+ function addToSymbolTable(target, source, message) {
+ source.forEach(function (sourceSymbol, id) {
+ var targetSymbol = target.get(id);
+ if (targetSymbol) {
+ // Error on redeclarations
+ ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
}
else {
- var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
- ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
- error(name, message, declarationName, declarationName, moduleName);
+ target.set(id, sourceSymbol);
}
+ });
+ function addDeclarationDiagnostic(id, message) {
+ return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
}
}
- function getTargetOfImportSpecifier(node, dontResolveAlias) {
- var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
- return resolved;
- }
- function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
- var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
- return resolved;
- }
- function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
- var resolved = node.parent.parent.moduleSpecifier ?
- getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
- resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
- return resolved;
- }
- function getTargetOfExportAssignment(node, dontResolveAlias) {
- var expression = ts.isExportAssignment(node) ? node.expression : node.right;
- var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
- markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
- return resolved;
- }
- function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
- if (ts.isClassExpression(expression)) {
- return checkExpressionCached(expression).symbol;
- }
- if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
- return undefined;
- }
- var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
- if (aliasLike) {
- return aliasLike;
- }
- checkExpressionCached(expression);
- return getNodeLinks(expression).resolvedSymbol;
- }
- function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
- var expression = node.initializer;
- return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
- }
- function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
- if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
- return undefined;
- }
- return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
- }
- function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
- if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
- switch (node.kind) {
- case 253 /* ImportEqualsDeclaration */:
- return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
- case 255 /* ImportClause */:
- return getTargetOfImportClause(node, dontRecursivelyResolve);
- case 256 /* NamespaceImport */:
- return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
- case 262 /* NamespaceExport */:
- return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
- case 258 /* ImportSpecifier */:
- return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
- case 263 /* ExportSpecifier */:
- return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
- case 259 /* ExportAssignment */:
- case 209 /* BinaryExpression */:
- return getTargetOfExportAssignment(node, dontRecursivelyResolve);
- case 252 /* NamespaceExportDeclaration */:
- return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
- case 282 /* ShorthandPropertyAssignment */:
- return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
- case 281 /* PropertyAssignment */:
- return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
- case 194 /* PropertyAccessExpression */:
- return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
- default:
- return ts.Debug.fail();
- }
+ function getSymbolLinks(symbol) {
+ if (symbol.flags & 33554432 /* Transient */)
+ return symbol;
+ var id = getSymbolId(symbol);
+ return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
}
- /**
- * Indicates that a symbol is an alias that does not merge with a local declaration.
- * OR Is a JSContainer which may merge an alias with a local declaration
- */
- function isNonLocalAlias(symbol, excludes) {
- if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
- if (!symbol)
- return false;
- return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
+ function getNodeLinks(node) {
+ var nodeId = getNodeId(node);
+ return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
}
- function resolveSymbol(symbol, dontResolveAlias) {
- return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
+ function isGlobalSourceFile(node) {
+ return node.kind === 303 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
- function resolveAlias(symbol) {
- ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.target) {
- links.target = resolvingSymbol;
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- var target = getTargetOfAliasDeclaration(node);
- if (links.target === resolvingSymbol) {
- links.target = target || unknownSymbol;
- }
- else {
- error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
+ function getSymbol(symbols, name, meaning) {
+ if (meaning) {
+ var symbol = getMergedSymbol(symbols.get(name));
+ if (symbol) {
+ ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
+ if (symbol.flags & meaning) {
+ return symbol;
+ }
+ if (symbol.flags & 2097152 /* Alias */) {
+ var target = resolveAlias(symbol);
+ // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
+ if (target === unknownSymbol || target.flags & meaning) {
+ return symbol;
+ }
+ }
}
}
- else if (links.target === resolvingSymbol) {
- links.target = unknownSymbol;
- }
- return links.target;
- }
- function tryResolveAlias(symbol) {
- var links = getSymbolLinks(symbol);
- if (links.target !== resolvingSymbol) {
- return resolveAlias(symbol);
- }
- return undefined;
+ // return undefined if we can't find a symbol.
}
/**
- * Marks a symbol as type-only if its declaration is syntactically type-only.
- * If it is not itself marked type-only, but resolves to a type-only alias
- * somewhere in its resolution chain, save a reference to the type-only alias declaration
- * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
- *
- * This function is called on each alias declaration that could be type-only or resolve to
- * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
- * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
- * and issue an error if so.
- *
- * @param aliasDeclaration The alias declaration not marked as type-only
- * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
- * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
- * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
- * must still be checked for a type-only marker, overwriting the previous negative result if found.
- * @param immediateTarget The symbol to which the alias declaration immediately resolves
- * @param finalTarget The symbol to which the alias declaration ultimately resolves
- * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
+ * Get symbols that represent parameter-property-declaration as parameter and as property declaration
+ * @param parameter a parameterDeclaration node
+ * @param parameterName a name of the parameter to get the symbols for.
+ * @return a tuple of two symbols
*/
- function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
- if (!aliasDeclaration)
- return false;
- // If the declaration itself is type-only, mark it and return.
- // No need to check what it resolves to.
- var sourceSymbol = getSymbolOfNode(aliasDeclaration);
- if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
- var links_1 = getSymbolLinks(sourceSymbol);
- links_1.typeOnlyDeclaration = aliasDeclaration;
- return true;
- }
- var links = getSymbolLinks(sourceSymbol);
- return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
- || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
- }
- function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
- var _a, _b, _c;
- if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
- var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
- var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
- aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
- }
- return !!aliasDeclarationLinks.typeOnlyDeclaration;
- }
- /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
- function getTypeOnlyAliasDeclaration(symbol) {
- if (!(symbol.flags & 2097152 /* Alias */)) {
- return undefined;
+ function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
+ var constructorDeclaration = parameter.parent;
+ var classDeclaration = parameter.parent.parent;
+ var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
+ var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
+ if (parameterSymbol && propertySymbol) {
+ return [parameterSymbol, propertySymbol];
}
- var links = getSymbolLinks(symbol);
- return links.typeOnlyDeclaration || undefined;
+ return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
}
- function markExportAsReferenced(node) {
- var symbol = getSymbolOfNode(node);
- var target = resolveAlias(symbol);
- if (target) {
- var markAlias = target === unknownSymbol ||
- ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
- if (markAlias) {
- markAliasSymbolAsReferenced(symbol);
+ function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
+ var declarationFile = ts.getSourceFileOfNode(declaration);
+ var useFile = ts.getSourceFileOfNode(usage);
+ var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
+ if (declarationFile !== useFile) {
+ if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
+ (!ts.outFile(compilerOptions)) ||
+ isInTypeQuery(usage) ||
+ declaration.flags & 8388608 /* Ambient */) {
+ // nodes are in different files and order cannot be determined
+ return true;
+ }
+ // declaration is after usage
+ // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
+ if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
+ return true;
}
+ var sourceFiles = host.getSourceFiles();
+ return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
}
- }
- // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
- // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
- // the alias as an expression (which recursively takes us back here if the target references another alias).
- function markAliasSymbolAsReferenced(symbol) {
- var links = getSymbolLinks(symbol);
- if (!links.referenced) {
- links.referenced = true;
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- // We defer checking of the reference of an `import =` until the import itself is referenced,
- // This way a chain of imports can be elided if ultimately the final input is only used in a type
- // position.
- if (ts.isInternalModuleImportEqualsDeclaration(node)) {
- var target = resolveSymbol(symbol);
- if (target === unknownSymbol || target.flags & 111551 /* Value */) {
- // import foo =
- checkExpressionCached(node.moduleReference);
+ if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
+ // declaration is before usage
+ if (declaration.kind === 202 /* BindingElement */) {
+ // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
+ var errorBindingElement = ts.getAncestor(usage, 202 /* BindingElement */);
+ if (errorBindingElement) {
+ return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
+ declaration.pos < errorBindingElement.pos;
}
+ // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
+ return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 253 /* VariableDeclaration */), usage);
}
+ else if (declaration.kind === 253 /* VariableDeclaration */) {
+ // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
+ return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
+ }
+ else if (ts.isClassDeclaration(declaration)) {
+ // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
+ return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
+ }
+ else if (ts.isPropertyDeclaration(declaration)) {
+ // still might be illegal if a self-referencing property initializer (eg private x = this.x)
+ return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
+ }
+ else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
+ // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
+ return !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields
+ && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
+ && isUsedInFunctionOrInstanceProperty(usage, declaration));
+ }
+ return true;
}
- }
- // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
- // but their usage in value positions must be tracked to determine if the import can be type-only.
- function markConstEnumAliasAsReferenced(symbol) {
- var links = getSymbolLinks(symbol);
- if (!links.constEnumReferenced) {
- links.constEnumReferenced = true;
- }
- }
- // This function is only for imports with entity names
- function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
- // There are three things we might try to look for. In the following examples,
- // the search term is enclosed in |...|:
- //
- // import a = |b|; // Namespace
- // import a = |b.c|; // Value, type, namespace
- // import a = |b.c|.d; // Namespace
- if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
- entityName = entityName.parent;
- }
- // Check for case 1 and 3 in the above example
- if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
- return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
+ // declaration is after usage, but it can still be legal if usage is deferred:
+ // 1. inside an export specifier
+ // 2. inside a function
+ // 3. inside an instance property initializer, a reference to a non-instance property
+ // (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
+ // 4. inside a static property initializer, a reference to a static method in the same class
+ // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
+ // or if usage is in a type context:
+ // 1. inside a type query (typeof in type position)
+ // 2. inside a jsdoc comment
+ if (usage.parent.kind === 274 /* ExportSpecifier */ || (usage.parent.kind === 270 /* ExportAssignment */ && usage.parent.isExportEquals)) {
+ // export specifiers do not use the variable, they only make it available for use
+ return true;
}
- else {
- // Case 2 in above example
- // entityName.kind could be a QualifiedName or a Missing identifier
- ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
- return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
+ // When resolving symbols for exports, the `usage` location passed in can be the export site directly
+ if (usage.kind === 270 /* ExportAssignment */ && usage.isExportEquals) {
+ return true;
}
- }
- function getFullyQualifiedName(symbol, containingLocation) {
- return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
- }
- /**
- * Resolves a qualified name and any involved aliases.
- */
- function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
- if (ts.nodeIsMissing(name)) {
- return undefined;
+ if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
+ return true;
}
- var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
- var symbol;
- if (name.kind === 75 /* Identifier */) {
- var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
- var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
- symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
- if (!symbol) {
- return getMergedSymbol(symbolFromJSPrototype);
+ if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
+ if (ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields
+ && ts.getContainingClass(declaration)
+ && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
+ return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
}
- }
- else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
- var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
- var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
- var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
- if (!namespace || ts.nodeIsMissing(right)) {
- return undefined;
+ else {
+ return true;
}
- else if (namespace === unknownSymbol) {
- return namespace;
+ }
+ return false;
+ function usageInTypeDeclaration() {
+ return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
+ }
+ function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
+ switch (declaration.parent.parent.kind) {
+ case 236 /* VariableStatement */:
+ case 241 /* ForStatement */:
+ case 243 /* ForOfStatement */:
+ // variable statement/for/for-of statement case,
+ // use site should not be inside variable declaration (initializer of declaration or binding element)
+ if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
+ return true;
+ }
+ break;
}
- if (ts.isInJSFile(name)) {
- if (namespace.valueDeclaration &&
- ts.isVariableDeclaration(namespace.valueDeclaration) &&
- namespace.valueDeclaration.initializer &&
- isCommonJsRequire(namespace.valueDeclaration.initializer)) {
- var moduleName = namespace.valueDeclaration.initializer.arguments[0];
- var moduleSym = resolveExternalModuleName(moduleName, moduleName);
- if (moduleSym) {
- var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
- if (resolvedModuleSymbol) {
- namespace = resolvedModuleSymbol;
+ // ForIn/ForOf case - use site should not be used in expression part
+ var grandparent = declaration.parent.parent;
+ return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
+ }
+ function isUsedInFunctionOrInstanceProperty(usage, declaration) {
+ return !!ts.findAncestor(usage, function (current) {
+ if (current === declContainer) {
+ return "quit";
+ }
+ if (ts.isFunctionLike(current)) {
+ return true;
+ }
+ if (ts.isClassStaticBlockDeclaration(current)) {
+ return declaration.pos < usage.pos;
+ }
+ var propertyDeclaration = ts.tryCast(current.parent, ts.isPropertyDeclaration);
+ if (propertyDeclaration) {
+ var initializerOfProperty = propertyDeclaration.initializer === current;
+ if (initializerOfProperty) {
+ if (ts.isStatic(current.parent)) {
+ if (declaration.kind === 168 /* MethodDeclaration */) {
+ return true;
+ }
+ if (ts.isPropertyDeclaration(declaration) && ts.getContainingClass(usage) === ts.getContainingClass(declaration)) {
+ var propName = declaration.name;
+ if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
+ var type = getTypeOfSymbol(getSymbolOfNode(declaration));
+ var staticBlocks = ts.filter(declaration.parent.members, ts.isClassStaticBlockDeclaration);
+ if (isPropertyInitializedInStaticBlocks(propName, type, staticBlocks, declaration.parent.pos, current.pos)) {
+ return true;
+ }
+ }
+ }
+ }
+ else {
+ var isDeclarationInstanceProperty = declaration.kind === 166 /* PropertyDeclaration */ && !ts.isStatic(declaration);
+ if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
+ return true;
+ }
}
}
}
+ return false;
+ });
+ }
+ /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
+ function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
+ // always legal if usage is after declaration
+ if (usage.end > declaration.end) {
+ return false;
}
- symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
- if (!symbol) {
- if (!ignoreErrors) {
- error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
+ // still might be legal if usage is deferred (e.g. x: any = () => this.x)
+ // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
+ var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
+ if (node === declaration) {
+ return "quit";
}
- return undefined;
- }
- }
- else {
- throw ts.Debug.assertNever(name, "Unknown entity name kind.");
- }
- ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
- if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
- markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
+ switch (node.kind) {
+ case 213 /* ArrowFunction */:
+ return true;
+ case 166 /* PropertyDeclaration */:
+ // even when stopping at any property declaration, they need to come from the same class
+ return stopAtAnyPropertyDeclaration &&
+ (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
+ || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
+ ? "quit" : true;
+ case 234 /* Block */:
+ switch (node.parent.kind) {
+ case 171 /* GetAccessor */:
+ case 168 /* MethodDeclaration */:
+ case 172 /* SetAccessor */:
+ return true;
+ default:
+ return false;
+ }
+ default:
+ return false;
+ }
+ });
+ return ancestorChangingReferenceScope === undefined;
}
- return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
}
- /**
- * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
- * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
- * name resolution won't work either.
- * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
- */
- function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
- if (isJSDocTypeReference(name.parent)) {
- var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
- if (secondaryLocation) {
- return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
+ function useOuterVariableScopeInParameter(result, location, lastLocation) {
+ var target = ts.getEmitScriptTarget(compilerOptions);
+ var functionLocation = location;
+ if (ts.isParameter(lastLocation)
+ && functionLocation.body
+ && result.valueDeclaration
+ && result.valueDeclaration.pos >= functionLocation.body.pos
+ && result.valueDeclaration.end <= functionLocation.body.end) {
+ // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
+ // - static field in a class expression
+ // - optional chaining pre-es2020
+ // - nullish coalesce pre-es2020
+ // - spread assignment in binding pattern pre-es2017
+ if (target >= 2 /* ES2015 */) {
+ var links = getNodeLinks(functionLocation);
+ if (links.declarationRequiresScopeChange === undefined) {
+ links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
+ }
+ return !links.declarationRequiresScopeChange;
}
}
- }
- function getAssignmentDeclarationLocation(node) {
- var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
- if (typeAlias) {
- return;
- }
- var host = ts.getJSDocHost(node);
- if (ts.isExpressionStatement(host) &&
- ts.isBinaryExpression(host.expression) &&
- ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
- // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
- var symbol = getSymbolOfNode(host.expression.left);
- if (symbol) {
- return getDeclarationOfJSPrototypeContainer(symbol);
- }
+ return false;
+ function requiresScopeChange(node) {
+ return requiresScopeChangeWorker(node.name)
+ || !!node.initializer && requiresScopeChangeWorker(node.initializer);
}
- if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
- ts.isBinaryExpression(host.parent.parent) &&
- ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
- // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
- var symbol = getSymbolOfNode(host.parent.parent.left);
- if (symbol) {
- return getDeclarationOfJSPrototypeContainer(symbol);
+ function requiresScopeChangeWorker(node) {
+ switch (node.kind) {
+ case 213 /* ArrowFunction */:
+ case 212 /* FunctionExpression */:
+ case 255 /* FunctionDeclaration */:
+ case 170 /* Constructor */:
+ // do not descend into these
+ return false;
+ case 168 /* MethodDeclaration */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 294 /* PropertyAssignment */:
+ return requiresScopeChangeWorker(node.name);
+ case 166 /* PropertyDeclaration */:
+ // static properties in classes introduce temporary variables
+ if (ts.hasStaticModifier(node)) {
+ return target < 99 /* ESNext */ || !useDefineForClassFields;
+ }
+ return requiresScopeChangeWorker(node.name);
+ default:
+ // null coalesce and optional chain pre-es2020 produce temporary variables
+ if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
+ return target < 7 /* ES2020 */;
+ }
+ if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
+ return target < 4 /* ES2017 */;
+ }
+ if (ts.isTypeNode(node))
+ return false;
+ return ts.forEachChild(node, requiresScopeChangeWorker) || false;
}
}
- var sig = ts.getEffectiveJSDocHost(node);
- if (sig && ts.isFunctionLike(sig)) {
- var symbol = getSymbolOfNode(sig);
- return symbol && symbol.valueDeclaration;
- }
- }
- function getDeclarationOfJSPrototypeContainer(symbol) {
- var decl = symbol.parent.valueDeclaration;
- if (!decl) {
- return undefined;
- }
- var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
- ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
- undefined;
- return initializer || decl;
}
/**
- * Get the real symbol of a declaration with an expando initializer.
+ * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
+ * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
+ * the given name can be found.
*
- * Normally, declarations have an associated symbol, but when a declaration has an expando
- * initializer, the expando's symbol is the one that has all the members merged into it.
+ * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
*/
- function getExpandoSymbol(symbol) {
- var decl = symbol.valueDeclaration;
- if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
- return undefined;
- }
- var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
- if (init) {
- var initSymbol = getSymbolOfNode(init);
- if (initSymbol) {
- return mergeJSSymbols(initSymbol, symbol);
- }
- }
- }
- function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
- }
- function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
- if (isForAugmentation === void 0) { isForAugmentation = false; }
- return ts.isStringLiteralLike(moduleReferenceExpression)
- ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
- : undefined;
+ function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) {
+ if (excludeGlobals === void 0) { excludeGlobals = false; }
+ return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol);
}
- function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
- if (isForAugmentation === void 0) { isForAugmentation = false; }
- if (ts.startsWith(moduleReference, "@types/")) {
- var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
- var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
- error(errorNode, diag, withoutAtTypePrefix, moduleReference);
+ function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) {
+ var _a, _b, _c;
+ var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
+ var result;
+ var lastLocation;
+ var lastSelfReferenceLocation;
+ var propertyWithInvalidInitializer;
+ var associatedDeclarationForContainingInitializerOrBindingName;
+ var withinDeferredContext = false;
+ var errorLocation = location;
+ var grandparent;
+ var isInExternalModule = false;
+ loop: while (location) {
+ // Locals of a source file are not in scope (because they get merged into the global symbol table)
+ if (location.locals && !isGlobalSourceFile(location)) {
+ if (result = lookup(location.locals, name, meaning)) {
+ var useResult = true;
+ if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
+ // symbol lookup restrictions for function-like declarations
+ // - Type parameters of a function are in scope in the entire function declaration, including the parameter
+ // list and return type. However, local types are only in scope in the function body.
+ // - parameters are only in the scope of function body
+ // This restriction does not apply to JSDoc comment types because they are parented
+ // at a higher level than type parameters would normally be
+ if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 318 /* JSDocComment */) {
+ useResult = result.flags & 262144 /* TypeParameter */
+ // type parameters are visible in parameter list, return type and type parameter list
+ ? lastLocation === location.type ||
+ lastLocation.kind === 163 /* Parameter */ ||
+ lastLocation.kind === 162 /* TypeParameter */
+ // local types not visible outside the function body
+ : false;
+ }
+ if (meaning & result.flags & 3 /* Variable */) {
+ // expression inside parameter will lookup as normal variable scope when targeting es2015+
+ if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
+ useResult = false;
+ }
+ else if (result.flags & 1 /* FunctionScopedVariable */) {
+ // parameters are visible only inside function body, parameter list and return type
+ // technically for parameter list case here we might mix parameters and variables declared in function,
+ // however it is detected separately when checking initializers of parameters
+ // to make sure that they reference no variables declared after them.
+ useResult =
+ lastLocation.kind === 163 /* Parameter */ ||
+ (lastLocation === location.type &&
+ !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
+ }
+ }
+ }
+ else if (location.kind === 188 /* ConditionalType */) {
+ // A type parameter declared using 'infer T' in a conditional type is visible only in
+ // the true branch of the conditional type.
+ useResult = lastLocation === location.trueType;
+ }
+ if (useResult) {
+ break loop;
+ }
+ else {
+ result = undefined;
+ }
+ }
+ }
+ withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
+ switch (location.kind) {
+ case 303 /* SourceFile */:
+ if (!ts.isExternalOrCommonJsModule(location))
+ break;
+ isInExternalModule = true;
+ // falls through
+ case 260 /* ModuleDeclaration */:
+ var moduleExports = ((_a = getSymbolOfNode(location)) === null || _a === void 0 ? void 0 : _a.exports) || emptySymbols;
+ if (location.kind === 303 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
+ // It's an external module. First see if the module has an export default and if the local
+ // name of that export default matches.
+ if (result = moduleExports.get("default" /* Default */)) {
+ var localSymbol = ts.getLocalSymbolForExportDefault(result);
+ if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
+ break loop;
+ }
+ result = undefined;
+ }
+ // Because of module/namespace merging, a module's exports are in scope,
+ // yet we never want to treat an export specifier as putting a member in scope.
+ // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
+ // Two things to note about this:
+ // 1. We have to check this without calling getSymbol. The problem with calling getSymbol
+ // on an export specifier is that it might find the export specifier itself, and try to
+ // resolve it as an alias. This will cause the checker to consider the export specifier
+ // a circular alias reference when it might not be.
+ // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
+ // an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
+ // which is not the desired behavior.
+ var moduleExport = moduleExports.get(name);
+ if (moduleExport &&
+ moduleExport.flags === 2097152 /* Alias */ &&
+ (ts.getDeclarationOfKind(moduleExport, 274 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 273 /* NamespaceExport */))) {
+ break;
+ }
+ }
+ // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
+ if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
+ if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) === null || _b === void 0 ? void 0 : _b.some(ts.isJSDocTypeAlias))) {
+ result = undefined;
+ }
+ else {
+ break loop;
+ }
+ }
+ break;
+ case 259 /* EnumDeclaration */:
+ if (result = lookup(((_c = getSymbolOfNode(location)) === null || _c === void 0 ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */)) {
+ break loop;
+ }
+ break;
+ case 166 /* PropertyDeclaration */:
+ // TypeScript 1.0 spec (April 2014): 8.4.1
+ // Initializer expressions for instance member variables are evaluated in the scope
+ // of the class constructor body but are not permitted to reference parameters or
+ // local variables of the constructor. This effectively means that entities from outer scopes
+ // by the same name as a constructor parameter or local variable are inaccessible
+ // in initializer expressions for instance member variables.
+ if (!ts.isStatic(location)) {
+ var ctor = findConstructorDeclaration(location.parent);
+ if (ctor && ctor.locals) {
+ if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
+ // Remember the property node, it will be used later to report appropriate error
+ propertyWithInvalidInitializer = location;
+ }
+ }
+ }
+ break;
+ case 256 /* ClassDeclaration */:
+ case 225 /* ClassExpression */:
+ case 257 /* InterfaceDeclaration */:
+ // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
+ // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
+ // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
+ if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
+ if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
+ // ignore type parameters not declared in this container
+ result = undefined;
+ break;
+ }
+ if (lastLocation && ts.isStatic(lastLocation)) {
+ // TypeScript 1.0 spec (April 2014): 3.4.1
+ // The scope of a type parameter extends over the entire declaration with which the type
+ // parameter list is associated, with the exception of static member declarations in classes.
+ error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
+ return undefined;
+ }
+ break loop;
+ }
+ if (location.kind === 225 /* ClassExpression */ && meaning & 32 /* Class */) {
+ var className = location.name;
+ if (className && name === className.escapedText) {
+ result = location.symbol;
+ break loop;
+ }
+ }
+ break;
+ case 227 /* ExpressionWithTypeArguments */:
+ // The type parameters of a class are not in scope in the base class expression.
+ if (lastLocation === location.expression && location.parent.token === 94 /* ExtendsKeyword */) {
+ var container = location.parent.parent;
+ if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
+ if (nameNotFoundMessage) {
+ error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
+ }
+ return undefined;
+ }
+ }
+ break;
+ // It is not legal to reference a class's own type parameters from a computed property name that
+ // belongs to the class. For example:
+ //
+ // function foo() { return '' }
+ // class C { // <-- Class's own type parameter T
+ // [foo()]() { } // <-- Reference to T from class's own computed property
+ // }
+ //
+ case 161 /* ComputedPropertyName */:
+ grandparent = location.parent.parent;
+ if (ts.isClassLike(grandparent) || grandparent.kind === 257 /* InterfaceDeclaration */) {
+ // A reference to this grandparent's type parameters would be an error
+ if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
+ error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
+ return undefined;
+ }
+ }
+ break;
+ case 213 /* ArrowFunction */:
+ // when targeting ES6 or higher there is no 'arguments' in an arrow function
+ // for lower compile targets the resolved symbol is used to emit an error
+ if (ts.getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) {
+ break;
+ }
+ // falls through
+ case 168 /* MethodDeclaration */:
+ case 170 /* Constructor */:
+ case 171 /* GetAccessor */:
+ case 172 /* SetAccessor */:
+ case 255 /* FunctionDeclaration */:
+ if (meaning & 3 /* Variable */ && name === "arguments") {
+ result = argumentsSymbol;
+ break loop;
+ }
+ break;
+ case 212 /* FunctionExpression */:
+ if (meaning & 3 /* Variable */ && name === "arguments") {
+ result = argumentsSymbol;
+ break loop;
+ }
+ if (meaning & 16 /* Function */) {
+ var functionName = location.name;
+ if (functionName && name === functionName.escapedText) {
+ result = location.symbol;
+ break loop;
+ }
+ }
+ break;
+ case 164 /* Decorator */:
+ // Decorators are resolved at the class declaration. Resolving at the parameter
+ // or member would result in looking up locals in the method.
+ //
+ // function y() {}
+ // class C {
+ // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
+ // }
+ //
+ if (location.parent && location.parent.kind === 163 /* Parameter */) {
+ location = location.parent;
+ }
+ //
+ // function y() {}
+ // class C {
+ // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
+ // }
+ //
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 256 /* ClassDeclaration */)) {
+ location = location.parent;
+ }
+ break;
+ case 343 /* JSDocTypedefTag */:
+ case 336 /* JSDocCallbackTag */:
+ case 337 /* JSDocEnumTag */:
+ // js type aliases do not resolve names from their host, so skip past it
+ var root = ts.getJSDocRoot(location);
+ if (root) {
+ location = root.parent;
+ }
+ break;
+ case 163 /* Parameter */:
+ if (lastLocation && (lastLocation === location.initializer ||
+ lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
+ if (!associatedDeclarationForContainingInitializerOrBindingName) {
+ associatedDeclarationForContainingInitializerOrBindingName = location;
+ }
+ }
+ break;
+ case 202 /* BindingElement */:
+ if (lastLocation && (lastLocation === location.initializer ||
+ lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
+ if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) {
+ associatedDeclarationForContainingInitializerOrBindingName = location;
+ }
+ }
+ break;
+ case 189 /* InferType */:
+ if (meaning & 262144 /* TypeParameter */) {
+ var parameterName = location.typeParameter.name;
+ if (parameterName && name === parameterName.escapedText) {
+ result = location.typeParameter.symbol;
+ break loop;
+ }
+ }
+ break;
+ }
+ if (isSelfReferenceLocation(location)) {
+ lastSelfReferenceLocation = location;
+ }
+ lastLocation = location;
+ location = ts.isJSDocTemplateTag(location) ?
+ ts.getEffectiveContainerForJSDocTemplateTag(location) || location.parent :
+ location.parent;
}
- var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
- if (ambientModule) {
- return ambientModule;
+ // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
+ // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
+ // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
+ if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
+ result.isReferenced |= meaning;
}
- var currentSourceFile = ts.getSourceFileOfNode(location);
- var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
- var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
- var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
- if (sourceFile) {
- if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
- errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
+ if (!result) {
+ if (lastLocation) {
+ ts.Debug.assert(lastLocation.kind === 303 /* SourceFile */);
+ if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
+ return lastLocation.symbol;
}
- // merged symbol is module declaration symbol combined with all augmentations
- return getMergedSymbol(sourceFile.symbol);
}
- if (moduleNotFoundError) {
- // report errors only if it was requested
- error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
+ if (!excludeGlobals) {
+ result = lookup(globals, name, meaning);
}
- return undefined;
}
- if (patternAmbientModules) {
- var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
- if (pattern) {
- // If the module reference matched a pattern ambient module ('*.foo') but there's also a
- // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
- // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
- // from a.foo.
- var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
- if (augmentation) {
- return getMergedSymbol(augmentation);
+ if (!result) {
+ if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
+ if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
+ return requireSymbol;
+ }
+ }
+ }
+ if (!result) {
+ if (nameNotFoundMessage) {
+ if (!errorLocation ||
+ !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
+ !checkAndReportErrorForExtendingInterface(errorLocation) &&
+ !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
+ !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
+ !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
+ var suggestion = void 0;
+ if (suggestionCount < maximumSuggestionCount) {
+ suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
+ var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration);
+ if (isGlobalScopeAugmentationDeclaration) {
+ suggestion = undefined;
+ }
+ if (suggestion) {
+ var suggestionName = symbolToString(suggestion);
+ var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false);
+ var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1
+ : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1
+ : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1;
+ var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName);
+ addErrorOrSuggestion(!isUncheckedJS, diagnostic);
+ if (suggestion.valueDeclaration) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
+ }
+ }
+ }
+ if (!suggestion) {
+ if (nameArg) {
+ var lib = getSuggestedLibForNonExistentName(nameArg);
+ if (lib) {
+ error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib);
+ }
+ else {
+ error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
+ }
+ }
+ }
+ suggestionCount++;
}
- return getMergedSymbol(pattern.symbol);
- }
- }
- // May be an untyped module. If so, ignore resolutionDiagnostic.
- if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
- if (isForAugmentation) {
- var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
- error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
- }
- else {
- errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
}
- // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
return undefined;
}
- if (moduleNotFoundError) {
- // See if this was possibly a projectReference redirect
- if (resolvedModule) {
- var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
- if (redirect) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
- return undefined;
- }
+ // Perform extra checks only if error reporting was requested
+ if (nameNotFoundMessage) {
+ if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields)) {
+ // We have a match, but the reference occurred within a property initializer and the identifier also binds
+ // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
+ // with ESNext+useDefineForClassFields because the scope semantics are different.
+ var propertyName = propertyWithInvalidInitializer.name;
+ error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
+ return undefined;
}
- if (resolutionDiagnostic) {
- error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
+ // Only check for block-scoped variable if we have an error location and are looking for the
+ // name with variable meaning
+ // For example,
+ // declare module foo {
+ // interface bar {}
+ // }
+ // const foo/*1*/: foo/*2*/.bar;
+ // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
+ // block-scoped variable and namespace module. However, only when we
+ // try to resolve name in /*1*/ which is used in variable position,
+ // we want to check for block-scoped
+ if (errorLocation &&
+ (meaning & 2 /* BlockScopedVariable */ ||
+ ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
+ var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
+ if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
+ checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
+ }
}
- else {
- var tsExtension = ts.tryExtractTSExtension(moduleReference);
- if (tsExtension) {
- var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
- error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
+ // If we're in an external module, we can't reference value symbols created from UMD export declarations
+ if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
+ var merged = getMergedSymbol(result);
+ if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
+ errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name));
}
- else if (!compilerOptions.resolveJsonModule &&
- ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
- ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
- ts.hasJsonModuleEmitEnabled(compilerOptions)) {
- error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
+ }
+ // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right
+ if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
+ var candidate = getMergedSymbol(getLateBoundSymbol(result));
+ var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
+ // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
+ if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
+ error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
}
- else {
- error(errorNode, moduleNotFoundError, moduleReference);
+ // And it cannot refer to any declarations which come after it
+ else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
+ error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
}
}
+ if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
+ checkSymbolUsageInExpressionContext(result, name, errorLocation);
+ }
}
- return undefined;
+ return result;
}
- function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
- var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
- var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
- ? typesPackageExists(packageId.name)
- ? ts.chainDiagnosticMessages(
- /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name))
- : ts.chainDiagnosticMessages(
- /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
- : undefined;
- errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
+ function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
+ if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
+ var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
+ if (typeOnlyDeclaration) {
+ var message = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */
+ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
+ : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
+ var unescapedName = ts.unescapeLeadingUnderscores(name);
+ addTypeOnlyDeclarationRelatedInfo(error(useSite, message, unescapedName), typeOnlyDeclaration, unescapedName);
+ }
+ }
}
- function typesPackageExists(packageName) {
- return getPackagesSet().has(ts.getTypesPackageName(packageName));
+ function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) {
+ if (!typeOnlyDeclaration)
+ return diagnostic;
+ return ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 274 /* ExportSpecifier */ ? ts.Diagnostics._0_was_exported_here : ts.Diagnostics._0_was_imported_here, unescapedName));
}
- function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
- if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
- var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
- var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
- return getMergedSymbol(exported) || moduleSymbol;
+ function getIsDeferredContext(location, lastLocation) {
+ if (location.kind !== 213 /* ArrowFunction */ && location.kind !== 212 /* FunctionExpression */) {
+ // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
+ return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
+ (location.kind === 166 /* PropertyDeclaration */ && !ts.isStatic(location))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
}
- return undefined;
- }
- function getCommonJsExportEquals(exported, moduleSymbol) {
- if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
- return exported;
+ if (lastLocation && lastLocation === location.name) {
+ return false;
}
- var links = getSymbolLinks(exported);
- if (links.cjsExportMerged) {
- return links.cjsExportMerged;
+ // generator functions and async functions are not inlined in control flow when immediately invoked
+ if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* Async */)) {
+ return true;
}
- var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
- merged.flags = merged.flags | 512 /* ValueModule */;
- if (merged.exports === undefined) {
- merged.exports = ts.createSymbolTable();
+ return !ts.getImmediatelyInvokedFunctionExpression(location);
+ }
+ function isSelfReferenceLocation(node) {
+ switch (node.kind) {
+ case 255 /* FunctionDeclaration */:
+ case 256 /* ClassDeclaration */:
+ case 257 /* InterfaceDeclaration */:
+ case 259 /* EnumDeclaration */:
+ case 258 /* TypeAliasDeclaration */:
+ case 260 /* ModuleDeclaration */: // For `namespace N { N; }`
+ return true;
+ default:
+ return false;
}
- moduleSymbol.exports.forEach(function (s, name) {
- if (name === "export=" /* ExportEquals */)
- return;
- merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
- });
- getSymbolLinks(merged).cjsExportMerged = merged;
- return links.cjsExportMerged = merged;
}
- // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
- // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
- // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
- function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
- var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
- if (!dontResolveAlias && symbol) {
- if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
- var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
- ? "allowSyntheticDefaultImports"
- : "esModuleInterop";
- error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
- return symbol;
- }
- if (compilerOptions.esModuleInterop) {
- var referenceParent = referencingLocation.parent;
- if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
- ts.isImportCall(referenceParent)) {
- var type = getTypeOfSymbol(symbol);
- var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
- if (!sigs || !sigs.length) {
- sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
- }
- if (sigs && sigs.length) {
- var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
- // Create a new symbol which has the module's type less the call and construct signatures
- var result = createSymbol(symbol.flags, symbol.escapedName);
- result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
- result.parent = symbol.parent;
- result.target = symbol;
- result.originatingImport = referenceParent;
- if (symbol.valueDeclaration)
- result.valueDeclaration = symbol.valueDeclaration;
- if (symbol.constEnumOnlyModule)
- result.constEnumOnlyModule = true;
- if (symbol.members)
- result.members = ts.cloneMap(symbol.members);
- if (symbol.exports)
- result.exports = ts.cloneMap(symbol.exports);
- var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
- result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
- return result;
+ function diagnosticName(nameArg) {
+ return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
+ }
+ function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
+ if (symbol.declarations) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.kind === 162 /* TypeParameter */) {
+ var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
+ if (parent === container) {
+ return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
}
}
}
}
- return symbol;
- }
- function hasExportAssignmentSymbol(moduleSymbol) {
- return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
- }
- function getExportsOfModuleAsArray(moduleSymbol) {
- return symbolsToArray(getExportsOfModule(moduleSymbol));
+ return false;
}
- function getExportsAndPropertiesOfModule(moduleSymbol) {
- var exports = getExportsOfModuleAsArray(moduleSymbol);
- var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
- if (exportEquals !== moduleSymbol) {
- ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
+ function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
+ if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
+ return false;
}
- return exports;
- }
- function tryGetMemberInModuleExports(memberName, moduleSymbol) {
- var symbolTable = getExportsOfModule(moduleSymbol);
- if (symbolTable) {
- return symbolTable.get(memberName);
+ var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
+ var location = container;
+ while (location) {
+ if (ts.isClassLike(location.parent)) {
+ var classSymbol = getSymbolOfNode(location.parent);
+ if (!classSymbol) {
+ break;
+ }
+ // Check to see if a static member exists.
+ var constructorType = getTypeOfSymbol(classSymbol);
+ if (getPropertyOfType(constructorType, name)) {
+ error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
+ return true;
+ }
+ // No static member is present.
+ // Check if we're in an instance method and look for a relevant instance member.
+ if (location === container && !ts.isStatic(location)) {
+ var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
+ if (getPropertyOfType(instanceType, name)) {
+ error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
+ return true;
+ }
+ }
+ }
+ location = location.parent;
}
+ return false;
}
- function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
- var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
- if (symbol) {
- return symbol;
- }
- var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
- if (exportEquals === moduleSymbol) {
- return undefined;
+ function checkAndReportErrorForExtendingInterface(errorLocation) {
+ var expression = getEntityNameForExtendingInterface(errorLocation);
+ if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
+ error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
+ return true;
}
- var type = getTypeOfSymbol(exportEquals);
- return type.flags & 131068 /* Primitive */ ||
- ts.getObjectFlags(type) & 1 /* Class */ ||
- isArrayOrTupleLikeType(type)
- ? undefined
- : getPropertyOfType(type, memberName);
- }
- function getExportsOfSymbol(symbol) {
- return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
- symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
- symbol.exports || emptySymbols;
- }
- function getExportsOfModule(moduleSymbol) {
- var links = getSymbolLinks(moduleSymbol);
- return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
+ return false;
}
/**
- * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
- * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
+ * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
+ * but returns undefined if that expression is not an EntityNameExpression.
*/
- function extendExportSymbols(target, source, lookupTable, exportNode) {
- if (!source)
- return;
- source.forEach(function (sourceSymbol, id) {
- if (id === "default" /* Default */)
- return;
- var targetSymbol = target.get(id);
- if (!targetSymbol) {
- target.set(id, sourceSymbol);
- if (lookupTable && exportNode) {
- lookupTable.set(id, {
- specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
- });
- }
- }
- else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
- var collisionTracker = lookupTable.get(id);
- if (!collisionTracker.exportsWithDuplicate) {
- collisionTracker.exportsWithDuplicate = [exportNode];
- }
- else {
- collisionTracker.exportsWithDuplicate.push(exportNode);
+ function getEntityNameForExtendingInterface(node) {
+ switch (node.kind) {
+ case 79 /* Identifier */:
+ case 205 /* PropertyAccessExpression */:
+ return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
+ case 227 /* ExpressionWithTypeArguments */:
+ if (ts.isEntityNameExpression(node.expression)) {
+ return node.expression;
}
- }
- });
+ // falls through
+ default:
+ return undefined;
+ }
}
- function getExportsOfModuleWorker(moduleSymbol) {
- var visitedSymbols = [];
- // A module defined by an 'export=' consists of one export that needs to be resolved
- moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
- return visit(moduleSymbol) || emptySymbols;
- // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
- // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
- function visit(symbol) {
- if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
- return;
- }
- var symbols = ts.cloneMap(symbol.exports);
- // All export * declarations are collected in an __export symbol by the binder
- var exportStars = symbol.exports.get("__export" /* ExportStar */);
- if (exportStars) {
- var nestedSymbols = ts.createSymbolTable();
- var lookupTable_1 = ts.createMap();
- for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
- var node = _a[_i];
- var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
- var exportedSymbols = visit(resolvedModule);
- extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
- }
- lookupTable_1.forEach(function (_a, id) {
- var exportsWithDuplicate = _a.exportsWithDuplicate;
- // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
- if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
- return;
- }
- for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
- var node = exportsWithDuplicate_1[_i];
- diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id)));
+ function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
+ var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
+ if (meaning === namespaceMeaning) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ var parent = errorLocation.parent;
+ if (symbol) {
+ if (ts.isQualifiedName(parent)) {
+ ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
+ var propName = parent.right.escapedText;
+ var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
+ if (propType) {
+ error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName));
+ return true;
}
- });
- extendExportSymbols(symbols, nestedSymbols);
+ }
+ error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
+ return true;
}
- return symbols;
}
+ return false;
}
- function getMergedSymbol(symbol) {
- var merged;
- return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
- }
- function getSymbolOfNode(node) {
- return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
}
- function getParentOfSymbol(symbol) {
- return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
+ function isPrimitiveTypeName(name) {
+ return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
}
- function getAlternativeContainingModules(symbol, enclosingDeclaration) {
- var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
- var id = "" + getNodeId(containingFile);
- var links = getSymbolLinks(symbol);
- var results;
- if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
- return results;
+ function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
+ if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 274 /* ExportSpecifier */) {
+ error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
+ return true;
}
- if (containingFile && containingFile.imports) {
- // Try to make an import using an import already in the enclosing file, if possible
- for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
- var importRef = _a[_i];
- if (ts.nodeIsSynthesized(importRef))
- continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
- var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
- if (!resolvedModule)
- continue;
- var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
- if (!ref)
- continue;
- results = ts.append(results, resolvedModule);
+ return false;
+ }
+ function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
+ if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
+ if (isPrimitiveTypeName(name)) {
+ error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
+ return true;
}
- if (ts.length(results)) {
- (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
- return results;
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
+ var rawName = ts.unescapeLeadingUnderscores(name);
+ if (isES2015OrLaterConstructorName(name)) {
+ error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName);
+ }
+ else if (maybeMappedType(errorLocation, symbol)) {
+ error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K");
+ }
+ else {
+ error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
+ }
+ return true;
}
}
- if (links.extendedContainers) {
- return links.extendedContainers;
+ return false;
+ }
+ function maybeMappedType(node, symbol) {
+ var container = ts.findAncestor(node.parent, function (n) {
+ return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit";
+ });
+ if (container && container.members.length === 1) {
+ var type = getDeclaredTypeOfSymbol(symbol);
+ return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true);
}
- // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
- var otherFiles = host.getSourceFiles();
- for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
- var file = otherFiles_1[_b];
- if (!ts.isExternalModule(file))
- continue;
- var sym = getSymbolOfNode(file);
- var ref = getAliasForSymbolInContainer(sym, symbol);
- if (!ref)
- continue;
- results = ts.append(results, sym);
+ return false;
+ }
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
}
- return links.extendedContainers = results || ts.emptyArray;
+ return false;
}
- /**
- * Attempts to find the symbol corresponding to the container a symbol is in - usually this
- * is just its' `.parent`, but for locals, this value is `undefined`
- */
- function getContainersOfSymbol(symbol, enclosingDeclaration) {
- var container = getParentOfSymbol(symbol);
- // Type parameters end up in the `members` lists but are not externally visible
- if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
- var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
- var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
- if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
- return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
+ function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
+ if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol) {
+ error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
+ return true;
}
- var res = ts.append(additionalContainers, container);
- return ts.concatenate(res, reexportContainers);
}
- var candidates = ts.mapDefined(symbol.declarations, function (d) {
- if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
- return getSymbolOfNode(d.parent);
- }
- if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
- if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
- return getSymbolOfNode(ts.getSourceFileOfNode(d));
- }
- checkExpressionCached(d.parent.left.expression);
- return getNodeLinks(d.parent.left.expression).resolvedSymbol;
+ else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol) {
+ error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
+ return true;
}
- });
- if (!ts.length(candidates)) {
- return undefined;
- }
- return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
- function fileSymbolIfFileSymbolExportEqualsContainer(d) {
- return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
}
+ return false;
}
- function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
- var fileSymbol = getExternalModuleContainer(d);
- var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
- return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
- }
- function getAliasForSymbolInContainer(container, symbol) {
- if (container === getParentOfSymbol(symbol)) {
- // fast path, `symbol` is either already the alias or isn't aliased
- return symbol;
- }
- // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
- // the container itself as the alias for the symbol
- var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
- if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
- return container;
- }
- var exports = getExportsOfSymbol(container);
- var quick = exports.get(symbol.escapedName);
- if (quick && getSymbolIfSameReference(quick, symbol)) {
- return quick;
+ function checkResolvedBlockScopedVariable(result, errorLocation) {
+ var _a;
+ ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
+ if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
+ // constructor functions aren't block scoped
+ return;
}
- return ts.forEachEntry(exports, function (exported) {
- if (getSymbolIfSameReference(exported, symbol)) {
- return exported;
+ // Block-scoped variables cannot be used before their definition
+ var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 259 /* EnumDeclaration */); });
+ if (declaration === undefined)
+ return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
+ if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
+ var diagnosticMessage = void 0;
+ var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
+ if (result.flags & 2 /* BlockScopedVariable */) {
+ diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
}
- });
- }
- /**
- * Checks if two symbols, through aliasing and/or merging, refer to the same thing
- */
- function getSymbolIfSameReference(s1, s2) {
- if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
- return s1;
- }
- }
- function getExportSymbolOfValueSymbolIfExported(symbol) {
- return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
- }
- function symbolIsValue(symbol) {
- return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
- }
- function findConstructorDeclaration(node) {
- var members = node.members;
- for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
- var member = members_3[_i];
- if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
- return member;
+ else if (result.flags & 32 /* Class */) {
+ diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
+ }
+ else if (result.flags & 256 /* RegularEnum */) {
+ diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
+ }
+ else {
+ ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
+ if (ts.shouldPreserveConstEnums(compilerOptions)) {
+ diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
+ }
+ }
+ if (diagnosticMessage) {
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
- function createType(flags) {
- var result = new Type(checker, flags);
- typeCount++;
- result.id = typeCount;
- return result;
+ /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
+ * If at any point current node is equal to 'parent' node - return true.
+ * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
+ */
+ function isSameScopeDescendentOf(initial, parent, stopAt) {
+ return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
}
- function createIntrinsicType(kind, intrinsicName, objectFlags) {
- if (objectFlags === void 0) { objectFlags = 0; }
- var type = createType(kind);
- type.intrinsicName = intrinsicName;
- type.objectFlags = objectFlags;
- return type;
+ function getAnyImportSyntax(node) {
+ switch (node.kind) {
+ case 264 /* ImportEqualsDeclaration */:
+ return node;
+ case 266 /* ImportClause */:
+ return node.parent;
+ case 267 /* NamespaceImport */:
+ return node.parent.parent;
+ case 269 /* ImportSpecifier */:
+ return node.parent.parent.parent;
+ default:
+ return undefined;
+ }
}
- function createBooleanType(trueFalseTypes) {
- var type = getUnionType(trueFalseTypes);
- type.flags |= 16 /* Boolean */;
- type.intrinsicName = "boolean";
- return type;
+ function getDeclarationOfAliasSymbol(symbol) {
+ return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration);
}
- function createObjectType(objectFlags, symbol) {
- var type = createType(524288 /* Object */);
- type.objectFlags = objectFlags;
- type.symbol = symbol;
- type.members = undefined;
- type.properties = undefined;
- type.callSignatures = undefined;
- type.constructSignatures = undefined;
- type.stringIndexInfo = undefined;
- type.numberIndexInfo = undefined;
- return type;
+ /**
+ * An alias symbol is created by one of the following declarations:
+ * import